2 * Copyright (C) 2009 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22 #define _GNU_SOURCE /* for vasprintf, GNU strerror_r, strchrnul */
34 #include <sys/select.h>
37 #include <rpc/types.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
48 #ifdef HAVE_SYS_WAIT_H
52 #ifdef HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
61 #include "guestfs_protocol.h"
65 #define _(str) dgettext(PACKAGE, (str))
66 #define N_(str) dgettext(PACKAGE, (str))
72 #define error guestfs_error
73 #define perrorf guestfs_perrorf
74 #define safe_malloc guestfs_safe_malloc
75 #define safe_realloc guestfs_safe_realloc
76 #define safe_strdup guestfs_safe_strdup
77 #define safe_memdup guestfs_safe_memdup
79 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
80 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
81 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
82 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
84 static void close_handles (void);
86 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
87 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
88 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
89 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
90 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
91 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
93 /* Default select-based main loop. */
94 struct select_handle_cb_data {
95 guestfs_handle_event_cb cb;
100 struct select_main_loop {
101 /* NB. These fields must be the same as in struct guestfs_main_loop: */
102 guestfs_add_handle_cb add_handle;
103 guestfs_remove_handle_cb remove_handle;
104 guestfs_add_timeout_cb add_timeout;
105 guestfs_remove_timeout_cb remove_timeout;
106 guestfs_main_loop_run_cb main_loop_run;
107 guestfs_main_loop_quit_cb main_loop_quit;
109 /* Additional private data: */
118 struct select_handle_cb_data *handle_cb_data;
121 /* Default main loop. */
122 static struct select_main_loop default_main_loop = {
123 .add_handle = select_add_handle,
124 .remove_handle = select_remove_handle,
125 .add_timeout = select_add_timeout,
126 .remove_timeout = select_remove_timeout,
127 .main_loop_run = select_main_loop_run,
128 .main_loop_quit = select_main_loop_quit,
130 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
131 * set by the normal action of everything being initialized to zero.
136 .handle_cb_data = NULL,
139 #define UNIX_PATH_MAX 108
141 /* Also in guestfsd.c */
142 #define VMCHANNEL_PORT 6666
143 #define VMCHANNEL_ADDR "10.0.2.4"
145 /* GuestFS handle and connection. */
146 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
150 struct guestfs_h *next; /* Linked list of open handles. */
152 /* State: see the state machine diagram in the man page guestfs(3). */
155 int fd[2]; /* Stdin/stdout of qemu. */
156 int sock; /* Daemon communications socket. */
157 pid_t pid; /* Qemu PID. */
158 pid_t recoverypid; /* Recovery process PID. */
159 time_t start_t; /* The time when we started qemu. */
161 int stdout_watch; /* Watches qemu stdout for log messages. */
162 int sock_watch; /* Watches daemon comm socket. */
164 char *tmpdir; /* Temporary directory containing socket. */
166 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
168 char **cmdline; /* Qemu command line. */
174 char *path; /* Path to kernel, initrd. */
175 char *qemu; /* Qemu binary. */
176 char *append; /* Append to kernel command line. */
178 int memsize; /* Size of RAM (megabytes). */
183 guestfs_abort_cb abort_cb;
184 guestfs_error_handler_cb error_cb;
185 void * error_cb_data;
186 guestfs_send_cb send_cb;
188 guestfs_reply_cb reply_cb;
189 void * reply_cb_data;
190 guestfs_log_message_cb log_message_cb;
191 void * log_message_cb_data;
192 guestfs_subprocess_quit_cb subprocess_quit_cb;
193 void * subprocess_quit_cb_data;
194 guestfs_launch_done_cb launch_done_cb;
195 void * launch_done_cb_data;
197 /* Main loop used by this handle. */
198 guestfs_main_loop *main_loop;
200 /* Messages sent and received from the daemon. */
202 int msg_in_size, msg_in_allocated;
204 int msg_out_size, msg_out_pos;
209 static guestfs_h *handles = NULL;
210 static int atexit_handler_set = 0;
213 guestfs_create (void)
218 g = malloc (sizeof (*g));
221 memset (g, 0, sizeof (*g));
228 g->stdout_watch = -1;
232 g->error_cb = default_error_cb;
233 g->error_cb_data = NULL;
235 str = getenv ("LIBGUESTFS_DEBUG");
236 g->verbose = str != NULL && strcmp (str, "1") == 0;
238 str = getenv ("LIBGUESTFS_PATH");
239 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
240 if (!g->path) goto error;
242 str = getenv ("LIBGUESTFS_QEMU");
243 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
244 if (!g->qemu) goto error;
246 str = getenv ("LIBGUESTFS_APPEND");
248 g->append = strdup (str);
249 if (!g->append) goto error;
252 /* Choose a suitable memory size. Previously we tried to choose
253 * a minimal memory size, but this isn't really necessary since
254 * recent QEMU and KVM don't do anything nasty like locking
255 * memory into core any more. Thus we can safely choose a
256 * large, generous amount of memory, and it'll just get swapped
257 * on smaller systems.
259 str = getenv ("LIBGUESTFS_MEMSIZE");
261 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
262 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
268 g->main_loop = guestfs_get_default_main_loop ();
270 /* Start with large serial numbers so they are easy to spot
271 * inside the protocol.
273 g->msg_next_serial = 0x00123400;
275 /* Link the handles onto a global list. This is the one area
276 * where the library needs to be made thread-safe. (XXX)
278 /* acquire mutex (XXX) */
281 if (!atexit_handler_set) {
282 atexit (close_handles);
283 atexit_handler_set = 1;
285 /* release mutex (XXX) */
288 fprintf (stderr, "new guestfs handle %p\n", g);
301 guestfs_close (guestfs_h *g)
307 if (g->state == NO_HANDLE) {
308 /* Not safe to call 'error' here, so ... */
309 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
314 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
316 /* Try to sync if autosync flag is set. */
317 if (g->autosync && g->state == READY) {
318 guestfs_umount_all (g);
322 /* Remove any handlers that might be called back before we kill the
325 g->log_message_cb = NULL;
327 if (g->state != CONFIG)
328 guestfs_kill_subprocess (g);
330 /* Close any sockets and deregister any handlers. */
331 if (g->stdout_watch >= 0)
332 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
333 if (g->sock_watch >= 0)
334 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
335 g->stdout_watch = -1;
348 /* Remove tmpfiles. */
350 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
353 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
356 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
365 for (i = 0; i < g->cmdline_size; ++i)
366 free (g->cmdline[i]);
370 /* Mark the handle as dead before freeing it. */
371 g->state = NO_HANDLE;
373 /* acquire mutex (XXX) */
377 for (gg = handles; gg->next != g; gg = gg->next)
381 /* release mutex (XXX) */
385 free (g->last_error);
390 free (g->qemu_version);
394 /* Close all open handles (called from atexit(3)). */
398 while (handles) guestfs_close (handles);
402 guestfs_last_error (guestfs_h *g)
404 return g->last_error;
408 set_last_error (guestfs_h *g, const char *msg)
410 free (g->last_error);
411 g->last_error = strdup (msg);
415 default_error_cb (guestfs_h *g, void *data, const char *msg)
417 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
421 guestfs_error (guestfs_h *g, const char *fs, ...)
427 int err = vasprintf (&msg, fs, args);
432 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
433 set_last_error (g, msg);
439 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
446 vasprintf (&msg, fs, args);
451 strerror_r (err, buf, sizeof buf);
455 buf = strerror_r (err, _buf, sizeof _buf);
458 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
462 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
463 set_last_error (g, msg);
469 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
471 void *ptr = malloc (nbytes);
472 if (nbytes > 0 && !ptr) g->abort_cb ();
476 /* Return 1 if an array of N objects, each of size S, cannot exist due
477 to size arithmetic overflow. S must be positive and N must be
478 nonnegative. This is a macro, not an inline function, so that it
479 works correctly even when SIZE_MAX < N.
481 By gnulib convention, SIZE_MAX represents overflow in size
482 calculations, so the conservative dividend to use here is
483 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
484 However, malloc (SIZE_MAX) fails on all known hosts where
485 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
486 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
487 branch when S is known to be 1. */
488 # define xalloc_oversized(n, s) \
489 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
491 /* Technically we should add an autoconf test for this, testing for the desired
492 functionality, like what's done in gnulib, but for now, this is fine. */
493 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
495 /* Allocate zeroed memory for N elements of S bytes, with error
496 checking. S must be nonzero. */
498 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
500 /* From gnulib's calloc function in xmalloc.c. */
502 /* Test for overflow, since some calloc implementations don't have
503 proper overflow checks. But omit overflow and size-zero tests if
504 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
505 returns NULL if successful. */
506 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
507 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
513 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
515 void *p = realloc (ptr, nbytes);
516 if (nbytes > 0 && !p) g->abort_cb ();
521 guestfs_safe_strdup (guestfs_h *g, const char *str)
523 char *s = strdup (str);
524 if (!s) g->abort_cb ();
529 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
531 void *p = malloc (size);
532 if (!p) g->abort_cb ();
533 memcpy (p, ptr, size);
538 xwrite (int fd, const void *buf, size_t len)
543 r = write (fd, buf, len);
555 xread (int fd, void *buf, size_t len)
560 r = read (fd, buf, len);
562 if (errno == EINTR || errno == EAGAIN)
575 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
581 guestfs_get_out_of_memory_handler (guestfs_h *g)
587 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
590 g->error_cb_data = data;
593 guestfs_error_handler_cb
594 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
596 if (data_rtn) *data_rtn = g->error_cb_data;
601 guestfs_set_verbose (guestfs_h *g, int v)
608 guestfs_get_verbose (guestfs_h *g)
614 guestfs_set_autosync (guestfs_h *g, int a)
621 guestfs_get_autosync (guestfs_h *g)
627 guestfs_set_path (guestfs_h *g, const char *path)
634 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
639 guestfs_get_path (guestfs_h *g)
645 guestfs_set_qemu (guestfs_h *g, const char *qemu)
650 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
655 guestfs_get_qemu (guestfs_h *g)
661 guestfs_set_append (guestfs_h *g, const char *append)
666 g->append = append ? safe_strdup (g, append) : NULL;
671 guestfs_get_append (guestfs_h *g)
677 guestfs_set_memsize (guestfs_h *g, int memsize)
679 g->memsize = memsize;
684 guestfs_get_memsize (guestfs_h *g)
690 guestfs_get_pid (guestfs_h *g)
695 error (g, "get_pid: no qemu subprocess");
700 struct guestfs_version *
701 guestfs_version (guestfs_h *g)
703 struct guestfs_version *r;
705 r = safe_malloc (g, sizeof *r);
706 r->major = PACKAGE_VERSION_MAJOR;
707 r->minor = PACKAGE_VERSION_MINOR;
708 r->release = PACKAGE_VERSION_RELEASE;
709 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
713 /* Add a string to the current command line. */
715 incr_cmdline_size (guestfs_h *g)
717 if (g->cmdline == NULL) {
718 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
720 g->cmdline = safe_malloc (g, sizeof (char *));
721 g->cmdline[0] = NULL;
725 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
729 add_cmdline (guestfs_h *g, const char *str)
731 if (g->state != CONFIG) {
733 _("command line cannot be altered after qemu subprocess launched"));
737 incr_cmdline_size (g);
738 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
743 guestfs_config (guestfs_h *g,
744 const char *qemu_param, const char *qemu_value)
746 if (qemu_param[0] != '-') {
747 error (g, _("guestfs_config: parameter must begin with '-' character"));
751 /* A bit fascist, but the user will probably break the extra
752 * parameters that we add if they try to set any of these.
754 if (strcmp (qemu_param, "-kernel") == 0 ||
755 strcmp (qemu_param, "-initrd") == 0 ||
756 strcmp (qemu_param, "-nographic") == 0 ||
757 strcmp (qemu_param, "-serial") == 0 ||
758 strcmp (qemu_param, "-full-screen") == 0 ||
759 strcmp (qemu_param, "-std-vga") == 0 ||
760 strcmp (qemu_param, "-vnc") == 0) {
761 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
765 if (add_cmdline (g, qemu_param) != 0) return -1;
767 if (qemu_value != NULL) {
768 if (add_cmdline (g, qemu_value) != 0) return -1;
775 guestfs_add_drive (guestfs_h *g, const char *filename)
777 size_t len = strlen (filename) + 64;
780 if (strchr (filename, ',') != NULL) {
781 error (g, _("filename cannot contain ',' (comma) character"));
785 if (access (filename, F_OK) == -1) {
786 perrorf (g, "%s", filename);
790 /* cache=off improves reliability in the event of a host crash. */
791 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, DRIVE_IF);
793 return guestfs_config (g, "-drive", buf);
797 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
799 size_t len = strlen (filename) + 64;
802 if (strchr (filename, ',') != NULL) {
803 error (g, _("filename cannot contain ',' (comma) character"));
807 if (access (filename, F_OK) == -1) {
808 perrorf (g, "%s", filename);
812 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
814 return guestfs_config (g, "-drive", buf);
818 guestfs_add_cdrom (guestfs_h *g, const char *filename)
820 if (strchr (filename, ',') != NULL) {
821 error (g, _("filename cannot contain ',' (comma) character"));
825 if (access (filename, F_OK) == -1) {
826 perrorf (g, "%s", filename);
830 return guestfs_config (g, "-cdrom", filename);
833 /* Returns true iff file is contained in dir. */
835 dir_contains_file (const char *dir, const char *file)
837 int dirlen = strlen (dir);
838 int filelen = strlen (file);
839 int len = dirlen+filelen+2;
842 snprintf (path, len, "%s/%s", dir, file);
843 return access (path, F_OK) == 0;
846 /* Returns true iff every listed file is contained in 'dir'. */
848 dir_contains_files (const char *dir, ...)
853 va_start (args, dir);
854 while ((file = va_arg (args, const char *)) != NULL) {
855 if (!dir_contains_file (dir, file)) {
864 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
865 static int test_qemu (guestfs_h *g);
866 static int qemu_supports (guestfs_h *g, const char *option);
868 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
869 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
870 static const char *supermin_name =
871 "initramfs." REPO "." host_cpu ".supermin.img";
872 static const char *supermin_hostfiles_name =
873 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
876 guestfs_launch (guestfs_h *g)
879 char dir_template[PATH_MAX];
884 char *path, *pelem, *pend;
885 char *kernel = NULL, *initrd = NULL;
887 struct sockaddr_un addr;
895 tmpdir = getenv ("TMPDIR") ? : tmpdir;
896 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
900 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
904 if (g->state != CONFIG) {
905 error (g, _("qemu has already been launched"));
909 /* Make the temporary directory. */
911 g->tmpdir = safe_strdup (g, dir_template);
912 if (mkdtemp (g->tmpdir) == NULL) {
913 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
918 /* First search g->path for the supermin appliance, and try to
919 * synthesize a kernel and initrd from that. If it fails, we
920 * try the path search again looking for a backup ordinary
923 pelem = path = safe_strdup (g, g->path);
925 pend = strchrnul (pelem, ':');
926 pmore = *pend == ':';
930 /* Empty element of "." means cwd. */
931 if (len == 0 || (len == 1 && *pelem == '.')) {
934 "looking for supermin appliance in current directory\n");
935 if (dir_contains_files (".",
936 supermin_name, supermin_hostfiles_name,
937 "kmod.whitelist", NULL)) {
938 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
943 /* Look at <path>/supermin* etc. */
946 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
948 if (dir_contains_files (pelem,
949 supermin_name, supermin_hostfiles_name,
950 "kmod.whitelist", NULL)) {
951 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
962 if (kernel == NULL || initrd == NULL) {
963 /* Search g->path for the kernel and initrd. */
964 pelem = path = safe_strdup (g, g->path);
966 pend = strchrnul (pelem, ':');
967 pmore = *pend == ':';
971 /* Empty element or "." means cwd. */
972 if (len == 0 || (len == 1 && *pelem == '.')) {
975 "looking for appliance in current directory\n");
976 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
977 kernel = safe_strdup (g, kernel_name);
978 initrd = safe_strdup (g, initrd_name);
982 /* Look at <path>/kernel etc. */
985 fprintf (stderr, "looking for appliance in %s\n", pelem);
987 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
988 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
989 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
990 sprintf (kernel, "%s/%s", pelem, kernel_name);
991 sprintf (initrd, "%s/%s", pelem, initrd_name);
1002 if (kernel == NULL || initrd == NULL) {
1003 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1004 kernel_name, initrd_name, g->path);
1008 /* Get qemu help text and version. */
1009 if (test_qemu (g) == -1)
1012 /* Make the vmchannel socket. */
1013 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1016 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1017 perrorf (g, "pipe");
1023 perrorf (g, "fork");
1031 if (r == 0) { /* Child (qemu). */
1032 char vmchannel[256];
1034 char memsize_str[256];
1036 /* Set up the full command line. Do this in the subprocess so we
1037 * don't need to worry about cleaning up.
1039 g->cmdline[0] = g->qemu;
1041 #define LINUX_CMDLINE \
1042 "panic=1 " /* force kernel to panic if daemon exits */ \
1043 "console=ttyS0 " /* serial console */ \
1044 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1045 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1046 "acpi=off " /* we don't need ACPI, turn it off */ \
1047 "cgroup_disable=memory " /* saves us about 5 MB of RAM */ \
1048 "selinux=0 " /* SELinux is messed up if there's no policy */
1050 /* Linux kernel command line. */
1051 snprintf (append, sizeof append,
1052 LINUX_CMDLINE "guestfs=%s:%d%s%s%s",
1053 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1054 g->verbose ? " guestfs_verbose=1" : "",
1055 g->append ? " " : "", g->append ? g->append : "");
1057 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1059 add_cmdline (g, "-m");
1060 add_cmdline (g, memsize_str);
1061 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1062 add_cmdline (g, "-kernel");
1063 add_cmdline (g, (char *) kernel);
1064 add_cmdline (g, "-initrd");
1065 add_cmdline (g, (char *) initrd);
1066 add_cmdline (g, "-append");
1067 add_cmdline (g, append);
1068 add_cmdline (g, "-nographic");
1069 add_cmdline (g, "-serial");
1070 add_cmdline (g, "stdio");
1073 /* Doesn't work. See:
1074 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1075 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1077 if (qemu_supports (g, "guestfwd")) {
1078 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1079 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1081 snprintf (vmchannel, sizeof vmchannel,
1082 "user,vlan=0,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1083 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1085 add_cmdline (g, "-net");
1086 add_cmdline (g, vmchannel);
1089 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1090 * syntax, or if not then we'll get a quick failure.
1092 snprintf (vmchannel, sizeof vmchannel,
1093 "channel,%d:unix:%s,server,nowait",
1094 VMCHANNEL_PORT, unixsock);
1096 add_cmdline (g, "-net");
1097 add_cmdline (g, vmchannel);
1098 add_cmdline (g, "-net");
1099 add_cmdline (g, "user,vlan=0");
1103 add_cmdline (g, "-net");
1104 add_cmdline (g, "nic,model=virtio,vlan=0");
1106 /* These options recommended by KVM developers to improve reliability. */
1107 if (qemu_supports (g, "-no-hpet"))
1108 add_cmdline (g, "-no-hpet");
1110 if (qemu_supports (g, "-rtc-td-hack"))
1111 add_cmdline (g, "-rtc-td-hack");
1113 /* Finish off the command line. */
1114 incr_cmdline_size (g);
1115 g->cmdline[g->cmdline_size-1] = NULL;
1118 fprintf (stderr, "%s", g->qemu);
1119 for (i = 0; g->cmdline[i]; ++i)
1120 fprintf (stderr, " %s", g->cmdline[i]);
1121 fprintf (stderr, "\n");
1124 /* Set up stdin, stdout. */
1135 /* Set up a new process group, so we can signal this process
1136 * and all subprocesses (eg. if qemu is really a shell script).
1141 execv (g->qemu, g->cmdline); /* Run qemu. */
1146 /* Parent (library). */
1154 /* Fork the recovery process off which will kill qemu if the parent
1155 * process fails to do so (eg. if the parent segfaults).
1159 pid_t qemu_pid = g->pid;
1160 pid_t parent_pid = getppid ();
1162 /* Writing to argv is hideously complicated and error prone. See:
1163 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1166 /* Loop around waiting for one or both of the other processes to
1167 * disappear. It's fair to say this is very hairy. The PIDs that
1168 * we are looking at might be reused by another process. We are
1169 * effectively polling. Is the cure worse than the disease?
1172 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1174 if (kill (parent_pid, 0) == -1) {
1175 /* Parent's gone away, qemu still around, so kill qemu. */
1183 /* Don't worry, if the fork failed, this will be -1. The recovery
1184 * process isn't essential.
1188 /* Start the clock ... */
1191 /* Close the other ends of the pipe. */
1195 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1196 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1197 perrorf (g, "fcntl");
1201 g->fd[0] = wfd[1]; /* stdin of child */
1202 g->fd[1] = rfd[0]; /* stdout of child */
1204 /* Open the Unix socket. The vmchannel implementation that got
1205 * merged with qemu sucks in a number of ways. Both ends do
1206 * connect(2), which means that no one knows what, if anything, is
1207 * connected to the other end, or if it becomes disconnected. Even
1208 * worse, we have to wait some indeterminate time for qemu to create
1209 * the socket and connect to it (which happens very early in qemu's
1210 * start-up), so any code that uses vmchannel is inherently racy.
1211 * Hence this silly loop.
1213 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1214 if (g->sock == -1) {
1215 perrorf (g, "socket");
1219 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1220 perrorf (g, "fcntl");
1224 addr.sun_family = AF_UNIX;
1225 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1226 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1229 /* Always sleep at least once to give qemu a small chance to start up. */
1232 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1233 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1236 if (errno != ENOENT)
1237 perrorf (g, "connect");
1242 error (g, _("failed to connect to vmchannel socket"));
1246 /* Watch the file descriptors. */
1249 g->msg_in_size = g->msg_in_allocated = 0;
1253 g->msg_out_size = 0;
1257 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1258 GUESTFS_HANDLE_READABLE,
1259 stdout_event, NULL);
1260 if (g->stdout_watch == -1) {
1261 error (g, _("could not watch qemu stdout"));
1265 if (guestfs__switch_to_receiving (g) == -1)
1268 g->state = LAUNCHING;
1272 if (g->stdout_watch >= 0)
1273 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1274 if (g->sock_watch >= 0)
1275 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1284 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1285 waitpid (g->pid, NULL, 0);
1286 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1293 g->stdout_watch = -1;
1302 /* This function does the hard work of building the supermin appliance
1303 * on the fly. 'path' is the directory containing the control files.
1304 * 'kernel' and 'initrd' are where we will return the names of the
1305 * kernel and initrd (only initrd is built). The work is done by
1306 * an external script. We just tell it where to put the result.
1309 build_supermin_appliance (guestfs_h *g, const char *path,
1310 char **kernel, char **initrd)
1315 len = strlen (g->tmpdir);
1316 *kernel = safe_malloc (g, len + 8);
1317 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1318 *initrd = safe_malloc (g, len + 8);
1319 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1321 snprintf (cmd, sizeof cmd,
1323 "libguestfs-supermin-helper '%s' %s %s",
1325 path, *kernel, *initrd);
1328 if (r == -1 || WEXITSTATUS(r) != 0) {
1329 error (g, _("external command failed: %s"), cmd);
1332 *kernel = *initrd = NULL;
1339 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1341 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1342 * 'qemu -version' so we know what options this qemu supports and
1346 test_qemu (guestfs_h *g)
1351 free (g->qemu_help);
1352 free (g->qemu_version);
1353 g->qemu_help = NULL;
1354 g->qemu_version = NULL;
1356 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1358 fp = popen (cmd, "r");
1359 /* qemu -help should always work (qemu -version OTOH wasn't
1360 * supported by qemu 0.9). If this command doesn't work then it
1361 * probably indicates that the qemu binary is missing.
1364 /* XXX This error is never printed, even if the qemu binary
1365 * doesn't exist. Why?
1368 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1372 if (read_all (g, fp, &g->qemu_help) == -1)
1375 if (pclose (fp) == -1)
1378 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1380 fp = popen (cmd, "r");
1382 /* Intentionally ignore errors. */
1383 read_all (g, fp, &g->qemu_version);
1391 read_all (guestfs_h *g, FILE *fp, char **ret)
1398 *ret = safe_realloc (g, *ret, n + 1);
1403 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1405 r = fread (p, 1, BUFSIZ, fp);
1407 perrorf (g, "read");
1414 /* Test if option is supported by qemu command line (just by grepping
1418 qemu_supports (guestfs_h *g, const char *option)
1420 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1424 finish_wait_ready (guestfs_h *g, void *vp)
1427 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1430 g->main_loop->main_loop_quit (g->main_loop, g);
1434 guestfs_wait_ready (guestfs_h *g)
1436 int finished = 0, r;
1438 if (g->state == READY) return 0;
1440 if (g->state == BUSY) {
1441 error (g, _("qemu has finished launching already"));
1445 if (g->state != LAUNCHING) {
1446 error (g, _("qemu has not been launched yet"));
1450 g->launch_done_cb = finish_wait_ready;
1451 g->launch_done_cb_data = &finished;
1452 r = g->main_loop->main_loop_run (g->main_loop, g);
1453 g->launch_done_cb = NULL;
1454 g->launch_done_cb_data = NULL;
1456 if (r == -1) return -1;
1458 if (finished != 1) {
1459 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1463 /* This is possible in some really strange situations, such as
1464 * guestfsd starts up OK but then qemu immediately exits. Check for
1465 * it because the caller is probably expecting to be able to send
1466 * commands after this function returns.
1468 if (g->state != READY) {
1469 error (g, _("qemu launched and contacted daemon, but state != READY"));
1477 guestfs_kill_subprocess (guestfs_h *g)
1479 if (g->state == CONFIG) {
1480 error (g, _("no subprocess to kill"));
1485 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1487 kill (g->pid, SIGTERM);
1488 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1493 /* Access current state. */
1495 guestfs_is_config (guestfs_h *g)
1497 return g->state == CONFIG;
1501 guestfs_is_launching (guestfs_h *g)
1503 return g->state == LAUNCHING;
1507 guestfs_is_ready (guestfs_h *g)
1509 return g->state == READY;
1513 guestfs_is_busy (guestfs_h *g)
1515 return g->state == BUSY;
1519 guestfs_get_state (guestfs_h *g)
1525 guestfs_set_ready (guestfs_h *g)
1527 if (g->state != BUSY) {
1528 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1537 guestfs_set_busy (guestfs_h *g)
1539 if (g->state != READY) {
1540 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1549 guestfs_end_busy (guestfs_h *g)
1561 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1567 /* We don't know if stdout_event or sock_read_event will be the
1568 * first to receive EOF if the qemu process dies. This function
1569 * has the common cleanup code for both.
1572 child_cleanup (guestfs_h *g)
1575 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1576 /*kill (g->pid, SIGTERM);*/
1577 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1578 waitpid (g->pid, NULL, 0);
1579 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1580 if (g->stdout_watch >= 0)
1581 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1582 if (g->sock_watch >= 0)
1583 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1593 g->stdout_watch = -1;
1596 if (g->subprocess_quit_cb)
1597 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1600 /* This function is called whenever qemu prints something on stdout.
1601 * Qemu's stdout is also connected to the guest's serial console, so
1602 * we see kernel messages here too.
1605 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1606 int watch, int fd, int events)
1614 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1615 g, g->state, fd, events);
1618 if (g->fd[1] != fd) {
1619 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1623 n = read (fd, buf, sizeof buf);
1625 /* Hopefully this indicates the qemu child process has died. */
1631 if (errno != EINTR && errno != EAGAIN)
1632 perrorf (g, "read");
1636 /* In verbose mode, copy all log messages to stderr. */
1640 /* It's an actual log message, send it upwards if anyone is listening. */
1641 if (g->log_message_cb)
1642 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1645 /* The function is called whenever we can read something on the
1646 * guestfsd (daemon inside the guest) communication socket.
1649 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1650 int watch, int fd, int events)
1658 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1659 g, g->state, fd, events);
1661 if (g->sock != fd) {
1662 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1666 if (g->msg_in_size <= g->msg_in_allocated) {
1667 g->msg_in_allocated += 4096;
1668 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1670 n = read (g->sock, g->msg_in + g->msg_in_size,
1671 g->msg_in_allocated - g->msg_in_size);
1679 if (errno != EINTR && errno != EAGAIN)
1680 perrorf (g, "read");
1684 g->msg_in_size += n;
1686 /* Have we got enough of a message to be able to process it yet? */
1688 if (g->msg_in_size < 4) return;
1690 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1691 if (!xdr_uint32_t (&xdr, &len)) {
1692 error (g, _("can't decode length word"));
1696 /* Length is normally the length of the message, but when guestfsd
1697 * starts up it sends a "magic" value (longer than any possible
1698 * message). Check for this.
1700 if (len == GUESTFS_LAUNCH_FLAG) {
1701 if (g->state != LAUNCHING)
1702 error (g, _("received magic signature from guestfsd, but in state %d"),
1704 else if (g->msg_in_size != 4)
1705 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1709 if (g->launch_done_cb)
1710 g->launch_done_cb (g, g->launch_done_cb_data);
1716 /* This can happen if a cancellation happens right at the end
1717 * of us sending a FileIn parameter to the daemon. Discard. The
1718 * daemon should send us an error message next.
1720 if (len == GUESTFS_CANCEL_FLAG) {
1721 g->msg_in_size -= 4;
1722 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1726 /* If this happens, it's pretty bad and we've probably lost
1729 if (len > GUESTFS_MESSAGE_MAX) {
1730 error (g, _("message length (%u) > maximum possible size (%d)"),
1731 len, GUESTFS_MESSAGE_MAX);
1735 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1737 /* Got the full message, begin processing it. */
1742 for (i = 0; i < g->msg_in_size; i += 16) {
1743 printf ("%04x: ", i);
1744 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1745 printf ("%02x ", (unsigned char) g->msg_in[j]);
1746 for (; j < i+16; ++j)
1749 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1750 if (isprint (g->msg_in[j]))
1751 printf ("%c", g->msg_in[j]);
1754 for (; j < i+16; ++j)
1761 /* Not in the expected state. */
1762 if (g->state != BUSY)
1763 error (g, _("state %d != BUSY"), g->state);
1765 /* Push the message up to the higher layer. */
1767 g->reply_cb (g, g->reply_cb_data, &xdr);
1769 /* This message (probably) should never be printed. */
1770 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1772 g->msg_in_size -= len + 4;
1773 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1774 if (g->msg_in_size > 0) goto again;
1777 /* Free the message buffer if it's grown excessively large. */
1778 if (g->msg_in_allocated > 65536) {
1781 g->msg_in_size = g->msg_in_allocated = 0;
1788 /* The function is called whenever we can write something on the
1789 * guestfsd (daemon inside the guest) communication socket.
1792 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1793 int watch, int fd, int events)
1799 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1800 g, g->state, fd, events);
1802 if (g->sock != fd) {
1803 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1807 if (g->state != BUSY) {
1808 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1813 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1814 g->msg_out_size - g->msg_out_pos);
1816 n = write (g->sock, g->msg_out + g->msg_out_pos,
1817 g->msg_out_size - g->msg_out_pos);
1821 perrorf (g, "write");
1822 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1828 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1830 g->msg_out_pos += n;
1832 /* More to write? */
1833 if (g->msg_out_pos < g->msg_out_size)
1837 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1841 g->msg_out_pos = g->msg_out_size = 0;
1843 /* Done writing, call the higher layer. */
1845 g->send_cb (g, g->send_cb_data);
1849 guestfs_set_send_callback (guestfs_h *g,
1850 guestfs_send_cb cb, void *opaque)
1853 g->send_cb_data = opaque;
1857 guestfs_set_reply_callback (guestfs_h *g,
1858 guestfs_reply_cb cb, void *opaque)
1861 g->reply_cb_data = opaque;
1865 guestfs_set_log_message_callback (guestfs_h *g,
1866 guestfs_log_message_cb cb, void *opaque)
1868 g->log_message_cb = cb;
1869 g->log_message_cb_data = opaque;
1873 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1874 guestfs_subprocess_quit_cb cb, void *opaque)
1876 g->subprocess_quit_cb = cb;
1877 g->subprocess_quit_cb_data = opaque;
1881 guestfs_set_launch_done_callback (guestfs_h *g,
1882 guestfs_launch_done_cb cb, void *opaque)
1884 g->launch_done_cb = cb;
1885 g->launch_done_cb_data = opaque;
1888 /* Access to the handle's main loop and the default main loop. */
1890 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1892 g->main_loop = main_loop;
1896 guestfs_get_main_loop (guestfs_h *g)
1898 return g->main_loop;
1902 guestfs_get_default_main_loop (void)
1904 return (guestfs_main_loop *) &default_main_loop;
1907 /* Change the daemon socket handler so that we are now writing.
1908 * This sets the handle to sock_write_event.
1911 guestfs__switch_to_sending (guestfs_h *g)
1913 if (g->sock_watch >= 0) {
1914 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1915 error (g, _("remove_handle failed"));
1922 g->main_loop->add_handle (g->main_loop, g, g->sock,
1923 GUESTFS_HANDLE_WRITABLE,
1924 sock_write_event, NULL);
1925 if (g->sock_watch == -1) {
1926 error (g, _("add_handle failed"));
1934 guestfs__switch_to_receiving (guestfs_h *g)
1936 if (g->sock_watch >= 0) {
1937 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1938 error (g, _("remove_handle failed"));
1945 g->main_loop->add_handle (g->main_loop, g, g->sock,
1946 GUESTFS_HANDLE_READABLE,
1947 sock_read_event, NULL);
1948 if (g->sock_watch == -1) {
1949 error (g, _("add_handle failed"));
1956 /* Dispatch a call (len + header + args) to the remote daemon,
1957 * synchronously (ie. using the guest's main loop to wait until
1958 * it has been sent). Returns -1 for error, or the serial
1959 * number of the message.
1962 send_cb (guestfs_h *g, void *data)
1964 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1967 ml->main_loop_quit (ml, g);
1971 guestfs__send_sync (guestfs_h *g, int proc_nr,
1972 xdrproc_t xdrp, char *args)
1974 struct guestfs_message_header hdr;
1977 int serial = g->msg_next_serial++;
1979 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1981 if (g->state != BUSY) {
1982 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1986 /* This is probably an internal error. Or perhaps we should just
1987 * free the buffer anyway?
1989 if (g->msg_out != NULL) {
1990 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1994 /* We have to allocate this message buffer on the heap because
1995 * it is quite large (although will be mostly unused). We
1996 * can't allocate it on the stack because in some environments
1997 * we have quite limited stack space available, notably when
1998 * running in the JVM.
2000 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2001 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2003 /* Serialize the header. */
2004 hdr.prog = GUESTFS_PROGRAM;
2005 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2007 hdr.direction = GUESTFS_DIRECTION_CALL;
2008 hdr.serial = serial;
2009 hdr.status = GUESTFS_STATUS_OK;
2011 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2012 error (g, _("xdr_guestfs_message_header failed"));
2016 /* Serialize the args. If any, because some message types
2017 * have no parameters.
2020 if (!(*xdrp) (&xdr, args)) {
2021 error (g, _("dispatch failed to marshal args"));
2026 /* Get the actual length of the message, resize the buffer to match
2027 * the actual length, and write the length word at the beginning.
2029 len = xdr_getpos (&xdr);
2032 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2033 g->msg_out_size = len + 4;
2036 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2037 xdr_uint32_t (&xdr, &len);
2039 if (guestfs__switch_to_sending (g) == -1)
2043 guestfs_set_send_callback (g, send_cb, &sent);
2044 if (ml->main_loop_run (ml, g) == -1)
2047 error (g, _("send failed, see earlier error messages"));
2056 g->msg_out_size = 0;
2060 static int cancel = 0; /* XXX Implement file cancellation. */
2061 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2062 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2063 static int send_file_cancellation_sync (guestfs_h *g);
2064 static int send_file_complete_sync (guestfs_h *g);
2066 /* Synchronously send a file.
2070 * -2 daemon cancelled (we must read the error message)
2073 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2075 char buf[GUESTFS_MAX_CHUNK_SIZE];
2078 fd = open (filename, O_RDONLY);
2080 perrorf (g, "open: %s", filename);
2081 send_file_cancellation_sync (g);
2082 /* Daemon sees cancellation and won't reply, so caller can
2088 /* Send file in chunked encoding. */
2090 r = read (fd, buf, sizeof buf);
2091 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2094 err = send_file_data_sync (g, buf, r);
2096 if (err == -2) /* daemon sent cancellation */
2097 send_file_cancellation_sync (g);
2102 if (cancel) { /* cancel from either end */
2103 send_file_cancellation_sync (g);
2108 perrorf (g, "read: %s", filename);
2109 send_file_cancellation_sync (g);
2113 /* End of file, but before we send that, we need to close
2114 * the file and check for errors.
2116 if (close (fd) == -1) {
2117 perrorf (g, "close: %s", filename);
2118 send_file_cancellation_sync (g);
2122 return send_file_complete_sync (g);
2125 /* Send a chunk of file data. */
2127 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2129 return send_file_chunk_sync (g, 0, buf, len);
2132 /* Send a cancellation message. */
2134 send_file_cancellation_sync (guestfs_h *g)
2136 return send_file_chunk_sync (g, 1, NULL, 0);
2139 /* Send a file complete chunk. */
2141 send_file_complete_sync (guestfs_h *g)
2144 return send_file_chunk_sync (g, 0, buf, 0);
2147 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2150 static int check_for_daemon_cancellation (guestfs_h *g);
2153 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2157 guestfs_chunk chunk;
2159 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2161 if (g->state != BUSY) {
2162 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2166 /* This is probably an internal error. Or perhaps we should just
2167 * free the buffer anyway?
2169 if (g->msg_out != NULL) {
2170 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2174 /* Did the daemon send a cancellation message? */
2175 if (check_for_daemon_cancellation (g)) {
2177 fprintf (stderr, "got daemon cancellation\n");
2181 /* Allocate the chunk buffer. Don't use the stack to avoid
2182 * excessive stack usage and unnecessary copies.
2184 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2185 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2187 /* Serialize the chunk. */
2188 chunk.cancel = cancel;
2189 chunk.data.data_len = buflen;
2190 chunk.data.data_val = (char *) buf;
2192 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2193 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2199 len = xdr_getpos (&xdr);
2202 /* Reduce the size of the outgoing message buffer to the real length. */
2203 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2204 g->msg_out_size = len + 4;
2207 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2208 xdr_uint32_t (&xdr, &len);
2210 if (guestfs__switch_to_sending (g) == -1)
2214 guestfs_set_send_callback (g, send_cb, &sent);
2215 if (ml->main_loop_run (ml, g) == -1)
2218 error (g, _("send file chunk failed, see earlier error messages"));
2227 g->msg_out_size = 0;
2231 /* At this point we are sending FileIn file(s) to the guest, and not
2232 * expecting to read anything, so if we do read anything, it must be
2233 * a cancellation message. This checks for this case without blocking.
2236 check_for_daemon_cancellation (guestfs_h *g)
2246 FD_SET (g->sock, &rset);
2249 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2251 perrorf (g, "select");
2257 /* Read the message from the daemon. */
2258 r = xread (g->sock, buf, sizeof buf);
2260 perrorf (g, "read");
2264 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2265 xdr_uint32_t (&xdr, &flag);
2268 if (flag != GUESTFS_CANCEL_FLAG) {
2269 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2270 flag, GUESTFS_CANCEL_FLAG);
2277 /* Synchronously receive a file. */
2279 /* Returns -1 = error, 0 = EOF, 1 = more data */
2280 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2283 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2289 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2291 perrorf (g, "open: %s", filename);
2295 /* Receive the file in chunked encoding. */
2296 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2297 if (xwrite (fd, buf, len) == -1) {
2298 perrorf (g, "%s: write", filename);
2303 if (r == 0) break; /* End of file. */
2307 error (g, _("%s: error in chunked encoding"), filename);
2311 if (close (fd) == -1) {
2312 perrorf (g, "close: %s", filename);
2319 /* Send cancellation message to daemon, then wait until it
2320 * cancels (just throwing away data).
2324 uint32_t flag = GUESTFS_CANCEL_FLAG;
2327 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2330 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2331 xdr_uint32_t (&xdr, &flag);
2334 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2335 perrorf (g, _("write to daemon socket"));
2339 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2340 ; /* just discard it */
2345 /* Note that the reply callback can be called multiple times before
2346 * the main loop quits and we get back to the synchronous code. So
2347 * we have to be prepared to save multiple chunks on a list here.
2349 struct receive_file_ctx {
2350 int count; /* 0 if receive_file_cb not called, or
2351 * else count number of chunks.
2353 guestfs_chunk *chunks; /* Array of chunks. */
2357 free_chunks (struct receive_file_ctx *ctx)
2361 for (i = 0; i < ctx->count; ++i)
2362 free (ctx->chunks[i].data.data_val);
2368 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2370 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2371 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2372 guestfs_chunk chunk;
2374 if (ctx->count == -1) /* Parse error occurred previously. */
2377 ml->main_loop_quit (ml, g);
2379 memset (&chunk, 0, sizeof chunk);
2381 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2382 error (g, _("failed to parse file chunk"));
2389 /* Copy the chunk to the list. */
2390 ctx->chunks = safe_realloc (g, ctx->chunks,
2391 sizeof (guestfs_chunk) * (ctx->count+1));
2392 ctx->chunks[ctx->count] = chunk;
2396 /* Receive a chunk of file data. */
2397 /* Returns -1 = error, 0 = EOF, 1 = more data */
2399 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2401 struct receive_file_ctx ctx;
2402 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2409 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2410 (void) ml->main_loop_run (ml, g);
2411 guestfs_set_reply_callback (g, NULL, NULL);
2413 if (ctx.count == 0) {
2414 error (g, _("receive_file_data_sync: reply callback not called\n"));
2418 if (ctx.count == -1) {
2419 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2420 /* callback already freed the chunks */
2425 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2427 /* Process each chunk in the list. */
2428 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2431 for (i = 0; i < ctx.count; ++i) {
2432 if (ctx.chunks[i].cancel) {
2433 error (g, _("file receive cancelled by daemon"));
2435 if (buf) free (*buf);
2436 if (len_r) *len_r = 0;
2440 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2442 if (len_r) *len_r = len;
2447 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2448 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2449 ctx.chunks[i].data.data_len);
2451 len += ctx.chunks[i].data.data_len;
2454 if (len_r) *len_r = len;
2459 /* This is the default main loop implementation, using select(2). */
2462 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2463 guestfs_handle_event_cb cb, void *data)
2465 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2467 if (fd < 0 || fd >= FD_SETSIZE) {
2468 error (g, _("fd %d is out of range"), fd);
2472 if ((events & ~(GUESTFS_HANDLE_READABLE |
2473 GUESTFS_HANDLE_WRITABLE |
2474 GUESTFS_HANDLE_HANGUP |
2475 GUESTFS_HANDLE_ERROR)) != 0) {
2476 error (g, _("set of events (0x%x) contains unknown events"), events);
2481 error (g, _("set of events is empty"));
2485 if (FD_ISSET (fd, &ml->rset) ||
2486 FD_ISSET (fd, &ml->wset) ||
2487 FD_ISSET (fd, &ml->xset)) {
2488 error (g, _("fd %d is already registered"), fd);
2493 error (g, _("callback is NULL"));
2497 if ((events & GUESTFS_HANDLE_READABLE))
2498 FD_SET (fd, &ml->rset);
2499 if ((events & GUESTFS_HANDLE_WRITABLE))
2500 FD_SET (fd, &ml->wset);
2501 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2502 FD_SET (fd, &ml->xset);
2504 if (fd > ml->max_fd) {
2506 ml->handle_cb_data =
2507 safe_realloc (g, ml->handle_cb_data,
2508 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2510 ml->handle_cb_data[fd].cb = cb;
2511 ml->handle_cb_data[fd].g = g;
2512 ml->handle_cb_data[fd].data = data;
2516 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2521 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2523 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2525 if (fd < 0 || fd >= FD_SETSIZE) {
2526 error (g, _("fd %d is out of range"), fd);
2530 if (!FD_ISSET (fd, &ml->rset) &&
2531 !FD_ISSET (fd, &ml->wset) &&
2532 !FD_ISSET (fd, &ml->xset)) {
2533 error (g, _("fd %d was not registered"), fd);
2537 FD_CLR (fd, &ml->rset);
2538 FD_CLR (fd, &ml->wset);
2539 FD_CLR (fd, &ml->xset);
2541 if (fd == ml->max_fd) {
2543 ml->handle_cb_data =
2544 safe_realloc (g, ml->handle_cb_data,
2545 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2554 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2555 guestfs_handle_timeout_cb cb, void *data)
2557 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2559 abort (); /* XXX not implemented yet */
2563 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2565 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2567 abort (); /* XXX not implemented yet */
2570 /* The 'g' parameter is just used for error reporting. Events
2571 * for multiple handles can be dispatched by running the main
2575 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2577 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2579 fd_set rset2, wset2, xset2;
2581 if (ml->is_running) {
2582 error (g, _("select_main_loop_run: this cannot be called recursively"));
2588 while (ml->is_running) {
2589 if (ml->nr_fds == 0)
2595 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2597 if (errno == EINTR || errno == EAGAIN)
2599 perrorf (g, "select");
2604 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2606 if (FD_ISSET (fd, &rset2))
2607 events |= GUESTFS_HANDLE_READABLE;
2608 if (FD_ISSET (fd, &wset2))
2609 events |= GUESTFS_HANDLE_WRITABLE;
2610 if (FD_ISSET (fd, &xset2))
2611 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2614 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2615 ml->handle_cb_data[fd].g,
2616 ml->handle_cb_data[fd].data,
2627 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2629 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2631 /* Note that legitimately ml->is_running can be zero when
2632 * this function is called.