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 **cmdline; /* Qemu command line. */
171 char *path; /* Path to kernel, initrd. */
172 char *qemu; /* Qemu binary. */
173 char *append; /* Append to kernel command line. */
178 guestfs_abort_cb abort_cb;
179 guestfs_error_handler_cb error_cb;
180 void * error_cb_data;
181 guestfs_send_cb send_cb;
183 guestfs_reply_cb reply_cb;
184 void * reply_cb_data;
185 guestfs_log_message_cb log_message_cb;
186 void * log_message_cb_data;
187 guestfs_subprocess_quit_cb subprocess_quit_cb;
188 void * subprocess_quit_cb_data;
189 guestfs_launch_done_cb launch_done_cb;
190 void * launch_done_cb_data;
192 /* Main loop used by this handle. */
193 guestfs_main_loop *main_loop;
195 /* Messages sent and received from the daemon. */
197 int msg_in_size, msg_in_allocated;
199 int msg_out_size, msg_out_pos;
204 static guestfs_h *handles = NULL;
205 static int atexit_handler_set = 0;
208 guestfs_create (void)
213 g = malloc (sizeof (*g));
216 memset (g, 0, sizeof (*g));
223 g->stdout_watch = -1;
227 g->error_cb = default_error_cb;
228 g->error_cb_data = NULL;
230 str = getenv ("LIBGUESTFS_DEBUG");
231 g->verbose = str != NULL && strcmp (str, "1") == 0;
233 str = getenv ("LIBGUESTFS_PATH");
234 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
235 if (!g->path) goto error;
237 str = getenv ("LIBGUESTFS_QEMU");
238 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
239 if (!g->qemu) goto error;
241 str = getenv ("LIBGUESTFS_APPEND");
243 g->append = strdup (str);
244 if (!g->append) goto error;
247 g->main_loop = guestfs_get_default_main_loop ();
249 /* Start with large serial numbers so they are easy to spot
250 * inside the protocol.
252 g->msg_next_serial = 0x00123400;
254 /* Link the handles onto a global list. This is the one area
255 * where the library needs to be made thread-safe. (XXX)
257 /* acquire mutex (XXX) */
260 if (!atexit_handler_set) {
261 atexit (close_handles);
262 atexit_handler_set = 1;
264 /* release mutex (XXX) */
267 fprintf (stderr, "new guestfs handle %p\n", g);
280 guestfs_close (guestfs_h *g)
286 if (g->state == NO_HANDLE) {
287 /* Not safe to call 'error' here, so ... */
288 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
293 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
295 /* Try to sync if autosync flag is set. */
296 if (g->autosync && g->state == READY) {
297 guestfs_umount_all (g);
301 /* Remove any handlers that might be called back before we kill the
304 g->log_message_cb = NULL;
306 if (g->state != CONFIG)
307 guestfs_kill_subprocess (g);
310 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
313 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
316 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
325 for (i = 0; i < g->cmdline_size; ++i)
326 free (g->cmdline[i]);
330 /* Mark the handle as dead before freeing it. */
331 g->state = NO_HANDLE;
333 /* acquire mutex (XXX) */
337 for (gg = handles; gg->next != g; gg = gg->next)
341 /* release mutex (XXX) */
345 free (g->last_error);
352 /* Close all open handles (called from atexit(3)). */
356 while (handles) guestfs_close (handles);
360 guestfs_last_error (guestfs_h *g)
362 return g->last_error;
366 set_last_error (guestfs_h *g, const char *msg)
368 free (g->last_error);
369 g->last_error = strdup (msg);
373 default_error_cb (guestfs_h *g, void *data, const char *msg)
375 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
379 guestfs_error (guestfs_h *g, const char *fs, ...)
385 vasprintf (&msg, fs, args);
388 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
389 set_last_error (g, msg);
395 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
402 vasprintf (&msg, fs, args);
407 strerror_r (err, buf, sizeof buf);
411 buf = strerror_r (err, _buf, sizeof _buf);
414 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
418 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
419 set_last_error (g, msg);
425 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
427 void *ptr = malloc (nbytes);
428 if (nbytes > 0 && !ptr) g->abort_cb ();
433 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
435 void *p = realloc (ptr, nbytes);
436 if (nbytes > 0 && !p) g->abort_cb ();
441 guestfs_safe_strdup (guestfs_h *g, const char *str)
443 char *s = strdup (str);
444 if (!s) g->abort_cb ();
449 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
451 void *p = malloc (size);
452 if (!p) g->abort_cb ();
453 memcpy (p, ptr, size);
458 xwrite (int fd, const void *buf, size_t len)
463 r = write (fd, buf, len);
475 xread (int fd, void *buf, size_t len)
480 r = read (fd, buf, len);
482 if (errno == EINTR || errno == EAGAIN)
495 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
501 guestfs_get_out_of_memory_handler (guestfs_h *g)
507 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
510 g->error_cb_data = data;
513 guestfs_error_handler_cb
514 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
516 if (data_rtn) *data_rtn = g->error_cb_data;
521 guestfs_set_verbose (guestfs_h *g, int v)
528 guestfs_get_verbose (guestfs_h *g)
534 guestfs_set_autosync (guestfs_h *g, int a)
541 guestfs_get_autosync (guestfs_h *g)
547 guestfs_set_path (guestfs_h *g, const char *path)
554 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
559 guestfs_get_path (guestfs_h *g)
565 guestfs_set_qemu (guestfs_h *g, const char *qemu)
570 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
575 guestfs_get_qemu (guestfs_h *g)
581 guestfs_set_append (guestfs_h *g, const char *append)
586 g->append = append ? safe_strdup (g, append) : NULL;
591 guestfs_get_append (guestfs_h *g)
596 /* Add a string to the current command line. */
598 incr_cmdline_size (guestfs_h *g)
600 if (g->cmdline == NULL) {
601 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
603 g->cmdline = safe_malloc (g, sizeof (char *));
604 g->cmdline[0] = NULL;
608 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
612 add_cmdline (guestfs_h *g, const char *str)
614 if (g->state != CONFIG) {
616 _("command line cannot be altered after qemu subprocess launched"));
620 incr_cmdline_size (g);
621 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
626 guestfs_config (guestfs_h *g,
627 const char *qemu_param, const char *qemu_value)
629 if (qemu_param[0] != '-') {
630 error (g, _("guestfs_config: parameter must begin with '-' character"));
634 /* A bit fascist, but the user will probably break the extra
635 * parameters that we add if they try to set any of these.
637 if (strcmp (qemu_param, "-kernel") == 0 ||
638 strcmp (qemu_param, "-initrd") == 0 ||
639 strcmp (qemu_param, "-nographic") == 0 ||
640 strcmp (qemu_param, "-serial") == 0 ||
641 strcmp (qemu_param, "-vnc") == 0 ||
642 strcmp (qemu_param, "-full-screen") == 0 ||
643 strcmp (qemu_param, "-std-vga") == 0 ||
644 strcmp (qemu_param, "-vnc") == 0) {
645 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
649 if (add_cmdline (g, qemu_param) != 0) return -1;
651 if (qemu_value != NULL) {
652 if (add_cmdline (g, qemu_value) != 0) return -1;
659 guestfs_add_drive (guestfs_h *g, const char *filename)
661 size_t len = strlen (filename) + 64;
664 if (strchr (filename, ',') != NULL) {
665 error (g, _("filename cannot contain ',' (comma) character"));
669 if (access (filename, F_OK) == -1) {
670 perrorf (g, "%s", filename);
674 snprintf (buf, len, "file=%s", filename);
676 return guestfs_config (g, "-drive", buf);
680 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
682 size_t len = strlen (filename) + 64;
685 if (strchr (filename, ',') != NULL) {
686 error (g, _("filename cannot contain ',' (comma) character"));
690 if (access (filename, F_OK) == -1) {
691 perrorf (g, "%s", filename);
695 snprintf (buf, len, "file=%s,snapshot=on", filename);
697 return guestfs_config (g, "-drive", buf);
701 guestfs_add_cdrom (guestfs_h *g, const char *filename)
703 if (strchr (filename, ',') != NULL) {
704 error (g, _("filename cannot contain ',' (comma) character"));
708 if (access (filename, F_OK) == -1) {
709 perrorf (g, "%s", filename);
713 return guestfs_config (g, "-cdrom", filename);
716 /* Returns true iff file is contained in dir. */
718 dir_contains_file (const char *dir, const char *file)
720 int dirlen = strlen (dir);
721 int filelen = strlen (file);
722 int len = dirlen+filelen+2;
725 snprintf (path, len, "%s/%s", dir, file);
726 return access (path, F_OK) == 0;
729 /* Returns true iff every listed file is contained in 'dir'. */
731 dir_contains_files (const char *dir, ...)
736 va_start (args, dir);
737 while ((file = va_arg (args, const char *)) != NULL) {
738 if (!dir_contains_file (dir, file)) {
747 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
749 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
750 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
751 static const char *supermin_name =
752 "initramfs." REPO "." host_cpu ".supermin.img";
753 static const char *supermin_hostfiles_name =
754 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
757 guestfs_launch (guestfs_h *g)
759 static const char *dir_template = "/tmp/libguestfsXXXXXX";
760 int r, i, pmore, memsize;
764 char *path, *pelem, *pend;
765 char *kernel = NULL, *initrd = NULL;
767 struct sockaddr_un addr;
771 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
775 if (g->state != CONFIG) {
776 error (g, _("qemu has already been launched"));
780 /* Make the temporary directory. */
782 g->tmpdir = safe_strdup (g, dir_template);
783 if (mkdtemp (g->tmpdir) == NULL) {
784 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
789 /* First search g->path for the supermin appliance, and try to
790 * synthesize a kernel and initrd from that. If it fails, we
791 * try the path search again looking for a backup ordinary
794 pelem = path = safe_strdup (g, g->path);
796 pend = strchrnul (pelem, ':');
797 pmore = *pend == ':';
801 /* Empty element of "." means cwd. */
802 if (len == 0 || (len == 1 && *pelem == '.')) {
805 "looking for supermin appliance in current directory\n");
806 if (dir_contains_files (".",
807 supermin_name, supermin_hostfiles_name,
808 "kmod.whitelist", NULL)) {
809 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
814 /* Look at <path>/supermin* etc. */
817 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
819 if (dir_contains_files (pelem,
820 supermin_name, supermin_hostfiles_name,
821 "kmod.whitelist", NULL)) {
822 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
833 if (kernel == NULL || initrd == NULL) {
834 /* Search g->path for the kernel and initrd. */
835 pelem = path = safe_strdup (g, g->path);
837 pend = strchrnul (pelem, ':');
838 pmore = *pend == ':';
842 /* Empty element or "." means cwd. */
843 if (len == 0 || (len == 1 && *pelem == '.')) {
846 "looking for appliance in current directory\n");
847 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
848 kernel = safe_strdup (g, kernel_name);
849 initrd = safe_strdup (g, initrd_name);
853 /* Look at <path>/kernel etc. */
856 fprintf (stderr, "looking for appliance in %s\n", pelem);
858 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
859 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
860 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
861 sprintf (kernel, "%s/%s", pelem, kernel_name);
862 sprintf (initrd, "%s/%s", pelem, initrd_name);
873 if (kernel == NULL || initrd == NULL) {
874 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
875 kernel_name, initrd_name, g->path);
879 /* Choose a suitable memory size. Previously we tried to choose
880 * a minimal memory size, but this isn't really necessary since
881 * recent QEMU and KVM don't do anything nasty like locking
882 * memory into core any more. This we can safely choose a
883 * large, generous amount of memory, and it'll just get swapped
884 * on smaller systems.
888 /* Make the vmchannel socket. */
889 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
892 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
907 if (r == 0) { /* Child (qemu). */
910 char memsize_str[256];
912 /* Set up the full command line. Do this in the subprocess so we
913 * don't need to worry about cleaning up.
915 g->cmdline[0] = g->qemu;
917 /* Construct the -net channel parameter for qemu. */
918 snprintf (vmchannel, sizeof vmchannel,
919 "channel,%d:unix:%s,server,nowait",
920 VMCHANNEL_PORT, unixsock);
922 /* Linux kernel command line. */
923 snprintf (append, sizeof append,
924 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
925 VMCHANNEL_ADDR, VMCHANNEL_PORT,
926 g->verbose ? " guestfs_verbose=1" : "",
927 g->append ? " " : "", g->append ? g->append : "");
929 snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
931 add_cmdline (g, "-m");
932 add_cmdline (g, memsize_str);
934 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
936 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
937 add_cmdline (g, "-kernel");
938 add_cmdline (g, (char *) kernel);
939 add_cmdline (g, "-initrd");
940 add_cmdline (g, (char *) initrd);
941 add_cmdline (g, "-append");
942 add_cmdline (g, append);
943 add_cmdline (g, "-nographic");
944 add_cmdline (g, "-serial");
945 add_cmdline (g, "stdio");
946 add_cmdline (g, "-net");
947 add_cmdline (g, vmchannel);
948 add_cmdline (g, "-net");
949 add_cmdline (g, "user,vlan=0");
950 add_cmdline (g, "-net");
951 add_cmdline (g, "nic,model=virtio,vlan=0");
952 incr_cmdline_size (g);
953 g->cmdline[g->cmdline_size-1] = NULL;
956 fprintf (stderr, "%s", g->qemu);
957 for (i = 0; g->cmdline[i]; ++i)
958 fprintf (stderr, " %s", g->cmdline[i]);
959 fprintf (stderr, "\n");
962 /* Set up stdin, stdout. */
973 /* Set up a new process group, so we can signal this process
974 * and all subprocesses (eg. if qemu is really a shell script).
979 execv (g->qemu, g->cmdline); /* Run qemu. */
984 /* Parent (library). */
992 /* Fork the recovery process off which will kill qemu if the parent
993 * process fails to do so (eg. if the parent segfaults).
997 pid_t qemu_pid = g->pid;
998 pid_t parent_pid = getppid ();
1000 /* Writing to argv is hideously complicated and error prone. See:
1001 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1004 /* Loop around waiting for one or both of the other processes to
1005 * disappear. It's fair to say this is very hairy. The PIDs that
1006 * we are looking at might be reused by another process. We are
1007 * effectively polling. Is the cure worse than the disease?
1010 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1012 if (kill (parent_pid, 0) == -1) {
1013 /* Parent's gone away, qemu still around, so kill qemu. */
1021 /* Don't worry, if the fork failed, this will be -1. The recovery
1022 * process isn't essential.
1026 /* Start the clock ... */
1029 /* Close the other ends of the pipe. */
1033 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1034 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1035 perrorf (g, "fcntl");
1039 g->fd[0] = wfd[1]; /* stdin of child */
1040 g->fd[1] = rfd[0]; /* stdout of child */
1042 /* Open the Unix socket. The vmchannel implementation that got
1043 * merged with qemu sucks in a number of ways. Both ends do
1044 * connect(2), which means that no one knows what, if anything, is
1045 * connected to the other end, or if it becomes disconnected. Even
1046 * worse, we have to wait some indeterminate time for qemu to create
1047 * the socket and connect to it (which happens very early in qemu's
1048 * start-up), so any code that uses vmchannel is inherently racy.
1049 * Hence this silly loop.
1051 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1052 if (g->sock == -1) {
1053 perrorf (g, "socket");
1057 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1058 perrorf (g, "fcntl");
1062 addr.sun_family = AF_UNIX;
1063 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1064 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1067 /* Always sleep at least once to give qemu a small chance to start up. */
1070 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1071 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1074 if (errno != ENOENT)
1075 perrorf (g, "connect");
1080 error (g, _("failed to connect to vmchannel socket"));
1084 /* Watch the file descriptors. */
1087 g->msg_in_size = g->msg_in_allocated = 0;
1091 g->msg_out_size = 0;
1095 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1096 GUESTFS_HANDLE_READABLE,
1097 stdout_event, NULL);
1098 if (g->stdout_watch == -1) {
1099 error (g, _("could not watch qemu stdout"));
1103 if (guestfs__switch_to_receiving (g) == -1)
1106 g->state = LAUNCHING;
1110 if (g->stdout_watch >= 0)
1111 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1112 if (g->sock_watch >= 0)
1113 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1122 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1123 waitpid (g->pid, NULL, 0);
1124 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1131 g->stdout_watch = -1;
1140 /* This function does the hard work of building the supermin appliance
1141 * on the fly. 'path' is the directory containing the control files.
1142 * 'kernel' and 'initrd' are where we will return the names of the
1143 * kernel and initrd (only initrd is built). The work is done by
1144 * an external script. We just tell it where to put the result.
1147 build_supermin_appliance (guestfs_h *g, const char *path,
1148 char **kernel, char **initrd)
1153 snprintf (cmd, sizeof cmd,
1155 "guestfs-supermin-helper '%s' %s/kernel %s/initrd",
1157 path, g->tmpdir, g->tmpdir);
1160 if (r == -1 || WEXITSTATUS(r) != 0) {
1161 error (g, _("external command failed: %s"), cmd);
1169 finish_wait_ready (guestfs_h *g, void *vp)
1172 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1175 g->main_loop->main_loop_quit (g->main_loop, g);
1179 guestfs_wait_ready (guestfs_h *g)
1181 int finished = 0, r;
1183 if (g->state == READY) return 0;
1185 if (g->state == BUSY) {
1186 error (g, _("qemu has finished launching already"));
1190 if (g->state != LAUNCHING) {
1191 error (g, _("qemu has not been launched yet"));
1195 g->launch_done_cb = finish_wait_ready;
1196 g->launch_done_cb_data = &finished;
1197 r = g->main_loop->main_loop_run (g->main_loop, g);
1198 g->launch_done_cb = NULL;
1199 g->launch_done_cb_data = NULL;
1201 if (r == -1) return -1;
1203 if (finished != 1) {
1204 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1208 /* This is possible in some really strange situations, such as
1209 * guestfsd starts up OK but then qemu immediately exits. Check for
1210 * it because the caller is probably expecting to be able to send
1211 * commands after this function returns.
1213 if (g->state != READY) {
1214 error (g, _("qemu launched and contacted daemon, but state != READY"));
1222 guestfs_kill_subprocess (guestfs_h *g)
1224 if (g->state == CONFIG) {
1225 error (g, _("no subprocess to kill"));
1230 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1232 kill (g->pid, SIGTERM);
1233 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1238 /* Access current state. */
1240 guestfs_is_config (guestfs_h *g)
1242 return g->state == CONFIG;
1246 guestfs_is_launching (guestfs_h *g)
1248 return g->state == LAUNCHING;
1252 guestfs_is_ready (guestfs_h *g)
1254 return g->state == READY;
1258 guestfs_is_busy (guestfs_h *g)
1260 return g->state == BUSY;
1264 guestfs_get_state (guestfs_h *g)
1270 guestfs_set_ready (guestfs_h *g)
1272 if (g->state != BUSY) {
1273 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1282 guestfs_set_busy (guestfs_h *g)
1284 if (g->state != READY) {
1285 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1294 guestfs_end_busy (guestfs_h *g)
1306 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1312 /* Structure-freeing functions. These rely on the fact that the
1313 * structure format is identical to the XDR format. See note in
1317 guestfs_free_int_bool (struct guestfs_int_bool *x)
1323 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1325 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1330 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1332 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1337 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1339 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1343 /* We don't know if stdout_event or sock_read_event will be the
1344 * first to receive EOF if the qemu process dies. This function
1345 * has the common cleanup code for both.
1348 child_cleanup (guestfs_h *g)
1351 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1352 /*kill (g->pid, SIGTERM);*/
1353 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1354 waitpid (g->pid, NULL, 0);
1355 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1356 if (g->stdout_watch >= 0)
1357 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1358 if (g->sock_watch >= 0)
1359 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1369 g->stdout_watch = -1;
1372 if (g->subprocess_quit_cb)
1373 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1376 /* This function is called whenever qemu prints something on stdout.
1377 * Qemu's stdout is also connected to the guest's serial console, so
1378 * we see kernel messages here too.
1381 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1382 int watch, int fd, int events)
1390 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1391 g, g->state, fd, events);
1394 if (g->fd[1] != fd) {
1395 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1399 n = read (fd, buf, sizeof buf);
1401 /* Hopefully this indicates the qemu child process has died. */
1407 if (errno != EINTR && errno != EAGAIN)
1408 perrorf (g, "read");
1412 /* In verbose mode, copy all log messages to stderr. */
1416 /* It's an actual log message, send it upwards if anyone is listening. */
1417 if (g->log_message_cb)
1418 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1421 /* The function is called whenever we can read something on the
1422 * guestfsd (daemon inside the guest) communication socket.
1425 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1426 int watch, int fd, int events)
1434 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1435 g, g->state, fd, events);
1437 if (g->sock != fd) {
1438 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1442 if (g->msg_in_size <= g->msg_in_allocated) {
1443 g->msg_in_allocated += 4096;
1444 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1446 n = read (g->sock, g->msg_in + g->msg_in_size,
1447 g->msg_in_allocated - g->msg_in_size);
1455 if (errno != EINTR && errno != EAGAIN)
1456 perrorf (g, "read");
1460 g->msg_in_size += n;
1462 /* Have we got enough of a message to be able to process it yet? */
1464 if (g->msg_in_size < 4) return;
1466 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1467 if (!xdr_uint32_t (&xdr, &len)) {
1468 error (g, _("can't decode length word"));
1472 /* Length is normally the length of the message, but when guestfsd
1473 * starts up it sends a "magic" value (longer than any possible
1474 * message). Check for this.
1476 if (len == GUESTFS_LAUNCH_FLAG) {
1477 if (g->state != LAUNCHING)
1478 error (g, _("received magic signature from guestfsd, but in state %d"),
1480 else if (g->msg_in_size != 4)
1481 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1485 if (g->launch_done_cb)
1486 g->launch_done_cb (g, g->launch_done_cb_data);
1492 /* This can happen if a cancellation happens right at the end
1493 * of us sending a FileIn parameter to the daemon. Discard. The
1494 * daemon should send us an error message next.
1496 if (len == GUESTFS_CANCEL_FLAG) {
1497 g->msg_in_size -= 4;
1498 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1502 /* If this happens, it's pretty bad and we've probably lost
1505 if (len > GUESTFS_MESSAGE_MAX) {
1506 error (g, _("message length (%u) > maximum possible size (%d)"),
1507 len, GUESTFS_MESSAGE_MAX);
1511 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1513 /* Got the full message, begin processing it. */
1518 for (i = 0; i < g->msg_in_size; i += 16) {
1519 printf ("%04x: ", i);
1520 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1521 printf ("%02x ", (unsigned char) g->msg_in[j]);
1522 for (; j < i+16; ++j)
1525 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1526 if (isprint (g->msg_in[j]))
1527 printf ("%c", g->msg_in[j]);
1530 for (; j < i+16; ++j)
1537 /* Not in the expected state. */
1538 if (g->state != BUSY)
1539 error (g, _("state %d != BUSY"), g->state);
1541 /* Push the message up to the higher layer. */
1543 g->reply_cb (g, g->reply_cb_data, &xdr);
1545 /* This message (probably) should never be printed. */
1546 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1548 g->msg_in_size -= len + 4;
1549 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1550 if (g->msg_in_size > 0) goto again;
1553 /* Free the message buffer if it's grown excessively large. */
1554 if (g->msg_in_allocated > 65536) {
1557 g->msg_in_size = g->msg_in_allocated = 0;
1564 /* The function is called whenever we can write something on the
1565 * guestfsd (daemon inside the guest) communication socket.
1568 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1569 int watch, int fd, int events)
1575 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1576 g, g->state, fd, events);
1578 if (g->sock != fd) {
1579 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1583 if (g->state != BUSY) {
1584 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1589 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1590 g->msg_out_size - g->msg_out_pos);
1592 n = write (g->sock, g->msg_out + g->msg_out_pos,
1593 g->msg_out_size - g->msg_out_pos);
1595 if (errno != EAGAIN)
1596 perrorf (g, "write");
1601 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1603 g->msg_out_pos += n;
1605 /* More to write? */
1606 if (g->msg_out_pos < g->msg_out_size)
1610 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1614 g->msg_out_pos = g->msg_out_size = 0;
1616 /* Done writing, call the higher layer. */
1618 g->send_cb (g, g->send_cb_data);
1622 guestfs_set_send_callback (guestfs_h *g,
1623 guestfs_send_cb cb, void *opaque)
1626 g->send_cb_data = opaque;
1630 guestfs_set_reply_callback (guestfs_h *g,
1631 guestfs_reply_cb cb, void *opaque)
1634 g->reply_cb_data = opaque;
1638 guestfs_set_log_message_callback (guestfs_h *g,
1639 guestfs_log_message_cb cb, void *opaque)
1641 g->log_message_cb = cb;
1642 g->log_message_cb_data = opaque;
1646 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1647 guestfs_subprocess_quit_cb cb, void *opaque)
1649 g->subprocess_quit_cb = cb;
1650 g->subprocess_quit_cb_data = opaque;
1654 guestfs_set_launch_done_callback (guestfs_h *g,
1655 guestfs_launch_done_cb cb, void *opaque)
1657 g->launch_done_cb = cb;
1658 g->launch_done_cb_data = opaque;
1661 /* Access to the handle's main loop and the default main loop. */
1663 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1665 g->main_loop = main_loop;
1669 guestfs_get_main_loop (guestfs_h *g)
1671 return g->main_loop;
1675 guestfs_get_default_main_loop (void)
1677 return (guestfs_main_loop *) &default_main_loop;
1680 /* Change the daemon socket handler so that we are now writing.
1681 * This sets the handle to sock_write_event.
1684 guestfs__switch_to_sending (guestfs_h *g)
1686 if (g->sock_watch >= 0) {
1687 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1688 error (g, _("remove_handle failed"));
1695 g->main_loop->add_handle (g->main_loop, g, g->sock,
1696 GUESTFS_HANDLE_WRITABLE,
1697 sock_write_event, NULL);
1698 if (g->sock_watch == -1) {
1699 error (g, _("add_handle failed"));
1707 guestfs__switch_to_receiving (guestfs_h *g)
1709 if (g->sock_watch >= 0) {
1710 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1711 error (g, _("remove_handle failed"));
1718 g->main_loop->add_handle (g->main_loop, g, g->sock,
1719 GUESTFS_HANDLE_READABLE,
1720 sock_read_event, NULL);
1721 if (g->sock_watch == -1) {
1722 error (g, _("add_handle failed"));
1729 /* Dispatch a call (len + header + args) to the remote daemon,
1730 * synchronously (ie. using the guest's main loop to wait until
1731 * it has been sent). Returns -1 for error, or the serial
1732 * number of the message.
1735 send_cb (guestfs_h *g, void *data)
1737 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1740 ml->main_loop_quit (ml, g);
1744 guestfs__send_sync (guestfs_h *g, int proc_nr,
1745 xdrproc_t xdrp, char *args)
1747 struct guestfs_message_header hdr;
1750 int serial = g->msg_next_serial++;
1752 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1754 if (g->state != BUSY) {
1755 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1759 /* This is probably an internal error. Or perhaps we should just
1760 * free the buffer anyway?
1762 if (g->msg_out != NULL) {
1763 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1767 /* We have to allocate this message buffer on the heap because
1768 * it is quite large (although will be mostly unused). We
1769 * can't allocate it on the stack because in some environments
1770 * we have quite limited stack space available, notably when
1771 * running in the JVM.
1773 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1774 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1776 /* Serialize the header. */
1777 hdr.prog = GUESTFS_PROGRAM;
1778 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1780 hdr.direction = GUESTFS_DIRECTION_CALL;
1781 hdr.serial = serial;
1782 hdr.status = GUESTFS_STATUS_OK;
1784 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1785 error (g, _("xdr_guestfs_message_header failed"));
1789 /* Serialize the args. If any, because some message types
1790 * have no parameters.
1793 if (!(*xdrp) (&xdr, args)) {
1794 error (g, _("dispatch failed to marshal args"));
1799 /* Get the actual length of the message, resize the buffer to match
1800 * the actual length, and write the length word at the beginning.
1802 len = xdr_getpos (&xdr);
1805 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1806 g->msg_out_size = len + 4;
1809 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1810 xdr_uint32_t (&xdr, &len);
1812 if (guestfs__switch_to_sending (g) == -1)
1816 guestfs_set_send_callback (g, send_cb, &sent);
1817 if (ml->main_loop_run (ml, g) == -1)
1820 error (g, _("send failed, see earlier error messages"));
1829 g->msg_out_size = 0;
1833 static int cancel = 0; /* XXX Implement file cancellation. */
1834 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1835 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1836 static int send_file_cancellation_sync (guestfs_h *g);
1837 static int send_file_complete_sync (guestfs_h *g);
1839 /* Synchronously send a file.
1843 * -2 daemon cancelled (we must read the error message)
1846 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1848 char buf[GUESTFS_MAX_CHUNK_SIZE];
1851 fd = open (filename, O_RDONLY);
1853 perrorf (g, "open: %s", filename);
1854 send_file_cancellation_sync (g);
1855 /* Daemon sees cancellation and won't reply, so caller can
1861 /* Send file in chunked encoding. */
1863 r = read (fd, buf, sizeof buf);
1864 if (r == -1 && (errno == EINTR || errno == EAGAIN))
1867 err = send_file_data_sync (g, buf, r);
1869 if (err == -2) /* daemon sent cancellation */
1870 send_file_cancellation_sync (g);
1875 if (cancel) { /* cancel from either end */
1876 send_file_cancellation_sync (g);
1881 perrorf (g, "read: %s", filename);
1882 send_file_cancellation_sync (g);
1886 /* End of file, but before we send that, we need to close
1887 * the file and check for errors.
1889 if (close (fd) == -1) {
1890 perrorf (g, "close: %s", filename);
1891 send_file_cancellation_sync (g);
1895 return send_file_complete_sync (g);
1898 /* Send a chunk of file data. */
1900 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1902 return send_file_chunk_sync (g, 0, buf, len);
1905 /* Send a cancellation message. */
1907 send_file_cancellation_sync (guestfs_h *g)
1909 return send_file_chunk_sync (g, 1, NULL, 0);
1912 /* Send a file complete chunk. */
1914 send_file_complete_sync (guestfs_h *g)
1917 return send_file_chunk_sync (g, 0, buf, 0);
1920 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1923 static int check_for_daemon_cancellation (guestfs_h *g);
1926 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
1930 guestfs_chunk chunk;
1932 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1934 if (g->state != BUSY) {
1935 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
1939 /* This is probably an internal error. Or perhaps we should just
1940 * free the buffer anyway?
1942 if (g->msg_out != NULL) {
1943 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1947 /* Did the daemon send a cancellation message? */
1948 if (check_for_daemon_cancellation (g)) {
1950 fprintf (stderr, "got daemon cancellation\n");
1954 /* Allocate the chunk buffer. Don't use the stack to avoid
1955 * excessive stack usage and unnecessary copies.
1957 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
1958 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1960 /* Serialize the chunk. */
1961 chunk.cancel = cancel;
1962 chunk.data.data_len = buflen;
1963 chunk.data.data_val = (char *) buf;
1965 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1966 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
1972 len = xdr_getpos (&xdr);
1975 /* Reduce the size of the outgoing message buffer to the real length. */
1976 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1977 g->msg_out_size = len + 4;
1980 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1981 xdr_uint32_t (&xdr, &len);
1983 if (guestfs__switch_to_sending (g) == -1)
1987 guestfs_set_send_callback (g, send_cb, &sent);
1988 if (ml->main_loop_run (ml, g) == -1)
1991 error (g, _("send file chunk failed, see earlier error messages"));
2000 g->msg_out_size = 0;
2004 /* At this point we are sending FileIn file(s) to the guest, and not
2005 * expecting to read anything, so if we do read anything, it must be
2006 * a cancellation message. This checks for this case without blocking.
2009 check_for_daemon_cancellation (guestfs_h *g)
2019 FD_SET (g->sock, &rset);
2022 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2024 perrorf (g, "select");
2030 /* Read the message from the daemon. */
2031 r = xread (g->sock, buf, sizeof buf);
2033 perrorf (g, "read");
2037 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2038 xdr_uint32_t (&xdr, &flag);
2041 if (flag != GUESTFS_CANCEL_FLAG) {
2042 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2043 flag, GUESTFS_CANCEL_FLAG);
2050 /* Synchronously receive a file. */
2052 /* Returns -1 = error, 0 = EOF, 1 = more data */
2053 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2056 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2062 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2064 perrorf (g, "open: %s", filename);
2068 /* Receive the file in chunked encoding. */
2069 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2070 if (xwrite (fd, buf, len) == -1) {
2071 perrorf (g, "%s: write", filename);
2076 if (r == 0) break; /* End of file. */
2080 error (g, _("%s: error in chunked encoding"), filename);
2084 if (close (fd) == -1) {
2085 perrorf (g, "close: %s", filename);
2092 /* Send cancellation message to daemon, then wait until it
2093 * cancels (just throwing away data).
2097 uint32_t flag = GUESTFS_CANCEL_FLAG;
2099 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2100 xdr_uint32_t (&xdr, &flag);
2103 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2104 perrorf (g, _("write to daemon socket"));
2108 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2109 ; /* just discard it */
2114 /* Note that the reply callback can be called multiple times before
2115 * the main loop quits and we get back to the synchronous code. So
2116 * we have to be prepared to save multiple chunks on a list here.
2118 struct receive_file_ctx {
2119 int count; /* 0 if receive_file_cb not called, or
2120 * else count number of chunks.
2122 guestfs_chunk *chunks; /* Array of chunks. */
2126 free_chunks (struct receive_file_ctx *ctx)
2130 for (i = 0; i < ctx->count; ++i)
2131 free (ctx->chunks[i].data.data_val);
2137 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2139 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2140 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2141 guestfs_chunk chunk;
2143 if (ctx->count == -1) /* Parse error occurred previously. */
2146 ml->main_loop_quit (ml, g);
2148 memset (&chunk, 0, sizeof chunk);
2150 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2151 error (g, _("failed to parse file chunk"));
2158 /* Copy the chunk to the list. */
2159 ctx->chunks = safe_realloc (g, ctx->chunks,
2160 sizeof (guestfs_chunk) * (ctx->count+1));
2161 ctx->chunks[ctx->count] = chunk;
2165 /* Receive a chunk of file data. */
2166 /* Returns -1 = error, 0 = EOF, 1 = more data */
2168 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2170 struct receive_file_ctx ctx;
2171 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2178 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2179 (void) ml->main_loop_run (ml, g);
2180 guestfs_set_reply_callback (g, NULL, NULL);
2182 if (ctx.count == 0) {
2183 error (g, _("receive_file_data_sync: reply callback not called\n"));
2187 if (ctx.count == -1) {
2188 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2189 /* callback already freed the chunks */
2194 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2196 /* Process each chunk in the list. */
2197 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2200 for (i = 0; i < ctx.count; ++i) {
2201 if (ctx.chunks[i].cancel) {
2202 error (g, _("file receive cancelled by daemon"));
2204 if (buf) free (*buf);
2205 if (len_r) *len_r = 0;
2209 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2211 if (len_r) *len_r = len;
2216 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2217 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2218 ctx.chunks[i].data.data_len);
2220 len += ctx.chunks[i].data.data_len;
2223 if (len_r) *len_r = len;
2228 /* This is the default main loop implementation, using select(2). */
2231 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2232 guestfs_handle_event_cb cb, void *data)
2234 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2236 if (fd < 0 || fd >= FD_SETSIZE) {
2237 error (g, _("fd %d is out of range"), fd);
2241 if ((events & ~(GUESTFS_HANDLE_READABLE |
2242 GUESTFS_HANDLE_WRITABLE |
2243 GUESTFS_HANDLE_HANGUP |
2244 GUESTFS_HANDLE_ERROR)) != 0) {
2245 error (g, _("set of events (0x%x) contains unknown events"), events);
2250 error (g, _("set of events is empty"));
2254 if (FD_ISSET (fd, &ml->rset) ||
2255 FD_ISSET (fd, &ml->wset) ||
2256 FD_ISSET (fd, &ml->xset)) {
2257 error (g, _("fd %d is already registered"), fd);
2262 error (g, _("callback is NULL"));
2266 if ((events & GUESTFS_HANDLE_READABLE))
2267 FD_SET (fd, &ml->rset);
2268 if ((events & GUESTFS_HANDLE_WRITABLE))
2269 FD_SET (fd, &ml->wset);
2270 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2271 FD_SET (fd, &ml->xset);
2273 if (fd > ml->max_fd) {
2275 ml->handle_cb_data =
2276 safe_realloc (g, ml->handle_cb_data,
2277 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2279 ml->handle_cb_data[fd].cb = cb;
2280 ml->handle_cb_data[fd].g = g;
2281 ml->handle_cb_data[fd].data = data;
2285 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2290 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2292 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2294 if (fd < 0 || fd >= FD_SETSIZE) {
2295 error (g, _("fd %d is out of range"), fd);
2299 if (!FD_ISSET (fd, &ml->rset) &&
2300 !FD_ISSET (fd, &ml->wset) &&
2301 !FD_ISSET (fd, &ml->xset)) {
2302 error (g, _("fd %d was not registered"), fd);
2306 FD_CLR (fd, &ml->rset);
2307 FD_CLR (fd, &ml->wset);
2308 FD_CLR (fd, &ml->xset);
2310 if (fd == ml->max_fd) {
2312 ml->handle_cb_data =
2313 safe_realloc (g, ml->handle_cb_data,
2314 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2323 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2324 guestfs_handle_timeout_cb cb, void *data)
2326 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2328 abort (); /* XXX not implemented yet */
2332 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2334 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2336 abort (); /* XXX not implemented yet */
2339 /* The 'g' parameter is just used for error reporting. Events
2340 * for multiple handles can be dispatched by running the main
2344 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2346 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2348 fd_set rset2, wset2, xset2;
2350 if (ml->is_running) {
2351 error (g, _("select_main_loop_run: this cannot be called recursively"));
2357 while (ml->is_running) {
2358 if (ml->nr_fds == 0)
2364 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2366 if (errno == EINTR || errno == EAGAIN)
2368 perrorf (g, "select");
2373 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2375 if (FD_ISSET (fd, &rset2))
2376 events |= GUESTFS_HANDLE_READABLE;
2377 if (FD_ISSET (fd, &wset2))
2378 events |= GUESTFS_HANDLE_WRITABLE;
2379 if (FD_ISSET (fd, &xset2))
2380 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2383 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2384 ml->handle_cb_data[fd].g,
2385 ml->handle_cb_data[fd].data,
2396 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2398 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2400 /* Note that legitimately ml->is_running can be zero when
2401 * this function is called.