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 vasprintf (&msg, fs, args);
410 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
411 set_last_error (g, msg);
417 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
424 vasprintf (&msg, fs, args);
429 strerror_r (err, buf, sizeof buf);
433 buf = strerror_r (err, _buf, sizeof _buf);
436 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
440 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
441 set_last_error (g, msg);
447 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
449 void *ptr = malloc (nbytes);
450 if (nbytes > 0 && !ptr) g->abort_cb ();
455 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
457 void *p = realloc (ptr, nbytes);
458 if (nbytes > 0 && !p) g->abort_cb ();
463 guestfs_safe_strdup (guestfs_h *g, const char *str)
465 char *s = strdup (str);
466 if (!s) g->abort_cb ();
471 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
473 void *p = malloc (size);
474 if (!p) g->abort_cb ();
475 memcpy (p, ptr, size);
480 xwrite (int fd, const void *buf, size_t len)
485 r = write (fd, buf, len);
497 xread (int fd, void *buf, size_t len)
502 r = read (fd, buf, len);
504 if (errno == EINTR || errno == EAGAIN)
517 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
523 guestfs_get_out_of_memory_handler (guestfs_h *g)
529 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
532 g->error_cb_data = data;
535 guestfs_error_handler_cb
536 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
538 if (data_rtn) *data_rtn = g->error_cb_data;
543 guestfs_set_verbose (guestfs_h *g, int v)
550 guestfs_get_verbose (guestfs_h *g)
556 guestfs_set_autosync (guestfs_h *g, int a)
563 guestfs_get_autosync (guestfs_h *g)
569 guestfs_set_path (guestfs_h *g, const char *path)
576 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
581 guestfs_get_path (guestfs_h *g)
587 guestfs_set_qemu (guestfs_h *g, const char *qemu)
592 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
597 guestfs_get_qemu (guestfs_h *g)
603 guestfs_set_append (guestfs_h *g, const char *append)
608 g->append = append ? safe_strdup (g, append) : NULL;
613 guestfs_get_append (guestfs_h *g)
619 guestfs_set_memsize (guestfs_h *g, int memsize)
621 g->memsize = memsize;
626 guestfs_get_memsize (guestfs_h *g)
631 /* Add a string to the current command line. */
633 incr_cmdline_size (guestfs_h *g)
635 if (g->cmdline == NULL) {
636 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
638 g->cmdline = safe_malloc (g, sizeof (char *));
639 g->cmdline[0] = NULL;
643 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
647 add_cmdline (guestfs_h *g, const char *str)
649 if (g->state != CONFIG) {
651 _("command line cannot be altered after qemu subprocess launched"));
655 incr_cmdline_size (g);
656 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
661 guestfs_config (guestfs_h *g,
662 const char *qemu_param, const char *qemu_value)
664 if (qemu_param[0] != '-') {
665 error (g, _("guestfs_config: parameter must begin with '-' character"));
669 /* A bit fascist, but the user will probably break the extra
670 * parameters that we add if they try to set any of these.
672 if (strcmp (qemu_param, "-kernel") == 0 ||
673 strcmp (qemu_param, "-initrd") == 0 ||
674 strcmp (qemu_param, "-nographic") == 0 ||
675 strcmp (qemu_param, "-serial") == 0 ||
676 strcmp (qemu_param, "-full-screen") == 0 ||
677 strcmp (qemu_param, "-std-vga") == 0 ||
678 strcmp (qemu_param, "-vnc") == 0) {
679 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
683 if (add_cmdline (g, qemu_param) != 0) return -1;
685 if (qemu_value != NULL) {
686 if (add_cmdline (g, qemu_value) != 0) return -1;
693 guestfs_add_drive (guestfs_h *g, const char *filename)
695 size_t len = strlen (filename) + 64;
698 if (strchr (filename, ',') != NULL) {
699 error (g, _("filename cannot contain ',' (comma) character"));
703 if (access (filename, F_OK) == -1) {
704 perrorf (g, "%s", filename);
708 /* cache=off improves reliability in the event of a host crash. */
709 snprintf (buf, len, "file=%s,cache=off", filename);
711 return guestfs_config (g, "-drive", buf);
715 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
717 size_t len = strlen (filename) + 64;
720 if (strchr (filename, ',') != NULL) {
721 error (g, _("filename cannot contain ',' (comma) character"));
725 if (access (filename, F_OK) == -1) {
726 perrorf (g, "%s", filename);
730 snprintf (buf, len, "file=%s,snapshot=on", filename);
732 return guestfs_config (g, "-drive", buf);
736 guestfs_add_cdrom (guestfs_h *g, const char *filename)
738 if (strchr (filename, ',') != NULL) {
739 error (g, _("filename cannot contain ',' (comma) character"));
743 if (access (filename, F_OK) == -1) {
744 perrorf (g, "%s", filename);
748 return guestfs_config (g, "-cdrom", filename);
751 /* Returns true iff file is contained in dir. */
753 dir_contains_file (const char *dir, const char *file)
755 int dirlen = strlen (dir);
756 int filelen = strlen (file);
757 int len = dirlen+filelen+2;
760 snprintf (path, len, "%s/%s", dir, file);
761 return access (path, F_OK) == 0;
764 /* Returns true iff every listed file is contained in 'dir'. */
766 dir_contains_files (const char *dir, ...)
771 va_start (args, dir);
772 while ((file = va_arg (args, const char *)) != NULL) {
773 if (!dir_contains_file (dir, file)) {
782 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
783 static int test_qemu (guestfs_h *g);
784 static int qemu_supports (guestfs_h *g, const char *option);
786 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
787 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
788 static const char *supermin_name =
789 "initramfs." REPO "." host_cpu ".supermin.img";
790 static const char *supermin_hostfiles_name =
791 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
794 guestfs_launch (guestfs_h *g)
796 static const char *dir_template = "/tmp/libguestfsXXXXXX";
801 char *path, *pelem, *pend;
802 char *kernel = NULL, *initrd = NULL;
804 struct sockaddr_un addr;
808 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
812 if (g->state != CONFIG) {
813 error (g, _("qemu has already been launched"));
817 /* Make the temporary directory. */
819 g->tmpdir = safe_strdup (g, dir_template);
820 if (mkdtemp (g->tmpdir) == NULL) {
821 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
826 /* First search g->path for the supermin appliance, and try to
827 * synthesize a kernel and initrd from that. If it fails, we
828 * try the path search again looking for a backup ordinary
831 pelem = path = safe_strdup (g, g->path);
833 pend = strchrnul (pelem, ':');
834 pmore = *pend == ':';
838 /* Empty element of "." means cwd. */
839 if (len == 0 || (len == 1 && *pelem == '.')) {
842 "looking for supermin appliance in current directory\n");
843 if (dir_contains_files (".",
844 supermin_name, supermin_hostfiles_name,
845 "kmod.whitelist", NULL)) {
846 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
851 /* Look at <path>/supermin* etc. */
854 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
856 if (dir_contains_files (pelem,
857 supermin_name, supermin_hostfiles_name,
858 "kmod.whitelist", NULL)) {
859 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
870 if (kernel == NULL || initrd == NULL) {
871 /* Search g->path for the kernel and initrd. */
872 pelem = path = safe_strdup (g, g->path);
874 pend = strchrnul (pelem, ':');
875 pmore = *pend == ':';
879 /* Empty element or "." means cwd. */
880 if (len == 0 || (len == 1 && *pelem == '.')) {
883 "looking for appliance in current directory\n");
884 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
885 kernel = safe_strdup (g, kernel_name);
886 initrd = safe_strdup (g, initrd_name);
890 /* Look at <path>/kernel etc. */
893 fprintf (stderr, "looking for appliance in %s\n", pelem);
895 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
896 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
897 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
898 sprintf (kernel, "%s/%s", pelem, kernel_name);
899 sprintf (initrd, "%s/%s", pelem, initrd_name);
910 if (kernel == NULL || initrd == NULL) {
911 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
912 kernel_name, initrd_name, g->path);
916 /* Get qemu help text and version. */
917 if (test_qemu (g) == -1)
920 /* Make the vmchannel socket. */
921 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
924 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
939 if (r == 0) { /* Child (qemu). */
942 char memsize_str[256];
944 /* Set up the full command line. Do this in the subprocess so we
945 * don't need to worry about cleaning up.
947 g->cmdline[0] = g->qemu;
949 /* Construct the -net channel parameter for qemu. */
950 snprintf (vmchannel, sizeof vmchannel,
951 "channel,%d:unix:%s,server,nowait",
952 VMCHANNEL_PORT, unixsock);
954 /* Linux kernel command line. */
955 snprintf (append, sizeof append,
956 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
957 VMCHANNEL_ADDR, VMCHANNEL_PORT,
958 g->verbose ? " guestfs_verbose=1" : "",
959 g->append ? " " : "", g->append ? g->append : "");
961 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
963 add_cmdline (g, "-m");
964 add_cmdline (g, memsize_str);
965 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
966 add_cmdline (g, "-kernel");
967 add_cmdline (g, (char *) kernel);
968 add_cmdline (g, "-initrd");
969 add_cmdline (g, (char *) initrd);
970 add_cmdline (g, "-append");
971 add_cmdline (g, append);
972 add_cmdline (g, "-nographic");
973 add_cmdline (g, "-serial");
974 add_cmdline (g, "stdio");
975 add_cmdline (g, "-net");
976 add_cmdline (g, vmchannel);
977 add_cmdline (g, "-net");
978 add_cmdline (g, "user,vlan=0");
979 add_cmdline (g, "-net");
980 add_cmdline (g, "nic,model=virtio,vlan=0");
982 /* These options recommended by KVM developers to improve reliability. */
983 if (qemu_supports (g, "-no-hpet"))
984 add_cmdline (g, "-no-hpet");
986 if (qemu_supports (g, "-rtc-td-hack"))
987 add_cmdline (g, "-rtc-td-hack");
989 /* Finish off the command line. */
990 incr_cmdline_size (g);
991 g->cmdline[g->cmdline_size-1] = NULL;
994 fprintf (stderr, "%s", g->qemu);
995 for (i = 0; g->cmdline[i]; ++i)
996 fprintf (stderr, " %s", g->cmdline[i]);
997 fprintf (stderr, "\n");
1000 /* Set up stdin, stdout. */
1011 /* Set up a new process group, so we can signal this process
1012 * and all subprocesses (eg. if qemu is really a shell script).
1017 execv (g->qemu, g->cmdline); /* Run qemu. */
1022 /* Parent (library). */
1030 /* Fork the recovery process off which will kill qemu if the parent
1031 * process fails to do so (eg. if the parent segfaults).
1035 pid_t qemu_pid = g->pid;
1036 pid_t parent_pid = getppid ();
1038 /* Writing to argv is hideously complicated and error prone. See:
1039 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1042 /* Loop around waiting for one or both of the other processes to
1043 * disappear. It's fair to say this is very hairy. The PIDs that
1044 * we are looking at might be reused by another process. We are
1045 * effectively polling. Is the cure worse than the disease?
1048 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1050 if (kill (parent_pid, 0) == -1) {
1051 /* Parent's gone away, qemu still around, so kill qemu. */
1059 /* Don't worry, if the fork failed, this will be -1. The recovery
1060 * process isn't essential.
1064 /* Start the clock ... */
1067 /* Close the other ends of the pipe. */
1071 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1072 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1073 perrorf (g, "fcntl");
1077 g->fd[0] = wfd[1]; /* stdin of child */
1078 g->fd[1] = rfd[0]; /* stdout of child */
1080 /* Open the Unix socket. The vmchannel implementation that got
1081 * merged with qemu sucks in a number of ways. Both ends do
1082 * connect(2), which means that no one knows what, if anything, is
1083 * connected to the other end, or if it becomes disconnected. Even
1084 * worse, we have to wait some indeterminate time for qemu to create
1085 * the socket and connect to it (which happens very early in qemu's
1086 * start-up), so any code that uses vmchannel is inherently racy.
1087 * Hence this silly loop.
1089 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1090 if (g->sock == -1) {
1091 perrorf (g, "socket");
1095 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1096 perrorf (g, "fcntl");
1100 addr.sun_family = AF_UNIX;
1101 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1102 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1105 /* Always sleep at least once to give qemu a small chance to start up. */
1108 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1109 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1112 if (errno != ENOENT)
1113 perrorf (g, "connect");
1118 error (g, _("failed to connect to vmchannel socket"));
1122 /* Watch the file descriptors. */
1125 g->msg_in_size = g->msg_in_allocated = 0;
1129 g->msg_out_size = 0;
1133 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1134 GUESTFS_HANDLE_READABLE,
1135 stdout_event, NULL);
1136 if (g->stdout_watch == -1) {
1137 error (g, _("could not watch qemu stdout"));
1141 if (guestfs__switch_to_receiving (g) == -1)
1144 g->state = LAUNCHING;
1148 if (g->stdout_watch >= 0)
1149 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1150 if (g->sock_watch >= 0)
1151 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1160 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1161 waitpid (g->pid, NULL, 0);
1162 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1169 g->stdout_watch = -1;
1178 /* This function does the hard work of building the supermin appliance
1179 * on the fly. 'path' is the directory containing the control files.
1180 * 'kernel' and 'initrd' are where we will return the names of the
1181 * kernel and initrd (only initrd is built). The work is done by
1182 * an external script. We just tell it where to put the result.
1185 build_supermin_appliance (guestfs_h *g, const char *path,
1186 char **kernel, char **initrd)
1191 len = strlen (g->tmpdir);
1192 *kernel = safe_malloc (g, len + 8);
1193 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1194 *initrd = safe_malloc (g, len + 8);
1195 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1197 snprintf (cmd, sizeof cmd,
1199 "libguestfs-supermin-helper '%s' %s %s",
1201 path, *kernel, *initrd);
1204 if (r == -1 || WEXITSTATUS(r) != 0) {
1205 error (g, _("external command failed: %s"), cmd);
1208 *kernel = *initrd = NULL;
1215 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1217 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1218 * 'qemu -version' so we know what options this qemu supports and
1222 test_qemu (guestfs_h *g)
1227 free (g->qemu_help);
1228 free (g->qemu_version);
1229 g->qemu_help = NULL;
1230 g->qemu_version = NULL;
1232 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1234 fp = popen (cmd, "r");
1235 /* qemu -help should always work (qemu -version OTOH wasn't
1236 * supported by qemu 0.9). If this command doesn't work then it
1237 * probably indicates that the qemu binary is missing.
1240 /* XXX This error is never printed, even if the qemu binary
1241 * doesn't exist. Why?
1244 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1248 if (read_all (g, fp, &g->qemu_help) == -1)
1251 if (pclose (fp) == -1)
1254 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1256 fp = popen (cmd, "r");
1258 /* Intentionally ignore errors. */
1259 read_all (g, fp, &g->qemu_version);
1267 read_all (guestfs_h *g, FILE *fp, char **ret)
1274 *ret = safe_realloc (g, *ret, n + 1);
1279 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1281 r = fread (p, 1, BUFSIZ, fp);
1283 perrorf (g, "read");
1290 /* Test if option is supported by qemu command line (just by grepping
1294 qemu_supports (guestfs_h *g, const char *option)
1296 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1300 finish_wait_ready (guestfs_h *g, void *vp)
1303 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1306 g->main_loop->main_loop_quit (g->main_loop, g);
1310 guestfs_wait_ready (guestfs_h *g)
1312 int finished = 0, r;
1314 if (g->state == READY) return 0;
1316 if (g->state == BUSY) {
1317 error (g, _("qemu has finished launching already"));
1321 if (g->state != LAUNCHING) {
1322 error (g, _("qemu has not been launched yet"));
1326 g->launch_done_cb = finish_wait_ready;
1327 g->launch_done_cb_data = &finished;
1328 r = g->main_loop->main_loop_run (g->main_loop, g);
1329 g->launch_done_cb = NULL;
1330 g->launch_done_cb_data = NULL;
1332 if (r == -1) return -1;
1334 if (finished != 1) {
1335 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1339 /* This is possible in some really strange situations, such as
1340 * guestfsd starts up OK but then qemu immediately exits. Check for
1341 * it because the caller is probably expecting to be able to send
1342 * commands after this function returns.
1344 if (g->state != READY) {
1345 error (g, _("qemu launched and contacted daemon, but state != READY"));
1353 guestfs_kill_subprocess (guestfs_h *g)
1355 if (g->state == CONFIG) {
1356 error (g, _("no subprocess to kill"));
1361 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1363 kill (g->pid, SIGTERM);
1364 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1369 /* Access current state. */
1371 guestfs_is_config (guestfs_h *g)
1373 return g->state == CONFIG;
1377 guestfs_is_launching (guestfs_h *g)
1379 return g->state == LAUNCHING;
1383 guestfs_is_ready (guestfs_h *g)
1385 return g->state == READY;
1389 guestfs_is_busy (guestfs_h *g)
1391 return g->state == BUSY;
1395 guestfs_get_state (guestfs_h *g)
1401 guestfs_set_ready (guestfs_h *g)
1403 if (g->state != BUSY) {
1404 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1413 guestfs_set_busy (guestfs_h *g)
1415 if (g->state != READY) {
1416 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1425 guestfs_end_busy (guestfs_h *g)
1437 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1443 /* Structure-freeing functions. These rely on the fact that the
1444 * structure format is identical to the XDR format. See note in
1448 guestfs_free_int_bool (struct guestfs_int_bool *x)
1454 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1456 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1461 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1463 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1468 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1470 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1474 /* We don't know if stdout_event or sock_read_event will be the
1475 * first to receive EOF if the qemu process dies. This function
1476 * has the common cleanup code for both.
1479 child_cleanup (guestfs_h *g)
1482 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1483 /*kill (g->pid, SIGTERM);*/
1484 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1485 waitpid (g->pid, NULL, 0);
1486 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1487 if (g->stdout_watch >= 0)
1488 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1489 if (g->sock_watch >= 0)
1490 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1500 g->stdout_watch = -1;
1503 if (g->subprocess_quit_cb)
1504 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1507 /* This function is called whenever qemu prints something on stdout.
1508 * Qemu's stdout is also connected to the guest's serial console, so
1509 * we see kernel messages here too.
1512 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1513 int watch, int fd, int events)
1521 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1522 g, g->state, fd, events);
1525 if (g->fd[1] != fd) {
1526 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1530 n = read (fd, buf, sizeof buf);
1532 /* Hopefully this indicates the qemu child process has died. */
1538 if (errno != EINTR && errno != EAGAIN)
1539 perrorf (g, "read");
1543 /* In verbose mode, copy all log messages to stderr. */
1547 /* It's an actual log message, send it upwards if anyone is listening. */
1548 if (g->log_message_cb)
1549 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1552 /* The function is called whenever we can read something on the
1553 * guestfsd (daemon inside the guest) communication socket.
1556 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1557 int watch, int fd, int events)
1565 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1566 g, g->state, fd, events);
1568 if (g->sock != fd) {
1569 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1573 if (g->msg_in_size <= g->msg_in_allocated) {
1574 g->msg_in_allocated += 4096;
1575 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1577 n = read (g->sock, g->msg_in + g->msg_in_size,
1578 g->msg_in_allocated - g->msg_in_size);
1586 if (errno != EINTR && errno != EAGAIN)
1587 perrorf (g, "read");
1591 g->msg_in_size += n;
1593 /* Have we got enough of a message to be able to process it yet? */
1595 if (g->msg_in_size < 4) return;
1597 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1598 if (!xdr_uint32_t (&xdr, &len)) {
1599 error (g, _("can't decode length word"));
1603 /* Length is normally the length of the message, but when guestfsd
1604 * starts up it sends a "magic" value (longer than any possible
1605 * message). Check for this.
1607 if (len == GUESTFS_LAUNCH_FLAG) {
1608 if (g->state != LAUNCHING)
1609 error (g, _("received magic signature from guestfsd, but in state %d"),
1611 else if (g->msg_in_size != 4)
1612 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1616 if (g->launch_done_cb)
1617 g->launch_done_cb (g, g->launch_done_cb_data);
1623 /* This can happen if a cancellation happens right at the end
1624 * of us sending a FileIn parameter to the daemon. Discard. The
1625 * daemon should send us an error message next.
1627 if (len == GUESTFS_CANCEL_FLAG) {
1628 g->msg_in_size -= 4;
1629 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1633 /* If this happens, it's pretty bad and we've probably lost
1636 if (len > GUESTFS_MESSAGE_MAX) {
1637 error (g, _("message length (%u) > maximum possible size (%d)"),
1638 len, GUESTFS_MESSAGE_MAX);
1642 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1644 /* Got the full message, begin processing it. */
1649 for (i = 0; i < g->msg_in_size; i += 16) {
1650 printf ("%04x: ", i);
1651 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1652 printf ("%02x ", (unsigned char) g->msg_in[j]);
1653 for (; j < i+16; ++j)
1656 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1657 if (isprint (g->msg_in[j]))
1658 printf ("%c", g->msg_in[j]);
1661 for (; j < i+16; ++j)
1668 /* Not in the expected state. */
1669 if (g->state != BUSY)
1670 error (g, _("state %d != BUSY"), g->state);
1672 /* Push the message up to the higher layer. */
1674 g->reply_cb (g, g->reply_cb_data, &xdr);
1676 /* This message (probably) should never be printed. */
1677 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1679 g->msg_in_size -= len + 4;
1680 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1681 if (g->msg_in_size > 0) goto again;
1684 /* Free the message buffer if it's grown excessively large. */
1685 if (g->msg_in_allocated > 65536) {
1688 g->msg_in_size = g->msg_in_allocated = 0;
1695 /* The function is called whenever we can write something on the
1696 * guestfsd (daemon inside the guest) communication socket.
1699 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1700 int watch, int fd, int events)
1706 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1707 g, g->state, fd, events);
1709 if (g->sock != fd) {
1710 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1714 if (g->state != BUSY) {
1715 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1720 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1721 g->msg_out_size - g->msg_out_pos);
1723 n = write (g->sock, g->msg_out + g->msg_out_pos,
1724 g->msg_out_size - g->msg_out_pos);
1728 perrorf (g, "write");
1729 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1735 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1737 g->msg_out_pos += n;
1739 /* More to write? */
1740 if (g->msg_out_pos < g->msg_out_size)
1744 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1748 g->msg_out_pos = g->msg_out_size = 0;
1750 /* Done writing, call the higher layer. */
1752 g->send_cb (g, g->send_cb_data);
1756 guestfs_set_send_callback (guestfs_h *g,
1757 guestfs_send_cb cb, void *opaque)
1760 g->send_cb_data = opaque;
1764 guestfs_set_reply_callback (guestfs_h *g,
1765 guestfs_reply_cb cb, void *opaque)
1768 g->reply_cb_data = opaque;
1772 guestfs_set_log_message_callback (guestfs_h *g,
1773 guestfs_log_message_cb cb, void *opaque)
1775 g->log_message_cb = cb;
1776 g->log_message_cb_data = opaque;
1780 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1781 guestfs_subprocess_quit_cb cb, void *opaque)
1783 g->subprocess_quit_cb = cb;
1784 g->subprocess_quit_cb_data = opaque;
1788 guestfs_set_launch_done_callback (guestfs_h *g,
1789 guestfs_launch_done_cb cb, void *opaque)
1791 g->launch_done_cb = cb;
1792 g->launch_done_cb_data = opaque;
1795 /* Access to the handle's main loop and the default main loop. */
1797 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1799 g->main_loop = main_loop;
1803 guestfs_get_main_loop (guestfs_h *g)
1805 return g->main_loop;
1809 guestfs_get_default_main_loop (void)
1811 return (guestfs_main_loop *) &default_main_loop;
1814 /* Change the daemon socket handler so that we are now writing.
1815 * This sets the handle to sock_write_event.
1818 guestfs__switch_to_sending (guestfs_h *g)
1820 if (g->sock_watch >= 0) {
1821 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1822 error (g, _("remove_handle failed"));
1829 g->main_loop->add_handle (g->main_loop, g, g->sock,
1830 GUESTFS_HANDLE_WRITABLE,
1831 sock_write_event, NULL);
1832 if (g->sock_watch == -1) {
1833 error (g, _("add_handle failed"));
1841 guestfs__switch_to_receiving (guestfs_h *g)
1843 if (g->sock_watch >= 0) {
1844 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1845 error (g, _("remove_handle failed"));
1852 g->main_loop->add_handle (g->main_loop, g, g->sock,
1853 GUESTFS_HANDLE_READABLE,
1854 sock_read_event, NULL);
1855 if (g->sock_watch == -1) {
1856 error (g, _("add_handle failed"));
1863 /* Dispatch a call (len + header + args) to the remote daemon,
1864 * synchronously (ie. using the guest's main loop to wait until
1865 * it has been sent). Returns -1 for error, or the serial
1866 * number of the message.
1869 send_cb (guestfs_h *g, void *data)
1871 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1874 ml->main_loop_quit (ml, g);
1878 guestfs__send_sync (guestfs_h *g, int proc_nr,
1879 xdrproc_t xdrp, char *args)
1881 struct guestfs_message_header hdr;
1884 int serial = g->msg_next_serial++;
1886 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1888 if (g->state != BUSY) {
1889 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1893 /* This is probably an internal error. Or perhaps we should just
1894 * free the buffer anyway?
1896 if (g->msg_out != NULL) {
1897 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1901 /* We have to allocate this message buffer on the heap because
1902 * it is quite large (although will be mostly unused). We
1903 * can't allocate it on the stack because in some environments
1904 * we have quite limited stack space available, notably when
1905 * running in the JVM.
1907 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1908 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1910 /* Serialize the header. */
1911 hdr.prog = GUESTFS_PROGRAM;
1912 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1914 hdr.direction = GUESTFS_DIRECTION_CALL;
1915 hdr.serial = serial;
1916 hdr.status = GUESTFS_STATUS_OK;
1918 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1919 error (g, _("xdr_guestfs_message_header failed"));
1923 /* Serialize the args. If any, because some message types
1924 * have no parameters.
1927 if (!(*xdrp) (&xdr, args)) {
1928 error (g, _("dispatch failed to marshal args"));
1933 /* Get the actual length of the message, resize the buffer to match
1934 * the actual length, and write the length word at the beginning.
1936 len = xdr_getpos (&xdr);
1939 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1940 g->msg_out_size = len + 4;
1943 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1944 xdr_uint32_t (&xdr, &len);
1946 if (guestfs__switch_to_sending (g) == -1)
1950 guestfs_set_send_callback (g, send_cb, &sent);
1951 if (ml->main_loop_run (ml, g) == -1)
1954 error (g, _("send failed, see earlier error messages"));
1963 g->msg_out_size = 0;
1967 static int cancel = 0; /* XXX Implement file cancellation. */
1968 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1969 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1970 static int send_file_cancellation_sync (guestfs_h *g);
1971 static int send_file_complete_sync (guestfs_h *g);
1973 /* Synchronously send a file.
1977 * -2 daemon cancelled (we must read the error message)
1980 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1982 char buf[GUESTFS_MAX_CHUNK_SIZE];
1985 fd = open (filename, O_RDONLY);
1987 perrorf (g, "open: %s", filename);
1988 send_file_cancellation_sync (g);
1989 /* Daemon sees cancellation and won't reply, so caller can
1995 /* Send file in chunked encoding. */
1997 r = read (fd, buf, sizeof buf);
1998 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2001 err = send_file_data_sync (g, buf, r);
2003 if (err == -2) /* daemon sent cancellation */
2004 send_file_cancellation_sync (g);
2009 if (cancel) { /* cancel from either end */
2010 send_file_cancellation_sync (g);
2015 perrorf (g, "read: %s", filename);
2016 send_file_cancellation_sync (g);
2020 /* End of file, but before we send that, we need to close
2021 * the file and check for errors.
2023 if (close (fd) == -1) {
2024 perrorf (g, "close: %s", filename);
2025 send_file_cancellation_sync (g);
2029 return send_file_complete_sync (g);
2032 /* Send a chunk of file data. */
2034 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2036 return send_file_chunk_sync (g, 0, buf, len);
2039 /* Send a cancellation message. */
2041 send_file_cancellation_sync (guestfs_h *g)
2043 return send_file_chunk_sync (g, 1, NULL, 0);
2046 /* Send a file complete chunk. */
2048 send_file_complete_sync (guestfs_h *g)
2051 return send_file_chunk_sync (g, 0, buf, 0);
2054 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2057 static int check_for_daemon_cancellation (guestfs_h *g);
2060 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2064 guestfs_chunk chunk;
2066 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2068 if (g->state != BUSY) {
2069 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2073 /* This is probably an internal error. Or perhaps we should just
2074 * free the buffer anyway?
2076 if (g->msg_out != NULL) {
2077 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2081 /* Did the daemon send a cancellation message? */
2082 if (check_for_daemon_cancellation (g)) {
2084 fprintf (stderr, "got daemon cancellation\n");
2088 /* Allocate the chunk buffer. Don't use the stack to avoid
2089 * excessive stack usage and unnecessary copies.
2091 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2092 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2094 /* Serialize the chunk. */
2095 chunk.cancel = cancel;
2096 chunk.data.data_len = buflen;
2097 chunk.data.data_val = (char *) buf;
2099 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2100 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2106 len = xdr_getpos (&xdr);
2109 /* Reduce the size of the outgoing message buffer to the real length. */
2110 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2111 g->msg_out_size = len + 4;
2114 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2115 xdr_uint32_t (&xdr, &len);
2117 if (guestfs__switch_to_sending (g) == -1)
2121 guestfs_set_send_callback (g, send_cb, &sent);
2122 if (ml->main_loop_run (ml, g) == -1)
2125 error (g, _("send file chunk failed, see earlier error messages"));
2134 g->msg_out_size = 0;
2138 /* At this point we are sending FileIn file(s) to the guest, and not
2139 * expecting to read anything, so if we do read anything, it must be
2140 * a cancellation message. This checks for this case without blocking.
2143 check_for_daemon_cancellation (guestfs_h *g)
2153 FD_SET (g->sock, &rset);
2156 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2158 perrorf (g, "select");
2164 /* Read the message from the daemon. */
2165 r = xread (g->sock, buf, sizeof buf);
2167 perrorf (g, "read");
2171 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2172 xdr_uint32_t (&xdr, &flag);
2175 if (flag != GUESTFS_CANCEL_FLAG) {
2176 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2177 flag, GUESTFS_CANCEL_FLAG);
2184 /* Synchronously receive a file. */
2186 /* Returns -1 = error, 0 = EOF, 1 = more data */
2187 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2190 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2196 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2198 perrorf (g, "open: %s", filename);
2202 /* Receive the file in chunked encoding. */
2203 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2204 if (xwrite (fd, buf, len) == -1) {
2205 perrorf (g, "%s: write", filename);
2210 if (r == 0) break; /* End of file. */
2214 error (g, _("%s: error in chunked encoding"), filename);
2218 if (close (fd) == -1) {
2219 perrorf (g, "close: %s", filename);
2226 /* Send cancellation message to daemon, then wait until it
2227 * cancels (just throwing away data).
2231 uint32_t flag = GUESTFS_CANCEL_FLAG;
2233 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2234 xdr_uint32_t (&xdr, &flag);
2237 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2238 perrorf (g, _("write to daemon socket"));
2242 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2243 ; /* just discard it */
2248 /* Note that the reply callback can be called multiple times before
2249 * the main loop quits and we get back to the synchronous code. So
2250 * we have to be prepared to save multiple chunks on a list here.
2252 struct receive_file_ctx {
2253 int count; /* 0 if receive_file_cb not called, or
2254 * else count number of chunks.
2256 guestfs_chunk *chunks; /* Array of chunks. */
2260 free_chunks (struct receive_file_ctx *ctx)
2264 for (i = 0; i < ctx->count; ++i)
2265 free (ctx->chunks[i].data.data_val);
2271 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2273 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2274 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2275 guestfs_chunk chunk;
2277 if (ctx->count == -1) /* Parse error occurred previously. */
2280 ml->main_loop_quit (ml, g);
2282 memset (&chunk, 0, sizeof chunk);
2284 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2285 error (g, _("failed to parse file chunk"));
2292 /* Copy the chunk to the list. */
2293 ctx->chunks = safe_realloc (g, ctx->chunks,
2294 sizeof (guestfs_chunk) * (ctx->count+1));
2295 ctx->chunks[ctx->count] = chunk;
2299 /* Receive a chunk of file data. */
2300 /* Returns -1 = error, 0 = EOF, 1 = more data */
2302 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2304 struct receive_file_ctx ctx;
2305 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2312 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2313 (void) ml->main_loop_run (ml, g);
2314 guestfs_set_reply_callback (g, NULL, NULL);
2316 if (ctx.count == 0) {
2317 error (g, _("receive_file_data_sync: reply callback not called\n"));
2321 if (ctx.count == -1) {
2322 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2323 /* callback already freed the chunks */
2328 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2330 /* Process each chunk in the list. */
2331 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2334 for (i = 0; i < ctx.count; ++i) {
2335 if (ctx.chunks[i].cancel) {
2336 error (g, _("file receive cancelled by daemon"));
2338 if (buf) free (*buf);
2339 if (len_r) *len_r = 0;
2343 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2345 if (len_r) *len_r = len;
2350 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2351 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2352 ctx.chunks[i].data.data_len);
2354 len += ctx.chunks[i].data.data_len;
2357 if (len_r) *len_r = len;
2362 /* This is the default main loop implementation, using select(2). */
2365 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2366 guestfs_handle_event_cb cb, void *data)
2368 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2370 if (fd < 0 || fd >= FD_SETSIZE) {
2371 error (g, _("fd %d is out of range"), fd);
2375 if ((events & ~(GUESTFS_HANDLE_READABLE |
2376 GUESTFS_HANDLE_WRITABLE |
2377 GUESTFS_HANDLE_HANGUP |
2378 GUESTFS_HANDLE_ERROR)) != 0) {
2379 error (g, _("set of events (0x%x) contains unknown events"), events);
2384 error (g, _("set of events is empty"));
2388 if (FD_ISSET (fd, &ml->rset) ||
2389 FD_ISSET (fd, &ml->wset) ||
2390 FD_ISSET (fd, &ml->xset)) {
2391 error (g, _("fd %d is already registered"), fd);
2396 error (g, _("callback is NULL"));
2400 if ((events & GUESTFS_HANDLE_READABLE))
2401 FD_SET (fd, &ml->rset);
2402 if ((events & GUESTFS_HANDLE_WRITABLE))
2403 FD_SET (fd, &ml->wset);
2404 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2405 FD_SET (fd, &ml->xset);
2407 if (fd > ml->max_fd) {
2409 ml->handle_cb_data =
2410 safe_realloc (g, ml->handle_cb_data,
2411 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2413 ml->handle_cb_data[fd].cb = cb;
2414 ml->handle_cb_data[fd].g = g;
2415 ml->handle_cb_data[fd].data = data;
2419 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2424 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2426 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2428 if (fd < 0 || fd >= FD_SETSIZE) {
2429 error (g, _("fd %d is out of range"), fd);
2433 if (!FD_ISSET (fd, &ml->rset) &&
2434 !FD_ISSET (fd, &ml->wset) &&
2435 !FD_ISSET (fd, &ml->xset)) {
2436 error (g, _("fd %d was not registered"), fd);
2440 FD_CLR (fd, &ml->rset);
2441 FD_CLR (fd, &ml->wset);
2442 FD_CLR (fd, &ml->xset);
2444 if (fd == ml->max_fd) {
2446 ml->handle_cb_data =
2447 safe_realloc (g, ml->handle_cb_data,
2448 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2457 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2458 guestfs_handle_timeout_cb cb, void *data)
2460 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2462 abort (); /* XXX not implemented yet */
2466 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2468 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2470 abort (); /* XXX not implemented yet */
2473 /* The 'g' parameter is just used for error reporting. Events
2474 * for multiple handles can be dispatched by running the main
2478 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2480 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2482 fd_set rset2, wset2, xset2;
2484 if (ml->is_running) {
2485 error (g, _("select_main_loop_run: this cannot be called recursively"));
2491 while (ml->is_running) {
2492 if (ml->nr_fds == 0)
2498 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2500 if (errno == EINTR || errno == EAGAIN)
2502 perrorf (g, "select");
2507 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2509 if (FD_ISSET (fd, &rset2))
2510 events |= GUESTFS_HANDLE_READABLE;
2511 if (FD_ISSET (fd, &wset2))
2512 events |= GUESTFS_HANDLE_WRITABLE;
2513 if (FD_ISSET (fd, &xset2))
2514 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2517 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2518 ml->handle_cb_data[fd].g,
2519 ml->handle_cb_data[fd].data,
2530 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2532 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2534 /* Note that legitimately ml->is_running can be zero when
2535 * this function is called.