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. */
180 guestfs_abort_cb abort_cb;
181 guestfs_error_handler_cb error_cb;
182 void * error_cb_data;
183 guestfs_send_cb send_cb;
185 guestfs_reply_cb reply_cb;
186 void * reply_cb_data;
187 guestfs_log_message_cb log_message_cb;
188 void * log_message_cb_data;
189 guestfs_subprocess_quit_cb subprocess_quit_cb;
190 void * subprocess_quit_cb_data;
191 guestfs_launch_done_cb launch_done_cb;
192 void * launch_done_cb_data;
194 /* Main loop used by this handle. */
195 guestfs_main_loop *main_loop;
197 /* Messages sent and received from the daemon. */
199 int msg_in_size, msg_in_allocated;
201 int msg_out_size, msg_out_pos;
206 static guestfs_h *handles = NULL;
207 static int atexit_handler_set = 0;
210 guestfs_create (void)
215 g = malloc (sizeof (*g));
218 memset (g, 0, sizeof (*g));
225 g->stdout_watch = -1;
229 g->error_cb = default_error_cb;
230 g->error_cb_data = NULL;
232 str = getenv ("LIBGUESTFS_DEBUG");
233 g->verbose = str != NULL && strcmp (str, "1") == 0;
235 str = getenv ("LIBGUESTFS_PATH");
236 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
237 if (!g->path) goto error;
239 str = getenv ("LIBGUESTFS_QEMU");
240 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
241 if (!g->qemu) goto error;
243 str = getenv ("LIBGUESTFS_APPEND");
245 g->append = strdup (str);
246 if (!g->append) goto error;
249 g->main_loop = guestfs_get_default_main_loop ();
251 /* Start with large serial numbers so they are easy to spot
252 * inside the protocol.
254 g->msg_next_serial = 0x00123400;
256 /* Link the handles onto a global list. This is the one area
257 * where the library needs to be made thread-safe. (XXX)
259 /* acquire mutex (XXX) */
262 if (!atexit_handler_set) {
263 atexit (close_handles);
264 atexit_handler_set = 1;
266 /* release mutex (XXX) */
269 fprintf (stderr, "new guestfs handle %p\n", g);
282 guestfs_close (guestfs_h *g)
288 if (g->state == NO_HANDLE) {
289 /* Not safe to call 'error' here, so ... */
290 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
295 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
297 /* Try to sync if autosync flag is set. */
298 if (g->autosync && g->state == READY) {
299 guestfs_umount_all (g);
303 /* Remove any handlers that might be called back before we kill the
306 g->log_message_cb = NULL;
308 if (g->state != CONFIG)
309 guestfs_kill_subprocess (g);
312 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
315 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
318 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
327 for (i = 0; i < g->cmdline_size; ++i)
328 free (g->cmdline[i]);
332 /* Mark the handle as dead before freeing it. */
333 g->state = NO_HANDLE;
335 /* acquire mutex (XXX) */
339 for (gg = handles; gg->next != g; gg = gg->next)
343 /* release mutex (XXX) */
347 free (g->last_error);
352 free (g->qemu_version);
356 /* Close all open handles (called from atexit(3)). */
360 while (handles) guestfs_close (handles);
364 guestfs_last_error (guestfs_h *g)
366 return g->last_error;
370 set_last_error (guestfs_h *g, const char *msg)
372 free (g->last_error);
373 g->last_error = strdup (msg);
377 default_error_cb (guestfs_h *g, void *data, const char *msg)
379 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
383 guestfs_error (guestfs_h *g, const char *fs, ...)
389 vasprintf (&msg, fs, args);
392 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
393 set_last_error (g, msg);
399 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
406 vasprintf (&msg, fs, args);
411 strerror_r (err, buf, sizeof buf);
415 buf = strerror_r (err, _buf, sizeof _buf);
418 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
422 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
423 set_last_error (g, msg);
429 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
431 void *ptr = malloc (nbytes);
432 if (nbytes > 0 && !ptr) g->abort_cb ();
437 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
439 void *p = realloc (ptr, nbytes);
440 if (nbytes > 0 && !p) g->abort_cb ();
445 guestfs_safe_strdup (guestfs_h *g, const char *str)
447 char *s = strdup (str);
448 if (!s) g->abort_cb ();
453 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
455 void *p = malloc (size);
456 if (!p) g->abort_cb ();
457 memcpy (p, ptr, size);
462 xwrite (int fd, const void *buf, size_t len)
467 r = write (fd, buf, len);
479 xread (int fd, void *buf, size_t len)
484 r = read (fd, buf, len);
486 if (errno == EINTR || errno == EAGAIN)
499 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
505 guestfs_get_out_of_memory_handler (guestfs_h *g)
511 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
514 g->error_cb_data = data;
517 guestfs_error_handler_cb
518 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
520 if (data_rtn) *data_rtn = g->error_cb_data;
525 guestfs_set_verbose (guestfs_h *g, int v)
532 guestfs_get_verbose (guestfs_h *g)
538 guestfs_set_autosync (guestfs_h *g, int a)
545 guestfs_get_autosync (guestfs_h *g)
551 guestfs_set_path (guestfs_h *g, const char *path)
558 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
563 guestfs_get_path (guestfs_h *g)
569 guestfs_set_qemu (guestfs_h *g, const char *qemu)
574 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
579 guestfs_get_qemu (guestfs_h *g)
585 guestfs_set_append (guestfs_h *g, const char *append)
590 g->append = append ? safe_strdup (g, append) : NULL;
595 guestfs_get_append (guestfs_h *g)
600 /* Add a string to the current command line. */
602 incr_cmdline_size (guestfs_h *g)
604 if (g->cmdline == NULL) {
605 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
607 g->cmdline = safe_malloc (g, sizeof (char *));
608 g->cmdline[0] = NULL;
612 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
616 add_cmdline (guestfs_h *g, const char *str)
618 if (g->state != CONFIG) {
620 _("command line cannot be altered after qemu subprocess launched"));
624 incr_cmdline_size (g);
625 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
630 guestfs_config (guestfs_h *g,
631 const char *qemu_param, const char *qemu_value)
633 if (qemu_param[0] != '-') {
634 error (g, _("guestfs_config: parameter must begin with '-' character"));
638 /* A bit fascist, but the user will probably break the extra
639 * parameters that we add if they try to set any of these.
641 if (strcmp (qemu_param, "-kernel") == 0 ||
642 strcmp (qemu_param, "-initrd") == 0 ||
643 strcmp (qemu_param, "-nographic") == 0 ||
644 strcmp (qemu_param, "-serial") == 0 ||
645 strcmp (qemu_param, "-full-screen") == 0 ||
646 strcmp (qemu_param, "-std-vga") == 0 ||
647 strcmp (qemu_param, "-vnc") == 0) {
648 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
652 if (add_cmdline (g, qemu_param) != 0) return -1;
654 if (qemu_value != NULL) {
655 if (add_cmdline (g, qemu_value) != 0) return -1;
662 guestfs_add_drive (guestfs_h *g, const char *filename)
664 size_t len = strlen (filename) + 64;
667 if (strchr (filename, ',') != NULL) {
668 error (g, _("filename cannot contain ',' (comma) character"));
672 if (access (filename, F_OK) == -1) {
673 perrorf (g, "%s", filename);
677 /* cache=off improves reliability in the event of a host crash. */
678 snprintf (buf, len, "file=%s,cache=off", filename);
680 return guestfs_config (g, "-drive", buf);
684 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
686 size_t len = strlen (filename) + 64;
689 if (strchr (filename, ',') != NULL) {
690 error (g, _("filename cannot contain ',' (comma) character"));
694 if (access (filename, F_OK) == -1) {
695 perrorf (g, "%s", filename);
699 snprintf (buf, len, "file=%s,snapshot=on", filename);
701 return guestfs_config (g, "-drive", buf);
705 guestfs_add_cdrom (guestfs_h *g, const char *filename)
707 if (strchr (filename, ',') != NULL) {
708 error (g, _("filename cannot contain ',' (comma) character"));
712 if (access (filename, F_OK) == -1) {
713 perrorf (g, "%s", filename);
717 return guestfs_config (g, "-cdrom", filename);
720 /* Returns true iff file is contained in dir. */
722 dir_contains_file (const char *dir, const char *file)
724 int dirlen = strlen (dir);
725 int filelen = strlen (file);
726 int len = dirlen+filelen+2;
729 snprintf (path, len, "%s/%s", dir, file);
730 return access (path, F_OK) == 0;
733 /* Returns true iff every listed file is contained in 'dir'. */
735 dir_contains_files (const char *dir, ...)
740 va_start (args, dir);
741 while ((file = va_arg (args, const char *)) != NULL) {
742 if (!dir_contains_file (dir, file)) {
751 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
752 static int test_qemu (guestfs_h *g);
753 static int qemu_supports (guestfs_h *g, const char *option);
755 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
756 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
757 static const char *supermin_name =
758 "initramfs." REPO "." host_cpu ".supermin.img";
759 static const char *supermin_hostfiles_name =
760 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
763 guestfs_launch (guestfs_h *g)
765 static const char *dir_template = "/tmp/libguestfsXXXXXX";
766 int r, i, pmore, memsize;
770 char *path, *pelem, *pend;
771 char *kernel = NULL, *initrd = NULL;
773 struct sockaddr_un addr;
777 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
781 if (g->state != CONFIG) {
782 error (g, _("qemu has already been launched"));
786 /* Make the temporary directory. */
788 g->tmpdir = safe_strdup (g, dir_template);
789 if (mkdtemp (g->tmpdir) == NULL) {
790 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
795 /* First search g->path for the supermin appliance, and try to
796 * synthesize a kernel and initrd from that. If it fails, we
797 * try the path search again looking for a backup ordinary
800 pelem = path = safe_strdup (g, g->path);
802 pend = strchrnul (pelem, ':');
803 pmore = *pend == ':';
807 /* Empty element of "." means cwd. */
808 if (len == 0 || (len == 1 && *pelem == '.')) {
811 "looking for supermin appliance in current directory\n");
812 if (dir_contains_files (".",
813 supermin_name, supermin_hostfiles_name,
814 "kmod.whitelist", NULL)) {
815 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
820 /* Look at <path>/supermin* etc. */
823 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
825 if (dir_contains_files (pelem,
826 supermin_name, supermin_hostfiles_name,
827 "kmod.whitelist", NULL)) {
828 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
839 if (kernel == NULL || initrd == NULL) {
840 /* Search g->path for the kernel and initrd. */
841 pelem = path = safe_strdup (g, g->path);
843 pend = strchrnul (pelem, ':');
844 pmore = *pend == ':';
848 /* Empty element or "." means cwd. */
849 if (len == 0 || (len == 1 && *pelem == '.')) {
852 "looking for appliance in current directory\n");
853 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
854 kernel = safe_strdup (g, kernel_name);
855 initrd = safe_strdup (g, initrd_name);
859 /* Look at <path>/kernel etc. */
862 fprintf (stderr, "looking for appliance in %s\n", pelem);
864 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
865 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
866 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
867 sprintf (kernel, "%s/%s", pelem, kernel_name);
868 sprintf (initrd, "%s/%s", pelem, initrd_name);
879 if (kernel == NULL || initrd == NULL) {
880 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
881 kernel_name, initrd_name, g->path);
885 /* Choose a suitable memory size. Previously we tried to choose
886 * a minimal memory size, but this isn't really necessary since
887 * recent QEMU and KVM don't do anything nasty like locking
888 * memory into core any more. Thus we can safely choose a
889 * large, generous amount of memory, and it'll just get swapped
890 * on smaller systems.
894 /* Get qemu help text and version. */
895 if (test_qemu (g) == -1)
898 /* Make the vmchannel socket. */
899 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
902 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
917 if (r == 0) { /* Child (qemu). */
920 char memsize_str[256];
922 /* Set up the full command line. Do this in the subprocess so we
923 * don't need to worry about cleaning up.
925 g->cmdline[0] = g->qemu;
927 /* Construct the -net channel parameter for qemu. */
928 snprintf (vmchannel, sizeof vmchannel,
929 "channel,%d:unix:%s,server,nowait",
930 VMCHANNEL_PORT, unixsock);
932 /* Linux kernel command line. */
933 snprintf (append, sizeof append,
934 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
935 VMCHANNEL_ADDR, VMCHANNEL_PORT,
936 g->verbose ? " guestfs_verbose=1" : "",
937 g->append ? " " : "", g->append ? g->append : "");
939 snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
941 add_cmdline (g, "-m");
942 add_cmdline (g, memsize_str);
943 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
944 add_cmdline (g, "-kernel");
945 add_cmdline (g, (char *) kernel);
946 add_cmdline (g, "-initrd");
947 add_cmdline (g, (char *) initrd);
948 add_cmdline (g, "-append");
949 add_cmdline (g, append);
950 add_cmdline (g, "-nographic");
951 add_cmdline (g, "-serial");
952 add_cmdline (g, "stdio");
953 add_cmdline (g, "-net");
954 add_cmdline (g, vmchannel);
955 add_cmdline (g, "-net");
956 add_cmdline (g, "user,vlan=0");
957 add_cmdline (g, "-net");
958 add_cmdline (g, "nic,model=virtio,vlan=0");
960 /* These options recommended by KVM developers to improve reliability. */
961 if (qemu_supports (g, "-no-hpet"))
962 add_cmdline (g, "-no-hpet");
964 if (qemu_supports (g, "-rtc-td-hack"))
965 add_cmdline (g, "-rtc-td-hack");
967 /* Finish off the command line. */
968 incr_cmdline_size (g);
969 g->cmdline[g->cmdline_size-1] = NULL;
972 fprintf (stderr, "%s", g->qemu);
973 for (i = 0; g->cmdline[i]; ++i)
974 fprintf (stderr, " %s", g->cmdline[i]);
975 fprintf (stderr, "\n");
978 /* Set up stdin, stdout. */
989 /* Set up a new process group, so we can signal this process
990 * and all subprocesses (eg. if qemu is really a shell script).
995 execv (g->qemu, g->cmdline); /* Run qemu. */
1000 /* Parent (library). */
1008 /* Fork the recovery process off which will kill qemu if the parent
1009 * process fails to do so (eg. if the parent segfaults).
1013 pid_t qemu_pid = g->pid;
1014 pid_t parent_pid = getppid ();
1016 /* Writing to argv is hideously complicated and error prone. See:
1017 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1020 /* Loop around waiting for one or both of the other processes to
1021 * disappear. It's fair to say this is very hairy. The PIDs that
1022 * we are looking at might be reused by another process. We are
1023 * effectively polling. Is the cure worse than the disease?
1026 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1028 if (kill (parent_pid, 0) == -1) {
1029 /* Parent's gone away, qemu still around, so kill qemu. */
1037 /* Don't worry, if the fork failed, this will be -1. The recovery
1038 * process isn't essential.
1042 /* Start the clock ... */
1045 /* Close the other ends of the pipe. */
1049 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1050 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1051 perrorf (g, "fcntl");
1055 g->fd[0] = wfd[1]; /* stdin of child */
1056 g->fd[1] = rfd[0]; /* stdout of child */
1058 /* Open the Unix socket. The vmchannel implementation that got
1059 * merged with qemu sucks in a number of ways. Both ends do
1060 * connect(2), which means that no one knows what, if anything, is
1061 * connected to the other end, or if it becomes disconnected. Even
1062 * worse, we have to wait some indeterminate time for qemu to create
1063 * the socket and connect to it (which happens very early in qemu's
1064 * start-up), so any code that uses vmchannel is inherently racy.
1065 * Hence this silly loop.
1067 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1068 if (g->sock == -1) {
1069 perrorf (g, "socket");
1073 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1074 perrorf (g, "fcntl");
1078 addr.sun_family = AF_UNIX;
1079 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1080 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1083 /* Always sleep at least once to give qemu a small chance to start up. */
1086 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1087 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1090 if (errno != ENOENT)
1091 perrorf (g, "connect");
1096 error (g, _("failed to connect to vmchannel socket"));
1100 /* Watch the file descriptors. */
1103 g->msg_in_size = g->msg_in_allocated = 0;
1107 g->msg_out_size = 0;
1111 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1112 GUESTFS_HANDLE_READABLE,
1113 stdout_event, NULL);
1114 if (g->stdout_watch == -1) {
1115 error (g, _("could not watch qemu stdout"));
1119 if (guestfs__switch_to_receiving (g) == -1)
1122 g->state = LAUNCHING;
1126 if (g->stdout_watch >= 0)
1127 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1128 if (g->sock_watch >= 0)
1129 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1138 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1139 waitpid (g->pid, NULL, 0);
1140 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1147 g->stdout_watch = -1;
1156 /* This function does the hard work of building the supermin appliance
1157 * on the fly. 'path' is the directory containing the control files.
1158 * 'kernel' and 'initrd' are where we will return the names of the
1159 * kernel and initrd (only initrd is built). The work is done by
1160 * an external script. We just tell it where to put the result.
1163 build_supermin_appliance (guestfs_h *g, const char *path,
1164 char **kernel, char **initrd)
1169 len = strlen (g->tmpdir);
1170 *kernel = safe_malloc (g, len + 8);
1171 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1172 *initrd = safe_malloc (g, len + 8);
1173 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1175 snprintf (cmd, sizeof cmd,
1177 "libguestfs-supermin-helper '%s' %s %s",
1179 path, *kernel, *initrd);
1182 if (r == -1 || WEXITSTATUS(r) != 0) {
1183 error (g, _("external command failed: %s"), cmd);
1186 *kernel = *initrd = NULL;
1193 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1195 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1196 * 'qemu -version' so we know what options this qemu supports and
1200 test_qemu (guestfs_h *g)
1205 free (g->qemu_help);
1206 free (g->qemu_version);
1207 g->qemu_help = NULL;
1208 g->qemu_version = NULL;
1210 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1212 fp = popen (cmd, "r");
1213 /* qemu -help should always work (qemu -version OTOH wasn't
1214 * supported by qemu 0.9). If this command doesn't work then it
1215 * probably indicates that the qemu binary is missing.
1218 /* XXX This error is never printed, even if the qemu binary
1219 * doesn't exist. Why?
1222 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1226 if (read_all (g, fp, &g->qemu_help) == -1)
1229 if (pclose (fp) == -1)
1232 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1234 fp = popen (cmd, "r");
1236 /* Intentionally ignore errors. */
1237 read_all (g, fp, &g->qemu_version);
1245 read_all (guestfs_h *g, FILE *fp, char **ret)
1252 *ret = safe_realloc (g, *ret, n + 1);
1257 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1259 r = fread (p, 1, BUFSIZ, fp);
1261 perrorf (g, "read");
1268 /* Test if option is supported by qemu command line (just by grepping
1272 qemu_supports (guestfs_h *g, const char *option)
1274 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1278 finish_wait_ready (guestfs_h *g, void *vp)
1281 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1284 g->main_loop->main_loop_quit (g->main_loop, g);
1288 guestfs_wait_ready (guestfs_h *g)
1290 int finished = 0, r;
1292 if (g->state == READY) return 0;
1294 if (g->state == BUSY) {
1295 error (g, _("qemu has finished launching already"));
1299 if (g->state != LAUNCHING) {
1300 error (g, _("qemu has not been launched yet"));
1304 g->launch_done_cb = finish_wait_ready;
1305 g->launch_done_cb_data = &finished;
1306 r = g->main_loop->main_loop_run (g->main_loop, g);
1307 g->launch_done_cb = NULL;
1308 g->launch_done_cb_data = NULL;
1310 if (r == -1) return -1;
1312 if (finished != 1) {
1313 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1317 /* This is possible in some really strange situations, such as
1318 * guestfsd starts up OK but then qemu immediately exits. Check for
1319 * it because the caller is probably expecting to be able to send
1320 * commands after this function returns.
1322 if (g->state != READY) {
1323 error (g, _("qemu launched and contacted daemon, but state != READY"));
1331 guestfs_kill_subprocess (guestfs_h *g)
1333 if (g->state == CONFIG) {
1334 error (g, _("no subprocess to kill"));
1339 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1341 kill (g->pid, SIGTERM);
1342 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1347 /* Access current state. */
1349 guestfs_is_config (guestfs_h *g)
1351 return g->state == CONFIG;
1355 guestfs_is_launching (guestfs_h *g)
1357 return g->state == LAUNCHING;
1361 guestfs_is_ready (guestfs_h *g)
1363 return g->state == READY;
1367 guestfs_is_busy (guestfs_h *g)
1369 return g->state == BUSY;
1373 guestfs_get_state (guestfs_h *g)
1379 guestfs_set_ready (guestfs_h *g)
1381 if (g->state != BUSY) {
1382 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1391 guestfs_set_busy (guestfs_h *g)
1393 if (g->state != READY) {
1394 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1403 guestfs_end_busy (guestfs_h *g)
1415 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1421 /* Structure-freeing functions. These rely on the fact that the
1422 * structure format is identical to the XDR format. See note in
1426 guestfs_free_int_bool (struct guestfs_int_bool *x)
1432 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1434 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1439 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1441 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1446 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1448 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1452 /* We don't know if stdout_event or sock_read_event will be the
1453 * first to receive EOF if the qemu process dies. This function
1454 * has the common cleanup code for both.
1457 child_cleanup (guestfs_h *g)
1460 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1461 /*kill (g->pid, SIGTERM);*/
1462 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1463 waitpid (g->pid, NULL, 0);
1464 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1465 if (g->stdout_watch >= 0)
1466 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1467 if (g->sock_watch >= 0)
1468 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1478 g->stdout_watch = -1;
1481 if (g->subprocess_quit_cb)
1482 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1485 /* This function is called whenever qemu prints something on stdout.
1486 * Qemu's stdout is also connected to the guest's serial console, so
1487 * we see kernel messages here too.
1490 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1491 int watch, int fd, int events)
1499 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1500 g, g->state, fd, events);
1503 if (g->fd[1] != fd) {
1504 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1508 n = read (fd, buf, sizeof buf);
1510 /* Hopefully this indicates the qemu child process has died. */
1516 if (errno != EINTR && errno != EAGAIN)
1517 perrorf (g, "read");
1521 /* In verbose mode, copy all log messages to stderr. */
1525 /* It's an actual log message, send it upwards if anyone is listening. */
1526 if (g->log_message_cb)
1527 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1530 /* The function is called whenever we can read something on the
1531 * guestfsd (daemon inside the guest) communication socket.
1534 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1535 int watch, int fd, int events)
1543 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1544 g, g->state, fd, events);
1546 if (g->sock != fd) {
1547 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1551 if (g->msg_in_size <= g->msg_in_allocated) {
1552 g->msg_in_allocated += 4096;
1553 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1555 n = read (g->sock, g->msg_in + g->msg_in_size,
1556 g->msg_in_allocated - g->msg_in_size);
1564 if (errno != EINTR && errno != EAGAIN)
1565 perrorf (g, "read");
1569 g->msg_in_size += n;
1571 /* Have we got enough of a message to be able to process it yet? */
1573 if (g->msg_in_size < 4) return;
1575 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1576 if (!xdr_uint32_t (&xdr, &len)) {
1577 error (g, _("can't decode length word"));
1581 /* Length is normally the length of the message, but when guestfsd
1582 * starts up it sends a "magic" value (longer than any possible
1583 * message). Check for this.
1585 if (len == GUESTFS_LAUNCH_FLAG) {
1586 if (g->state != LAUNCHING)
1587 error (g, _("received magic signature from guestfsd, but in state %d"),
1589 else if (g->msg_in_size != 4)
1590 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1594 if (g->launch_done_cb)
1595 g->launch_done_cb (g, g->launch_done_cb_data);
1601 /* This can happen if a cancellation happens right at the end
1602 * of us sending a FileIn parameter to the daemon. Discard. The
1603 * daemon should send us an error message next.
1605 if (len == GUESTFS_CANCEL_FLAG) {
1606 g->msg_in_size -= 4;
1607 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1611 /* If this happens, it's pretty bad and we've probably lost
1614 if (len > GUESTFS_MESSAGE_MAX) {
1615 error (g, _("message length (%u) > maximum possible size (%d)"),
1616 len, GUESTFS_MESSAGE_MAX);
1620 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1622 /* Got the full message, begin processing it. */
1627 for (i = 0; i < g->msg_in_size; i += 16) {
1628 printf ("%04x: ", i);
1629 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1630 printf ("%02x ", (unsigned char) g->msg_in[j]);
1631 for (; j < i+16; ++j)
1634 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1635 if (isprint (g->msg_in[j]))
1636 printf ("%c", g->msg_in[j]);
1639 for (; j < i+16; ++j)
1646 /* Not in the expected state. */
1647 if (g->state != BUSY)
1648 error (g, _("state %d != BUSY"), g->state);
1650 /* Push the message up to the higher layer. */
1652 g->reply_cb (g, g->reply_cb_data, &xdr);
1654 /* This message (probably) should never be printed. */
1655 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1657 g->msg_in_size -= len + 4;
1658 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1659 if (g->msg_in_size > 0) goto again;
1662 /* Free the message buffer if it's grown excessively large. */
1663 if (g->msg_in_allocated > 65536) {
1666 g->msg_in_size = g->msg_in_allocated = 0;
1673 /* The function is called whenever we can write something on the
1674 * guestfsd (daemon inside the guest) communication socket.
1677 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1678 int watch, int fd, int events)
1684 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1685 g, g->state, fd, events);
1687 if (g->sock != fd) {
1688 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1692 if (g->state != BUSY) {
1693 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1698 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1699 g->msg_out_size - g->msg_out_pos);
1701 n = write (g->sock, g->msg_out + g->msg_out_pos,
1702 g->msg_out_size - g->msg_out_pos);
1704 if (errno != EAGAIN)
1705 perrorf (g, "write");
1710 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1712 g->msg_out_pos += n;
1714 /* More to write? */
1715 if (g->msg_out_pos < g->msg_out_size)
1719 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1723 g->msg_out_pos = g->msg_out_size = 0;
1725 /* Done writing, call the higher layer. */
1727 g->send_cb (g, g->send_cb_data);
1731 guestfs_set_send_callback (guestfs_h *g,
1732 guestfs_send_cb cb, void *opaque)
1735 g->send_cb_data = opaque;
1739 guestfs_set_reply_callback (guestfs_h *g,
1740 guestfs_reply_cb cb, void *opaque)
1743 g->reply_cb_data = opaque;
1747 guestfs_set_log_message_callback (guestfs_h *g,
1748 guestfs_log_message_cb cb, void *opaque)
1750 g->log_message_cb = cb;
1751 g->log_message_cb_data = opaque;
1755 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1756 guestfs_subprocess_quit_cb cb, void *opaque)
1758 g->subprocess_quit_cb = cb;
1759 g->subprocess_quit_cb_data = opaque;
1763 guestfs_set_launch_done_callback (guestfs_h *g,
1764 guestfs_launch_done_cb cb, void *opaque)
1766 g->launch_done_cb = cb;
1767 g->launch_done_cb_data = opaque;
1770 /* Access to the handle's main loop and the default main loop. */
1772 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1774 g->main_loop = main_loop;
1778 guestfs_get_main_loop (guestfs_h *g)
1780 return g->main_loop;
1784 guestfs_get_default_main_loop (void)
1786 return (guestfs_main_loop *) &default_main_loop;
1789 /* Change the daemon socket handler so that we are now writing.
1790 * This sets the handle to sock_write_event.
1793 guestfs__switch_to_sending (guestfs_h *g)
1795 if (g->sock_watch >= 0) {
1796 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1797 error (g, _("remove_handle failed"));
1804 g->main_loop->add_handle (g->main_loop, g, g->sock,
1805 GUESTFS_HANDLE_WRITABLE,
1806 sock_write_event, NULL);
1807 if (g->sock_watch == -1) {
1808 error (g, _("add_handle failed"));
1816 guestfs__switch_to_receiving (guestfs_h *g)
1818 if (g->sock_watch >= 0) {
1819 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1820 error (g, _("remove_handle failed"));
1827 g->main_loop->add_handle (g->main_loop, g, g->sock,
1828 GUESTFS_HANDLE_READABLE,
1829 sock_read_event, NULL);
1830 if (g->sock_watch == -1) {
1831 error (g, _("add_handle failed"));
1838 /* Dispatch a call (len + header + args) to the remote daemon,
1839 * synchronously (ie. using the guest's main loop to wait until
1840 * it has been sent). Returns -1 for error, or the serial
1841 * number of the message.
1844 send_cb (guestfs_h *g, void *data)
1846 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1849 ml->main_loop_quit (ml, g);
1853 guestfs__send_sync (guestfs_h *g, int proc_nr,
1854 xdrproc_t xdrp, char *args)
1856 struct guestfs_message_header hdr;
1859 int serial = g->msg_next_serial++;
1861 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1863 if (g->state != BUSY) {
1864 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1868 /* This is probably an internal error. Or perhaps we should just
1869 * free the buffer anyway?
1871 if (g->msg_out != NULL) {
1872 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1876 /* We have to allocate this message buffer on the heap because
1877 * it is quite large (although will be mostly unused). We
1878 * can't allocate it on the stack because in some environments
1879 * we have quite limited stack space available, notably when
1880 * running in the JVM.
1882 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1883 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1885 /* Serialize the header. */
1886 hdr.prog = GUESTFS_PROGRAM;
1887 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1889 hdr.direction = GUESTFS_DIRECTION_CALL;
1890 hdr.serial = serial;
1891 hdr.status = GUESTFS_STATUS_OK;
1893 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1894 error (g, _("xdr_guestfs_message_header failed"));
1898 /* Serialize the args. If any, because some message types
1899 * have no parameters.
1902 if (!(*xdrp) (&xdr, args)) {
1903 error (g, _("dispatch failed to marshal args"));
1908 /* Get the actual length of the message, resize the buffer to match
1909 * the actual length, and write the length word at the beginning.
1911 len = xdr_getpos (&xdr);
1914 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1915 g->msg_out_size = len + 4;
1918 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1919 xdr_uint32_t (&xdr, &len);
1921 if (guestfs__switch_to_sending (g) == -1)
1925 guestfs_set_send_callback (g, send_cb, &sent);
1926 if (ml->main_loop_run (ml, g) == -1)
1929 error (g, _("send failed, see earlier error messages"));
1938 g->msg_out_size = 0;
1942 static int cancel = 0; /* XXX Implement file cancellation. */
1943 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1944 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1945 static int send_file_cancellation_sync (guestfs_h *g);
1946 static int send_file_complete_sync (guestfs_h *g);
1948 /* Synchronously send a file.
1952 * -2 daemon cancelled (we must read the error message)
1955 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1957 char buf[GUESTFS_MAX_CHUNK_SIZE];
1960 fd = open (filename, O_RDONLY);
1962 perrorf (g, "open: %s", filename);
1963 send_file_cancellation_sync (g);
1964 /* Daemon sees cancellation and won't reply, so caller can
1970 /* Send file in chunked encoding. */
1972 r = read (fd, buf, sizeof buf);
1973 if (r == -1 && (errno == EINTR || errno == EAGAIN))
1976 err = send_file_data_sync (g, buf, r);
1978 if (err == -2) /* daemon sent cancellation */
1979 send_file_cancellation_sync (g);
1984 if (cancel) { /* cancel from either end */
1985 send_file_cancellation_sync (g);
1990 perrorf (g, "read: %s", filename);
1991 send_file_cancellation_sync (g);
1995 /* End of file, but before we send that, we need to close
1996 * the file and check for errors.
1998 if (close (fd) == -1) {
1999 perrorf (g, "close: %s", filename);
2000 send_file_cancellation_sync (g);
2004 return send_file_complete_sync (g);
2007 /* Send a chunk of file data. */
2009 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2011 return send_file_chunk_sync (g, 0, buf, len);
2014 /* Send a cancellation message. */
2016 send_file_cancellation_sync (guestfs_h *g)
2018 return send_file_chunk_sync (g, 1, NULL, 0);
2021 /* Send a file complete chunk. */
2023 send_file_complete_sync (guestfs_h *g)
2026 return send_file_chunk_sync (g, 0, buf, 0);
2029 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2032 static int check_for_daemon_cancellation (guestfs_h *g);
2035 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2039 guestfs_chunk chunk;
2041 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2043 if (g->state != BUSY) {
2044 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2048 /* This is probably an internal error. Or perhaps we should just
2049 * free the buffer anyway?
2051 if (g->msg_out != NULL) {
2052 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2056 /* Did the daemon send a cancellation message? */
2057 if (check_for_daemon_cancellation (g)) {
2059 fprintf (stderr, "got daemon cancellation\n");
2063 /* Allocate the chunk buffer. Don't use the stack to avoid
2064 * excessive stack usage and unnecessary copies.
2066 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2067 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2069 /* Serialize the chunk. */
2070 chunk.cancel = cancel;
2071 chunk.data.data_len = buflen;
2072 chunk.data.data_val = (char *) buf;
2074 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2075 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2081 len = xdr_getpos (&xdr);
2084 /* Reduce the size of the outgoing message buffer to the real length. */
2085 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2086 g->msg_out_size = len + 4;
2089 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2090 xdr_uint32_t (&xdr, &len);
2092 if (guestfs__switch_to_sending (g) == -1)
2096 guestfs_set_send_callback (g, send_cb, &sent);
2097 if (ml->main_loop_run (ml, g) == -1)
2100 error (g, _("send file chunk failed, see earlier error messages"));
2109 g->msg_out_size = 0;
2113 /* At this point we are sending FileIn file(s) to the guest, and not
2114 * expecting to read anything, so if we do read anything, it must be
2115 * a cancellation message. This checks for this case without blocking.
2118 check_for_daemon_cancellation (guestfs_h *g)
2128 FD_SET (g->sock, &rset);
2131 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2133 perrorf (g, "select");
2139 /* Read the message from the daemon. */
2140 r = xread (g->sock, buf, sizeof buf);
2142 perrorf (g, "read");
2146 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2147 xdr_uint32_t (&xdr, &flag);
2150 if (flag != GUESTFS_CANCEL_FLAG) {
2151 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2152 flag, GUESTFS_CANCEL_FLAG);
2159 /* Synchronously receive a file. */
2161 /* Returns -1 = error, 0 = EOF, 1 = more data */
2162 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2165 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2171 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2173 perrorf (g, "open: %s", filename);
2177 /* Receive the file in chunked encoding. */
2178 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2179 if (xwrite (fd, buf, len) == -1) {
2180 perrorf (g, "%s: write", filename);
2185 if (r == 0) break; /* End of file. */
2189 error (g, _("%s: error in chunked encoding"), filename);
2193 if (close (fd) == -1) {
2194 perrorf (g, "close: %s", filename);
2201 /* Send cancellation message to daemon, then wait until it
2202 * cancels (just throwing away data).
2206 uint32_t flag = GUESTFS_CANCEL_FLAG;
2208 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2209 xdr_uint32_t (&xdr, &flag);
2212 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2213 perrorf (g, _("write to daemon socket"));
2217 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2218 ; /* just discard it */
2223 /* Note that the reply callback can be called multiple times before
2224 * the main loop quits and we get back to the synchronous code. So
2225 * we have to be prepared to save multiple chunks on a list here.
2227 struct receive_file_ctx {
2228 int count; /* 0 if receive_file_cb not called, or
2229 * else count number of chunks.
2231 guestfs_chunk *chunks; /* Array of chunks. */
2235 free_chunks (struct receive_file_ctx *ctx)
2239 for (i = 0; i < ctx->count; ++i)
2240 free (ctx->chunks[i].data.data_val);
2246 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2248 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2249 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2250 guestfs_chunk chunk;
2252 if (ctx->count == -1) /* Parse error occurred previously. */
2255 ml->main_loop_quit (ml, g);
2257 memset (&chunk, 0, sizeof chunk);
2259 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2260 error (g, _("failed to parse file chunk"));
2267 /* Copy the chunk to the list. */
2268 ctx->chunks = safe_realloc (g, ctx->chunks,
2269 sizeof (guestfs_chunk) * (ctx->count+1));
2270 ctx->chunks[ctx->count] = chunk;
2274 /* Receive a chunk of file data. */
2275 /* Returns -1 = error, 0 = EOF, 1 = more data */
2277 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2279 struct receive_file_ctx ctx;
2280 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2287 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2288 (void) ml->main_loop_run (ml, g);
2289 guestfs_set_reply_callback (g, NULL, NULL);
2291 if (ctx.count == 0) {
2292 error (g, _("receive_file_data_sync: reply callback not called\n"));
2296 if (ctx.count == -1) {
2297 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2298 /* callback already freed the chunks */
2303 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2305 /* Process each chunk in the list. */
2306 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2309 for (i = 0; i < ctx.count; ++i) {
2310 if (ctx.chunks[i].cancel) {
2311 error (g, _("file receive cancelled by daemon"));
2313 if (buf) free (*buf);
2314 if (len_r) *len_r = 0;
2318 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2320 if (len_r) *len_r = len;
2325 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2326 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2327 ctx.chunks[i].data.data_len);
2329 len += ctx.chunks[i].data.data_len;
2332 if (len_r) *len_r = len;
2337 /* This is the default main loop implementation, using select(2). */
2340 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2341 guestfs_handle_event_cb cb, void *data)
2343 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2345 if (fd < 0 || fd >= FD_SETSIZE) {
2346 error (g, _("fd %d is out of range"), fd);
2350 if ((events & ~(GUESTFS_HANDLE_READABLE |
2351 GUESTFS_HANDLE_WRITABLE |
2352 GUESTFS_HANDLE_HANGUP |
2353 GUESTFS_HANDLE_ERROR)) != 0) {
2354 error (g, _("set of events (0x%x) contains unknown events"), events);
2359 error (g, _("set of events is empty"));
2363 if (FD_ISSET (fd, &ml->rset) ||
2364 FD_ISSET (fd, &ml->wset) ||
2365 FD_ISSET (fd, &ml->xset)) {
2366 error (g, _("fd %d is already registered"), fd);
2371 error (g, _("callback is NULL"));
2375 if ((events & GUESTFS_HANDLE_READABLE))
2376 FD_SET (fd, &ml->rset);
2377 if ((events & GUESTFS_HANDLE_WRITABLE))
2378 FD_SET (fd, &ml->wset);
2379 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2380 FD_SET (fd, &ml->xset);
2382 if (fd > ml->max_fd) {
2384 ml->handle_cb_data =
2385 safe_realloc (g, ml->handle_cb_data,
2386 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2388 ml->handle_cb_data[fd].cb = cb;
2389 ml->handle_cb_data[fd].g = g;
2390 ml->handle_cb_data[fd].data = data;
2394 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2399 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2401 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2403 if (fd < 0 || fd >= FD_SETSIZE) {
2404 error (g, _("fd %d is out of range"), fd);
2408 if (!FD_ISSET (fd, &ml->rset) &&
2409 !FD_ISSET (fd, &ml->wset) &&
2410 !FD_ISSET (fd, &ml->xset)) {
2411 error (g, _("fd %d was not registered"), fd);
2415 FD_CLR (fd, &ml->rset);
2416 FD_CLR (fd, &ml->wset);
2417 FD_CLR (fd, &ml->xset);
2419 if (fd == ml->max_fd) {
2421 ml->handle_cb_data =
2422 safe_realloc (g, ml->handle_cb_data,
2423 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2432 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2433 guestfs_handle_timeout_cb cb, void *data)
2435 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2437 abort (); /* XXX not implemented yet */
2441 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2443 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2445 abort (); /* XXX not implemented yet */
2448 /* The 'g' parameter is just used for error reporting. Events
2449 * for multiple handles can be dispatched by running the main
2453 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2455 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2457 fd_set rset2, wset2, xset2;
2459 if (ml->is_running) {
2460 error (g, _("select_main_loop_run: this cannot be called recursively"));
2466 while (ml->is_running) {
2467 if (ml->nr_fds == 0)
2473 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2475 if (errno == EINTR || errno == EAGAIN)
2477 perrorf (g, "select");
2482 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2484 if (FD_ISSET (fd, &rset2))
2485 events |= GUESTFS_HANDLE_READABLE;
2486 if (FD_ISSET (fd, &wset2))
2487 events |= GUESTFS_HANDLE_WRITABLE;
2488 if (FD_ISSET (fd, &xset2))
2489 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2492 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2493 ml->handle_cb_data[fd].g,
2494 ml->handle_cb_data[fd].data,
2505 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2507 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2509 /* Note that legitimately ml->is_running can be zero when
2510 * this function is called.