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 */
33 #include <sys/select.h>
36 #include <rpc/types.h>
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
47 #ifdef HAVE_SYS_WAIT_H
51 #ifdef HAVE_SYS_SOCKET_H
52 #include <sys/socket.h>
60 #include "guestfs_protocol.h"
64 #define _(str) dgettext(PACKAGE, (str))
65 #define N_(str) dgettext(PACKAGE, (str))
71 #define error guestfs_error
72 #define perrorf guestfs_perrorf
73 #define safe_malloc guestfs_safe_malloc
74 #define safe_realloc guestfs_safe_realloc
75 #define safe_strdup guestfs_safe_strdup
76 #define safe_memdup guestfs_safe_memdup
78 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
79 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
80 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
81 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
83 static void close_handles (void);
85 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
86 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
87 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
88 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
89 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
90 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
92 /* Default select-based main loop. */
93 struct select_handle_cb_data {
94 guestfs_handle_event_cb cb;
99 struct select_main_loop {
100 /* NB. These fields must be the same as in struct guestfs_main_loop: */
101 guestfs_add_handle_cb add_handle;
102 guestfs_remove_handle_cb remove_handle;
103 guestfs_add_timeout_cb add_timeout;
104 guestfs_remove_timeout_cb remove_timeout;
105 guestfs_main_loop_run_cb main_loop_run;
106 guestfs_main_loop_quit_cb main_loop_quit;
108 /* Additional private data: */
117 struct select_handle_cb_data *handle_cb_data;
120 /* Default main loop. */
121 static struct select_main_loop default_main_loop = {
122 .add_handle = select_add_handle,
123 .remove_handle = select_remove_handle,
124 .add_timeout = select_add_timeout,
125 .remove_timeout = select_remove_timeout,
126 .main_loop_run = select_main_loop_run,
127 .main_loop_quit = select_main_loop_quit,
129 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
130 * set by the normal action of everything being initialized to zero.
135 .handle_cb_data = NULL,
138 #define UNIX_PATH_MAX 108
140 /* Also in guestfsd.c */
141 #define VMCHANNEL_PORT 6666
142 #define VMCHANNEL_ADDR "10.0.2.4"
144 /* GuestFS handle and connection. */
145 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
149 struct guestfs_h *next; /* Linked list of open handles. */
151 /* State: see the state machine diagram in the man page guestfs(3). */
154 int fd[2]; /* Stdin/stdout of qemu. */
155 int sock; /* Daemon communications socket. */
156 pid_t pid; /* Qemu PID. */
157 pid_t recoverypid; /* Recovery process PID. */
158 time_t start_t; /* The time when we started qemu. */
160 int stdout_watch; /* Watches qemu stdout for log messages. */
161 int sock_watch; /* Watches daemon comm socket. */
163 char *tmpdir; /* Temporary directory containing socket. */
165 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
167 char **cmdline; /* Qemu command line. */
173 char *path; /* Path to kernel, initrd. */
174 char *qemu; /* Qemu binary. */
175 char *append; /* Append to kernel command line. */
177 int memsize; /* Size of RAM (megabytes). */
182 guestfs_abort_cb abort_cb;
183 guestfs_error_handler_cb error_cb;
184 void * error_cb_data;
185 guestfs_send_cb send_cb;
187 guestfs_reply_cb reply_cb;
188 void * reply_cb_data;
189 guestfs_log_message_cb log_message_cb;
190 void * log_message_cb_data;
191 guestfs_subprocess_quit_cb subprocess_quit_cb;
192 void * subprocess_quit_cb_data;
193 guestfs_launch_done_cb launch_done_cb;
194 void * launch_done_cb_data;
196 /* Main loop used by this handle. */
197 guestfs_main_loop *main_loop;
199 /* Messages sent and received from the daemon. */
201 int msg_in_size, msg_in_allocated;
203 int msg_out_size, msg_out_pos;
208 static guestfs_h *handles = NULL;
209 static int atexit_handler_set = 0;
212 guestfs_create (void)
217 g = malloc (sizeof (*g));
220 memset (g, 0, sizeof (*g));
227 g->stdout_watch = -1;
231 g->error_cb = default_error_cb;
232 g->error_cb_data = NULL;
234 str = getenv ("LIBGUESTFS_DEBUG");
235 g->verbose = str != NULL && strcmp (str, "1") == 0;
237 str = getenv ("LIBGUESTFS_PATH");
238 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
239 if (!g->path) goto error;
241 str = getenv ("LIBGUESTFS_QEMU");
242 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
243 if (!g->qemu) goto error;
245 str = getenv ("LIBGUESTFS_APPEND");
247 g->append = strdup (str);
248 if (!g->append) goto error;
251 /* Choose a suitable memory size. Previously we tried to choose
252 * a minimal memory size, but this isn't really necessary since
253 * recent QEMU and KVM don't do anything nasty like locking
254 * memory into core any more. Thus we can safely choose a
255 * large, generous amount of memory, and it'll just get swapped
256 * on smaller systems.
258 str = getenv ("LIBGUESTFS_MEMSIZE");
260 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
261 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
267 g->main_loop = guestfs_get_default_main_loop ();
269 /* Start with large serial numbers so they are easy to spot
270 * inside the protocol.
272 g->msg_next_serial = 0x00123400;
274 /* Link the handles onto a global list. This is the one area
275 * where the library needs to be made thread-safe. (XXX)
277 /* acquire mutex (XXX) */
280 if (!atexit_handler_set) {
281 atexit (close_handles);
282 atexit_handler_set = 1;
284 /* release mutex (XXX) */
287 fprintf (stderr, "new guestfs handle %p\n", g);
300 guestfs_close (guestfs_h *g)
306 if (g->state == NO_HANDLE) {
307 /* Not safe to call 'error' here, so ... */
308 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
313 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
315 /* Try to sync if autosync flag is set. */
316 if (g->autosync && g->state == READY) {
317 guestfs_umount_all (g);
321 /* Remove any handlers that might be called back before we kill the
324 g->log_message_cb = NULL;
326 if (g->state != CONFIG)
327 guestfs_kill_subprocess (g);
330 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
333 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
336 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
345 for (i = 0; i < g->cmdline_size; ++i)
346 free (g->cmdline[i]);
350 /* Mark the handle as dead before freeing it. */
351 g->state = NO_HANDLE;
353 /* acquire mutex (XXX) */
357 for (gg = handles; gg->next != g; gg = gg->next)
361 /* release mutex (XXX) */
365 free (g->last_error);
370 free (g->qemu_version);
374 /* Close all open handles (called from atexit(3)). */
378 while (handles) guestfs_close (handles);
382 guestfs_last_error (guestfs_h *g)
384 return g->last_error;
388 set_last_error (guestfs_h *g, const char *msg)
390 free (g->last_error);
391 g->last_error = strdup (msg);
395 default_error_cb (guestfs_h *g, void *data, const char *msg)
397 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
401 guestfs_error (guestfs_h *g, const char *fs, ...)
407 int err = vasprintf (&msg, fs, args);
412 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
413 set_last_error (g, msg);
419 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
426 vasprintf (&msg, fs, args);
431 strerror_r (err, buf, sizeof buf);
435 buf = strerror_r (err, _buf, sizeof _buf);
438 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
442 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
443 set_last_error (g, msg);
449 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
451 void *ptr = malloc (nbytes);
452 if (nbytes > 0 && !ptr) g->abort_cb ();
457 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
459 void *p = realloc (ptr, nbytes);
460 if (nbytes > 0 && !p) g->abort_cb ();
465 guestfs_safe_strdup (guestfs_h *g, const char *str)
467 char *s = strdup (str);
468 if (!s) g->abort_cb ();
473 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
475 void *p = malloc (size);
476 if (!p) g->abort_cb ();
477 memcpy (p, ptr, size);
482 xwrite (int fd, const void *buf, size_t len)
487 r = write (fd, buf, len);
499 xread (int fd, void *buf, size_t len)
504 r = read (fd, buf, len);
506 if (errno == EINTR || errno == EAGAIN)
519 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
525 guestfs_get_out_of_memory_handler (guestfs_h *g)
531 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
534 g->error_cb_data = data;
537 guestfs_error_handler_cb
538 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
540 if (data_rtn) *data_rtn = g->error_cb_data;
545 guestfs_set_verbose (guestfs_h *g, int v)
552 guestfs_get_verbose (guestfs_h *g)
558 guestfs_set_autosync (guestfs_h *g, int a)
565 guestfs_get_autosync (guestfs_h *g)
571 guestfs_set_path (guestfs_h *g, const char *path)
578 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
583 guestfs_get_path (guestfs_h *g)
589 guestfs_set_qemu (guestfs_h *g, const char *qemu)
594 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
599 guestfs_get_qemu (guestfs_h *g)
605 guestfs_set_append (guestfs_h *g, const char *append)
610 g->append = append ? safe_strdup (g, append) : NULL;
615 guestfs_get_append (guestfs_h *g)
621 guestfs_set_memsize (guestfs_h *g, int memsize)
623 g->memsize = memsize;
628 guestfs_get_memsize (guestfs_h *g)
633 /* Add a string to the current command line. */
635 incr_cmdline_size (guestfs_h *g)
637 if (g->cmdline == NULL) {
638 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
640 g->cmdline = safe_malloc (g, sizeof (char *));
641 g->cmdline[0] = NULL;
645 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
649 add_cmdline (guestfs_h *g, const char *str)
651 if (g->state != CONFIG) {
653 _("command line cannot be altered after qemu subprocess launched"));
657 incr_cmdline_size (g);
658 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
663 guestfs_config (guestfs_h *g,
664 const char *qemu_param, const char *qemu_value)
666 if (qemu_param[0] != '-') {
667 error (g, _("guestfs_config: parameter must begin with '-' character"));
671 /* A bit fascist, but the user will probably break the extra
672 * parameters that we add if they try to set any of these.
674 if (strcmp (qemu_param, "-kernel") == 0 ||
675 strcmp (qemu_param, "-initrd") == 0 ||
676 strcmp (qemu_param, "-nographic") == 0 ||
677 strcmp (qemu_param, "-serial") == 0 ||
678 strcmp (qemu_param, "-full-screen") == 0 ||
679 strcmp (qemu_param, "-std-vga") == 0 ||
680 strcmp (qemu_param, "-vnc") == 0) {
681 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
685 if (add_cmdline (g, qemu_param) != 0) return -1;
687 if (qemu_value != NULL) {
688 if (add_cmdline (g, qemu_value) != 0) return -1;
695 guestfs_add_drive (guestfs_h *g, const char *filename)
697 size_t len = strlen (filename) + 64;
700 if (strchr (filename, ',') != NULL) {
701 error (g, _("filename cannot contain ',' (comma) character"));
705 if (access (filename, F_OK) == -1) {
706 perrorf (g, "%s", filename);
710 /* cache=off improves reliability in the event of a host crash. */
711 snprintf (buf, len, "file=%s,cache=off,if=virtio", filename);
713 return guestfs_config (g, "-drive", buf);
717 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
719 size_t len = strlen (filename) + 64;
722 if (strchr (filename, ',') != NULL) {
723 error (g, _("filename cannot contain ',' (comma) character"));
727 if (access (filename, F_OK) == -1) {
728 perrorf (g, "%s", filename);
732 snprintf (buf, len, "file=%s,snapshot=on,if=virtio", filename);
734 return guestfs_config (g, "-drive", buf);
738 guestfs_add_cdrom (guestfs_h *g, const char *filename)
740 if (strchr (filename, ',') != NULL) {
741 error (g, _("filename cannot contain ',' (comma) character"));
745 if (access (filename, F_OK) == -1) {
746 perrorf (g, "%s", filename);
750 return guestfs_config (g, "-cdrom", filename);
753 /* Returns true iff file is contained in dir. */
755 dir_contains_file (const char *dir, const char *file)
757 int dirlen = strlen (dir);
758 int filelen = strlen (file);
759 int len = dirlen+filelen+2;
762 snprintf (path, len, "%s/%s", dir, file);
763 return access (path, F_OK) == 0;
766 /* Returns true iff every listed file is contained in 'dir'. */
768 dir_contains_files (const char *dir, ...)
773 va_start (args, dir);
774 while ((file = va_arg (args, const char *)) != NULL) {
775 if (!dir_contains_file (dir, file)) {
784 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
785 static int test_qemu (guestfs_h *g);
786 static int qemu_supports (guestfs_h *g, const char *option);
788 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
789 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
790 static const char *supermin_name =
791 "initramfs." REPO "." host_cpu ".supermin.img";
792 static const char *supermin_hostfiles_name =
793 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
796 guestfs_launch (guestfs_h *g)
798 static const char *dir_template = "/tmp/libguestfsXXXXXX";
803 char *path, *pelem, *pend;
804 char *kernel = NULL, *initrd = NULL;
806 struct sockaddr_un addr;
810 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
814 if (g->state != CONFIG) {
815 error (g, _("qemu has already been launched"));
819 /* Make the temporary directory. */
821 g->tmpdir = safe_strdup (g, dir_template);
822 if (mkdtemp (g->tmpdir) == NULL) {
823 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
828 /* First search g->path for the supermin appliance, and try to
829 * synthesize a kernel and initrd from that. If it fails, we
830 * try the path search again looking for a backup ordinary
833 pelem = path = safe_strdup (g, g->path);
835 pend = strchrnul (pelem, ':');
836 pmore = *pend == ':';
840 /* Empty element of "." means cwd. */
841 if (len == 0 || (len == 1 && *pelem == '.')) {
844 "looking for supermin appliance in current directory\n");
845 if (dir_contains_files (".",
846 supermin_name, supermin_hostfiles_name,
847 "kmod.whitelist", NULL)) {
848 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
853 /* Look at <path>/supermin* etc. */
856 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
858 if (dir_contains_files (pelem,
859 supermin_name, supermin_hostfiles_name,
860 "kmod.whitelist", NULL)) {
861 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
872 if (kernel == NULL || initrd == NULL) {
873 /* Search g->path for the kernel and initrd. */
874 pelem = path = safe_strdup (g, g->path);
876 pend = strchrnul (pelem, ':');
877 pmore = *pend == ':';
881 /* Empty element or "." means cwd. */
882 if (len == 0 || (len == 1 && *pelem == '.')) {
885 "looking for appliance in current directory\n");
886 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
887 kernel = safe_strdup (g, kernel_name);
888 initrd = safe_strdup (g, initrd_name);
892 /* Look at <path>/kernel etc. */
895 fprintf (stderr, "looking for appliance in %s\n", pelem);
897 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
898 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
899 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
900 sprintf (kernel, "%s/%s", pelem, kernel_name);
901 sprintf (initrd, "%s/%s", pelem, initrd_name);
912 if (kernel == NULL || initrd == NULL) {
913 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
914 kernel_name, initrd_name, g->path);
918 /* Get qemu help text and version. */
919 if (test_qemu (g) == -1)
922 /* Make the vmchannel socket. */
923 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
926 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
941 if (r == 0) { /* Child (qemu). */
944 char memsize_str[256];
946 /* Set up the full command line. Do this in the subprocess so we
947 * don't need to worry about cleaning up.
949 g->cmdline[0] = g->qemu;
951 /* Construct the -net channel parameter for qemu. */
952 snprintf (vmchannel, sizeof vmchannel,
953 "channel,%d:unix:%s,server,nowait",
954 VMCHANNEL_PORT, unixsock);
956 /* Linux kernel command line. */
957 snprintf (append, sizeof append,
958 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
959 VMCHANNEL_ADDR, VMCHANNEL_PORT,
960 g->verbose ? " guestfs_verbose=1" : "",
961 g->append ? " " : "", g->append ? g->append : "");
963 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
965 add_cmdline (g, "-m");
966 add_cmdline (g, memsize_str);
967 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
968 add_cmdline (g, "-kernel");
969 add_cmdline (g, (char *) kernel);
970 add_cmdline (g, "-initrd");
971 add_cmdline (g, (char *) initrd);
972 add_cmdline (g, "-append");
973 add_cmdline (g, append);
974 add_cmdline (g, "-nographic");
975 add_cmdline (g, "-serial");
976 add_cmdline (g, "stdio");
977 add_cmdline (g, "-net");
978 add_cmdline (g, vmchannel);
979 add_cmdline (g, "-net");
980 add_cmdline (g, "user,vlan=0");
981 add_cmdline (g, "-net");
982 add_cmdline (g, "nic,model=virtio,vlan=0");
984 /* These options recommended by KVM developers to improve reliability. */
985 if (qemu_supports (g, "-no-hpet"))
986 add_cmdline (g, "-no-hpet");
988 if (qemu_supports (g, "-rtc-td-hack"))
989 add_cmdline (g, "-rtc-td-hack");
991 /* Finish off the command line. */
992 incr_cmdline_size (g);
993 g->cmdline[g->cmdline_size-1] = NULL;
996 fprintf (stderr, "%s", g->qemu);
997 for (i = 0; g->cmdline[i]; ++i)
998 fprintf (stderr, " %s", g->cmdline[i]);
999 fprintf (stderr, "\n");
1002 /* Set up stdin, stdout. */
1013 /* Set up a new process group, so we can signal this process
1014 * and all subprocesses (eg. if qemu is really a shell script).
1019 execv (g->qemu, g->cmdline); /* Run qemu. */
1024 /* Parent (library). */
1032 /* Fork the recovery process off which will kill qemu if the parent
1033 * process fails to do so (eg. if the parent segfaults).
1037 pid_t qemu_pid = g->pid;
1038 pid_t parent_pid = getppid ();
1040 /* Writing to argv is hideously complicated and error prone. See:
1041 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1044 /* Loop around waiting for one or both of the other processes to
1045 * disappear. It's fair to say this is very hairy. The PIDs that
1046 * we are looking at might be reused by another process. We are
1047 * effectively polling. Is the cure worse than the disease?
1050 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1052 if (kill (parent_pid, 0) == -1) {
1053 /* Parent's gone away, qemu still around, so kill qemu. */
1061 /* Don't worry, if the fork failed, this will be -1. The recovery
1062 * process isn't essential.
1066 /* Start the clock ... */
1069 /* Close the other ends of the pipe. */
1073 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1074 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1075 perrorf (g, "fcntl");
1079 g->fd[0] = wfd[1]; /* stdin of child */
1080 g->fd[1] = rfd[0]; /* stdout of child */
1082 /* Open the Unix socket. The vmchannel implementation that got
1083 * merged with qemu sucks in a number of ways. Both ends do
1084 * connect(2), which means that no one knows what, if anything, is
1085 * connected to the other end, or if it becomes disconnected. Even
1086 * worse, we have to wait some indeterminate time for qemu to create
1087 * the socket and connect to it (which happens very early in qemu's
1088 * start-up), so any code that uses vmchannel is inherently racy.
1089 * Hence this silly loop.
1091 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1092 if (g->sock == -1) {
1093 perrorf (g, "socket");
1097 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1098 perrorf (g, "fcntl");
1102 addr.sun_family = AF_UNIX;
1103 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1104 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1107 /* Always sleep at least once to give qemu a small chance to start up. */
1110 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1111 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1114 if (errno != ENOENT)
1115 perrorf (g, "connect");
1120 error (g, _("failed to connect to vmchannel socket"));
1124 /* Watch the file descriptors. */
1127 g->msg_in_size = g->msg_in_allocated = 0;
1131 g->msg_out_size = 0;
1135 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1136 GUESTFS_HANDLE_READABLE,
1137 stdout_event, NULL);
1138 if (g->stdout_watch == -1) {
1139 error (g, _("could not watch qemu stdout"));
1143 if (guestfs__switch_to_receiving (g) == -1)
1146 g->state = LAUNCHING;
1150 if (g->stdout_watch >= 0)
1151 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1152 if (g->sock_watch >= 0)
1153 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1162 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1163 waitpid (g->pid, NULL, 0);
1164 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1171 g->stdout_watch = -1;
1180 /* This function does the hard work of building the supermin appliance
1181 * on the fly. 'path' is the directory containing the control files.
1182 * 'kernel' and 'initrd' are where we will return the names of the
1183 * kernel and initrd (only initrd is built). The work is done by
1184 * an external script. We just tell it where to put the result.
1187 build_supermin_appliance (guestfs_h *g, const char *path,
1188 char **kernel, char **initrd)
1193 len = strlen (g->tmpdir);
1194 *kernel = safe_malloc (g, len + 8);
1195 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1196 *initrd = safe_malloc (g, len + 8);
1197 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1199 snprintf (cmd, sizeof cmd,
1201 "libguestfs-supermin-helper '%s' %s %s",
1203 path, *kernel, *initrd);
1206 if (r == -1 || WEXITSTATUS(r) != 0) {
1207 error (g, _("external command failed: %s"), cmd);
1210 *kernel = *initrd = NULL;
1217 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1219 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1220 * 'qemu -version' so we know what options this qemu supports and
1224 test_qemu (guestfs_h *g)
1229 free (g->qemu_help);
1230 free (g->qemu_version);
1231 g->qemu_help = NULL;
1232 g->qemu_version = NULL;
1234 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1236 fp = popen (cmd, "r");
1237 /* qemu -help should always work (qemu -version OTOH wasn't
1238 * supported by qemu 0.9). If this command doesn't work then it
1239 * probably indicates that the qemu binary is missing.
1242 /* XXX This error is never printed, even if the qemu binary
1243 * doesn't exist. Why?
1246 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1250 if (read_all (g, fp, &g->qemu_help) == -1)
1253 if (pclose (fp) == -1)
1256 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1258 fp = popen (cmd, "r");
1260 /* Intentionally ignore errors. */
1261 read_all (g, fp, &g->qemu_version);
1269 read_all (guestfs_h *g, FILE *fp, char **ret)
1276 *ret = safe_realloc (g, *ret, n + 1);
1281 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1283 r = fread (p, 1, BUFSIZ, fp);
1285 perrorf (g, "read");
1292 /* Test if option is supported by qemu command line (just by grepping
1296 qemu_supports (guestfs_h *g, const char *option)
1298 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1302 finish_wait_ready (guestfs_h *g, void *vp)
1305 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1308 g->main_loop->main_loop_quit (g->main_loop, g);
1312 guestfs_wait_ready (guestfs_h *g)
1314 int finished = 0, r;
1316 if (g->state == READY) return 0;
1318 if (g->state == BUSY) {
1319 error (g, _("qemu has finished launching already"));
1323 if (g->state != LAUNCHING) {
1324 error (g, _("qemu has not been launched yet"));
1328 g->launch_done_cb = finish_wait_ready;
1329 g->launch_done_cb_data = &finished;
1330 r = g->main_loop->main_loop_run (g->main_loop, g);
1331 g->launch_done_cb = NULL;
1332 g->launch_done_cb_data = NULL;
1334 if (r == -1) return -1;
1336 if (finished != 1) {
1337 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1341 /* This is possible in some really strange situations, such as
1342 * guestfsd starts up OK but then qemu immediately exits. Check for
1343 * it because the caller is probably expecting to be able to send
1344 * commands after this function returns.
1346 if (g->state != READY) {
1347 error (g, _("qemu launched and contacted daemon, but state != READY"));
1355 guestfs_kill_subprocess (guestfs_h *g)
1357 if (g->state == CONFIG) {
1358 error (g, _("no subprocess to kill"));
1363 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1365 kill (g->pid, SIGTERM);
1366 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1371 /* Access current state. */
1373 guestfs_is_config (guestfs_h *g)
1375 return g->state == CONFIG;
1379 guestfs_is_launching (guestfs_h *g)
1381 return g->state == LAUNCHING;
1385 guestfs_is_ready (guestfs_h *g)
1387 return g->state == READY;
1391 guestfs_is_busy (guestfs_h *g)
1393 return g->state == BUSY;
1397 guestfs_get_state (guestfs_h *g)
1403 guestfs_set_ready (guestfs_h *g)
1405 if (g->state != BUSY) {
1406 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1415 guestfs_set_busy (guestfs_h *g)
1417 if (g->state != READY) {
1418 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1427 guestfs_end_busy (guestfs_h *g)
1439 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1445 /* Structure-freeing functions. These rely on the fact that the
1446 * structure format is identical to the XDR format. See note in
1450 guestfs_free_int_bool (struct guestfs_int_bool *x)
1456 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1458 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1463 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1465 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1470 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1472 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1477 guestfs_free_dirent_list (struct guestfs_dirent_list *x)
1479 xdr_free ((xdrproc_t) xdr_guestfs_int_dirent_list, (char *) x);
1483 /* We don't know if stdout_event or sock_read_event will be the
1484 * first to receive EOF if the qemu process dies. This function
1485 * has the common cleanup code for both.
1488 child_cleanup (guestfs_h *g)
1491 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1492 /*kill (g->pid, SIGTERM);*/
1493 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1494 waitpid (g->pid, NULL, 0);
1495 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1496 if (g->stdout_watch >= 0)
1497 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1498 if (g->sock_watch >= 0)
1499 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1509 g->stdout_watch = -1;
1512 if (g->subprocess_quit_cb)
1513 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1516 /* This function is called whenever qemu prints something on stdout.
1517 * Qemu's stdout is also connected to the guest's serial console, so
1518 * we see kernel messages here too.
1521 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1522 int watch, int fd, int events)
1530 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1531 g, g->state, fd, events);
1534 if (g->fd[1] != fd) {
1535 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1539 n = read (fd, buf, sizeof buf);
1541 /* Hopefully this indicates the qemu child process has died. */
1547 if (errno != EINTR && errno != EAGAIN)
1548 perrorf (g, "read");
1552 /* In verbose mode, copy all log messages to stderr. */
1556 /* It's an actual log message, send it upwards if anyone is listening. */
1557 if (g->log_message_cb)
1558 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1561 /* The function is called whenever we can read something on the
1562 * guestfsd (daemon inside the guest) communication socket.
1565 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1566 int watch, int fd, int events)
1574 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1575 g, g->state, fd, events);
1577 if (g->sock != fd) {
1578 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1582 if (g->msg_in_size <= g->msg_in_allocated) {
1583 g->msg_in_allocated += 4096;
1584 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1586 n = read (g->sock, g->msg_in + g->msg_in_size,
1587 g->msg_in_allocated - g->msg_in_size);
1595 if (errno != EINTR && errno != EAGAIN)
1596 perrorf (g, "read");
1600 g->msg_in_size += n;
1602 /* Have we got enough of a message to be able to process it yet? */
1604 if (g->msg_in_size < 4) return;
1606 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1607 if (!xdr_uint32_t (&xdr, &len)) {
1608 error (g, _("can't decode length word"));
1612 /* Length is normally the length of the message, but when guestfsd
1613 * starts up it sends a "magic" value (longer than any possible
1614 * message). Check for this.
1616 if (len == GUESTFS_LAUNCH_FLAG) {
1617 if (g->state != LAUNCHING)
1618 error (g, _("received magic signature from guestfsd, but in state %d"),
1620 else if (g->msg_in_size != 4)
1621 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1625 if (g->launch_done_cb)
1626 g->launch_done_cb (g, g->launch_done_cb_data);
1632 /* This can happen if a cancellation happens right at the end
1633 * of us sending a FileIn parameter to the daemon. Discard. The
1634 * daemon should send us an error message next.
1636 if (len == GUESTFS_CANCEL_FLAG) {
1637 g->msg_in_size -= 4;
1638 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1642 /* If this happens, it's pretty bad and we've probably lost
1645 if (len > GUESTFS_MESSAGE_MAX) {
1646 error (g, _("message length (%u) > maximum possible size (%d)"),
1647 len, GUESTFS_MESSAGE_MAX);
1651 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1653 /* Got the full message, begin processing it. */
1658 for (i = 0; i < g->msg_in_size; i += 16) {
1659 printf ("%04x: ", i);
1660 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1661 printf ("%02x ", (unsigned char) g->msg_in[j]);
1662 for (; j < i+16; ++j)
1665 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1666 if (isprint (g->msg_in[j]))
1667 printf ("%c", g->msg_in[j]);
1670 for (; j < i+16; ++j)
1677 /* Not in the expected state. */
1678 if (g->state != BUSY)
1679 error (g, _("state %d != BUSY"), g->state);
1681 /* Push the message up to the higher layer. */
1683 g->reply_cb (g, g->reply_cb_data, &xdr);
1685 /* This message (probably) should never be printed. */
1686 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1688 g->msg_in_size -= len + 4;
1689 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1690 if (g->msg_in_size > 0) goto again;
1693 /* Free the message buffer if it's grown excessively large. */
1694 if (g->msg_in_allocated > 65536) {
1697 g->msg_in_size = g->msg_in_allocated = 0;
1704 /* The function is called whenever we can write something on the
1705 * guestfsd (daemon inside the guest) communication socket.
1708 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1709 int watch, int fd, int events)
1715 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1716 g, g->state, fd, events);
1718 if (g->sock != fd) {
1719 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1723 if (g->state != BUSY) {
1724 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1729 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1730 g->msg_out_size - g->msg_out_pos);
1732 n = write (g->sock, g->msg_out + g->msg_out_pos,
1733 g->msg_out_size - g->msg_out_pos);
1737 perrorf (g, "write");
1738 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1744 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1746 g->msg_out_pos += n;
1748 /* More to write? */
1749 if (g->msg_out_pos < g->msg_out_size)
1753 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1757 g->msg_out_pos = g->msg_out_size = 0;
1759 /* Done writing, call the higher layer. */
1761 g->send_cb (g, g->send_cb_data);
1765 guestfs_set_send_callback (guestfs_h *g,
1766 guestfs_send_cb cb, void *opaque)
1769 g->send_cb_data = opaque;
1773 guestfs_set_reply_callback (guestfs_h *g,
1774 guestfs_reply_cb cb, void *opaque)
1777 g->reply_cb_data = opaque;
1781 guestfs_set_log_message_callback (guestfs_h *g,
1782 guestfs_log_message_cb cb, void *opaque)
1784 g->log_message_cb = cb;
1785 g->log_message_cb_data = opaque;
1789 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1790 guestfs_subprocess_quit_cb cb, void *opaque)
1792 g->subprocess_quit_cb = cb;
1793 g->subprocess_quit_cb_data = opaque;
1797 guestfs_set_launch_done_callback (guestfs_h *g,
1798 guestfs_launch_done_cb cb, void *opaque)
1800 g->launch_done_cb = cb;
1801 g->launch_done_cb_data = opaque;
1804 /* Access to the handle's main loop and the default main loop. */
1806 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1808 g->main_loop = main_loop;
1812 guestfs_get_main_loop (guestfs_h *g)
1814 return g->main_loop;
1818 guestfs_get_default_main_loop (void)
1820 return (guestfs_main_loop *) &default_main_loop;
1823 /* Change the daemon socket handler so that we are now writing.
1824 * This sets the handle to sock_write_event.
1827 guestfs__switch_to_sending (guestfs_h *g)
1829 if (g->sock_watch >= 0) {
1830 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1831 error (g, _("remove_handle failed"));
1838 g->main_loop->add_handle (g->main_loop, g, g->sock,
1839 GUESTFS_HANDLE_WRITABLE,
1840 sock_write_event, NULL);
1841 if (g->sock_watch == -1) {
1842 error (g, _("add_handle failed"));
1850 guestfs__switch_to_receiving (guestfs_h *g)
1852 if (g->sock_watch >= 0) {
1853 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1854 error (g, _("remove_handle failed"));
1861 g->main_loop->add_handle (g->main_loop, g, g->sock,
1862 GUESTFS_HANDLE_READABLE,
1863 sock_read_event, NULL);
1864 if (g->sock_watch == -1) {
1865 error (g, _("add_handle failed"));
1872 /* Dispatch a call (len + header + args) to the remote daemon,
1873 * synchronously (ie. using the guest's main loop to wait until
1874 * it has been sent). Returns -1 for error, or the serial
1875 * number of the message.
1878 send_cb (guestfs_h *g, void *data)
1880 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1883 ml->main_loop_quit (ml, g);
1887 guestfs__send_sync (guestfs_h *g, int proc_nr,
1888 xdrproc_t xdrp, char *args)
1890 struct guestfs_message_header hdr;
1893 int serial = g->msg_next_serial++;
1895 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1897 if (g->state != BUSY) {
1898 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1902 /* This is probably an internal error. Or perhaps we should just
1903 * free the buffer anyway?
1905 if (g->msg_out != NULL) {
1906 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1910 /* We have to allocate this message buffer on the heap because
1911 * it is quite large (although will be mostly unused). We
1912 * can't allocate it on the stack because in some environments
1913 * we have quite limited stack space available, notably when
1914 * running in the JVM.
1916 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1917 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1919 /* Serialize the header. */
1920 hdr.prog = GUESTFS_PROGRAM;
1921 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1923 hdr.direction = GUESTFS_DIRECTION_CALL;
1924 hdr.serial = serial;
1925 hdr.status = GUESTFS_STATUS_OK;
1927 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1928 error (g, _("xdr_guestfs_message_header failed"));
1932 /* Serialize the args. If any, because some message types
1933 * have no parameters.
1936 if (!(*xdrp) (&xdr, args)) {
1937 error (g, _("dispatch failed to marshal args"));
1942 /* Get the actual length of the message, resize the buffer to match
1943 * the actual length, and write the length word at the beginning.
1945 len = xdr_getpos (&xdr);
1948 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1949 g->msg_out_size = len + 4;
1952 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1953 xdr_uint32_t (&xdr, &len);
1955 if (guestfs__switch_to_sending (g) == -1)
1959 guestfs_set_send_callback (g, send_cb, &sent);
1960 if (ml->main_loop_run (ml, g) == -1)
1963 error (g, _("send failed, see earlier error messages"));
1972 g->msg_out_size = 0;
1976 static int cancel = 0; /* XXX Implement file cancellation. */
1977 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1978 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1979 static int send_file_cancellation_sync (guestfs_h *g);
1980 static int send_file_complete_sync (guestfs_h *g);
1982 /* Synchronously send a file.
1986 * -2 daemon cancelled (we must read the error message)
1989 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1991 char buf[GUESTFS_MAX_CHUNK_SIZE];
1994 fd = open (filename, O_RDONLY);
1996 perrorf (g, "open: %s", filename);
1997 send_file_cancellation_sync (g);
1998 /* Daemon sees cancellation and won't reply, so caller can
2004 /* Send file in chunked encoding. */
2006 r = read (fd, buf, sizeof buf);
2007 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2010 err = send_file_data_sync (g, buf, r);
2012 if (err == -2) /* daemon sent cancellation */
2013 send_file_cancellation_sync (g);
2018 if (cancel) { /* cancel from either end */
2019 send_file_cancellation_sync (g);
2024 perrorf (g, "read: %s", filename);
2025 send_file_cancellation_sync (g);
2029 /* End of file, but before we send that, we need to close
2030 * the file and check for errors.
2032 if (close (fd) == -1) {
2033 perrorf (g, "close: %s", filename);
2034 send_file_cancellation_sync (g);
2038 return send_file_complete_sync (g);
2041 /* Send a chunk of file data. */
2043 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2045 return send_file_chunk_sync (g, 0, buf, len);
2048 /* Send a cancellation message. */
2050 send_file_cancellation_sync (guestfs_h *g)
2052 return send_file_chunk_sync (g, 1, NULL, 0);
2055 /* Send a file complete chunk. */
2057 send_file_complete_sync (guestfs_h *g)
2060 return send_file_chunk_sync (g, 0, buf, 0);
2063 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2066 static int check_for_daemon_cancellation (guestfs_h *g);
2069 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2073 guestfs_chunk chunk;
2075 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2077 if (g->state != BUSY) {
2078 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2082 /* This is probably an internal error. Or perhaps we should just
2083 * free the buffer anyway?
2085 if (g->msg_out != NULL) {
2086 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2090 /* Did the daemon send a cancellation message? */
2091 if (check_for_daemon_cancellation (g)) {
2093 fprintf (stderr, "got daemon cancellation\n");
2097 /* Allocate the chunk buffer. Don't use the stack to avoid
2098 * excessive stack usage and unnecessary copies.
2100 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2101 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2103 /* Serialize the chunk. */
2104 chunk.cancel = cancel;
2105 chunk.data.data_len = buflen;
2106 chunk.data.data_val = (char *) buf;
2108 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2109 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2115 len = xdr_getpos (&xdr);
2118 /* Reduce the size of the outgoing message buffer to the real length. */
2119 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2120 g->msg_out_size = len + 4;
2123 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2124 xdr_uint32_t (&xdr, &len);
2126 if (guestfs__switch_to_sending (g) == -1)
2130 guestfs_set_send_callback (g, send_cb, &sent);
2131 if (ml->main_loop_run (ml, g) == -1)
2134 error (g, _("send file chunk failed, see earlier error messages"));
2143 g->msg_out_size = 0;
2147 /* At this point we are sending FileIn file(s) to the guest, and not
2148 * expecting to read anything, so if we do read anything, it must be
2149 * a cancellation message. This checks for this case without blocking.
2152 check_for_daemon_cancellation (guestfs_h *g)
2162 FD_SET (g->sock, &rset);
2165 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2167 perrorf (g, "select");
2173 /* Read the message from the daemon. */
2174 r = xread (g->sock, buf, sizeof buf);
2176 perrorf (g, "read");
2180 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2181 xdr_uint32_t (&xdr, &flag);
2184 if (flag != GUESTFS_CANCEL_FLAG) {
2185 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2186 flag, GUESTFS_CANCEL_FLAG);
2193 /* Synchronously receive a file. */
2195 /* Returns -1 = error, 0 = EOF, 1 = more data */
2196 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2199 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2205 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2207 perrorf (g, "open: %s", filename);
2211 /* Receive the file in chunked encoding. */
2212 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2213 if (xwrite (fd, buf, len) == -1) {
2214 perrorf (g, "%s: write", filename);
2219 if (r == 0) break; /* End of file. */
2223 error (g, _("%s: error in chunked encoding"), filename);
2227 if (close (fd) == -1) {
2228 perrorf (g, "close: %s", filename);
2235 /* Send cancellation message to daemon, then wait until it
2236 * cancels (just throwing away data).
2240 uint32_t flag = GUESTFS_CANCEL_FLAG;
2242 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2243 xdr_uint32_t (&xdr, &flag);
2246 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2247 perrorf (g, _("write to daemon socket"));
2251 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2252 ; /* just discard it */
2257 /* Note that the reply callback can be called multiple times before
2258 * the main loop quits and we get back to the synchronous code. So
2259 * we have to be prepared to save multiple chunks on a list here.
2261 struct receive_file_ctx {
2262 int count; /* 0 if receive_file_cb not called, or
2263 * else count number of chunks.
2265 guestfs_chunk *chunks; /* Array of chunks. */
2269 free_chunks (struct receive_file_ctx *ctx)
2273 for (i = 0; i < ctx->count; ++i)
2274 free (ctx->chunks[i].data.data_val);
2280 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2282 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2283 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2284 guestfs_chunk chunk;
2286 if (ctx->count == -1) /* Parse error occurred previously. */
2289 ml->main_loop_quit (ml, g);
2291 memset (&chunk, 0, sizeof chunk);
2293 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2294 error (g, _("failed to parse file chunk"));
2301 /* Copy the chunk to the list. */
2302 ctx->chunks = safe_realloc (g, ctx->chunks,
2303 sizeof (guestfs_chunk) * (ctx->count+1));
2304 ctx->chunks[ctx->count] = chunk;
2308 /* Receive a chunk of file data. */
2309 /* Returns -1 = error, 0 = EOF, 1 = more data */
2311 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2313 struct receive_file_ctx ctx;
2314 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2321 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2322 (void) ml->main_loop_run (ml, g);
2323 guestfs_set_reply_callback (g, NULL, NULL);
2325 if (ctx.count == 0) {
2326 error (g, _("receive_file_data_sync: reply callback not called\n"));
2330 if (ctx.count == -1) {
2331 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2332 /* callback already freed the chunks */
2337 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2339 /* Process each chunk in the list. */
2340 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2343 for (i = 0; i < ctx.count; ++i) {
2344 if (ctx.chunks[i].cancel) {
2345 error (g, _("file receive cancelled by daemon"));
2347 if (buf) free (*buf);
2348 if (len_r) *len_r = 0;
2352 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2354 if (len_r) *len_r = len;
2359 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2360 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2361 ctx.chunks[i].data.data_len);
2363 len += ctx.chunks[i].data.data_len;
2366 if (len_r) *len_r = len;
2371 /* This is the default main loop implementation, using select(2). */
2374 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2375 guestfs_handle_event_cb cb, void *data)
2377 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2379 if (fd < 0 || fd >= FD_SETSIZE) {
2380 error (g, _("fd %d is out of range"), fd);
2384 if ((events & ~(GUESTFS_HANDLE_READABLE |
2385 GUESTFS_HANDLE_WRITABLE |
2386 GUESTFS_HANDLE_HANGUP |
2387 GUESTFS_HANDLE_ERROR)) != 0) {
2388 error (g, _("set of events (0x%x) contains unknown events"), events);
2393 error (g, _("set of events is empty"));
2397 if (FD_ISSET (fd, &ml->rset) ||
2398 FD_ISSET (fd, &ml->wset) ||
2399 FD_ISSET (fd, &ml->xset)) {
2400 error (g, _("fd %d is already registered"), fd);
2405 error (g, _("callback is NULL"));
2409 if ((events & GUESTFS_HANDLE_READABLE))
2410 FD_SET (fd, &ml->rset);
2411 if ((events & GUESTFS_HANDLE_WRITABLE))
2412 FD_SET (fd, &ml->wset);
2413 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2414 FD_SET (fd, &ml->xset);
2416 if (fd > ml->max_fd) {
2418 ml->handle_cb_data =
2419 safe_realloc (g, ml->handle_cb_data,
2420 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2422 ml->handle_cb_data[fd].cb = cb;
2423 ml->handle_cb_data[fd].g = g;
2424 ml->handle_cb_data[fd].data = data;
2428 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2433 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2435 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2437 if (fd < 0 || fd >= FD_SETSIZE) {
2438 error (g, _("fd %d is out of range"), fd);
2442 if (!FD_ISSET (fd, &ml->rset) &&
2443 !FD_ISSET (fd, &ml->wset) &&
2444 !FD_ISSET (fd, &ml->xset)) {
2445 error (g, _("fd %d was not registered"), fd);
2449 FD_CLR (fd, &ml->rset);
2450 FD_CLR (fd, &ml->wset);
2451 FD_CLR (fd, &ml->xset);
2453 if (fd == ml->max_fd) {
2455 ml->handle_cb_data =
2456 safe_realloc (g, ml->handle_cb_data,
2457 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2466 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2467 guestfs_handle_timeout_cb cb, void *data)
2469 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2471 abort (); /* XXX not implemented yet */
2475 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2477 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2479 abort (); /* XXX not implemented yet */
2482 /* The 'g' parameter is just used for error reporting. Events
2483 * for multiple handles can be dispatched by running the main
2487 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2489 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2491 fd_set rset2, wset2, xset2;
2493 if (ml->is_running) {
2494 error (g, _("select_main_loop_run: this cannot be called recursively"));
2500 while (ml->is_running) {
2501 if (ml->nr_fds == 0)
2507 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2509 if (errno == EINTR || errno == EAGAIN)
2511 perrorf (g, "select");
2516 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2518 if (FD_ISSET (fd, &rset2))
2519 events |= GUESTFS_HANDLE_READABLE;
2520 if (FD_ISSET (fd, &wset2))
2521 events |= GUESTFS_HANDLE_WRITABLE;
2522 if (FD_ISSET (fd, &xset2))
2523 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2526 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2527 ml->handle_cb_data[fd].g,
2528 ml->handle_cb_data[fd].data,
2539 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2541 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2543 /* Note that legitimately ml->is_running can be zero when
2544 * this function is called.