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>
35 #include <rpc/types.h>
42 #ifdef HAVE_SYS_TYPES_H
43 #include <sys/types.h>
46 #ifdef HAVE_SYS_WAIT_H
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
59 #include "guestfs_protocol.h"
61 #define error guestfs_error
62 #define perrorf guestfs_perrorf
63 #define safe_malloc guestfs_safe_malloc
64 #define safe_realloc guestfs_safe_realloc
65 #define safe_strdup guestfs_safe_strdup
66 #define safe_memdup guestfs_safe_memdup
68 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
69 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
70 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
71 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
73 static void close_handles (void);
75 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
76 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
77 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
78 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
79 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
80 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
82 /* Default select-based main loop. */
83 struct select_handle_cb_data {
84 guestfs_handle_event_cb cb;
89 struct select_main_loop {
90 /* NB. These fields must be the same as in struct guestfs_main_loop: */
91 guestfs_add_handle_cb add_handle;
92 guestfs_remove_handle_cb remove_handle;
93 guestfs_add_timeout_cb add_timeout;
94 guestfs_remove_timeout_cb remove_timeout;
95 guestfs_main_loop_run_cb main_loop_run;
96 guestfs_main_loop_quit_cb main_loop_quit;
98 /* Additional private data: */
107 struct select_handle_cb_data *handle_cb_data;
110 /* Default main loop. */
111 static struct select_main_loop default_main_loop = {
112 .add_handle = select_add_handle,
113 .remove_handle = select_remove_handle,
114 .add_timeout = select_add_timeout,
115 .remove_timeout = select_remove_timeout,
116 .main_loop_run = select_main_loop_run,
117 .main_loop_quit = select_main_loop_quit,
119 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
120 * set by the normal action of everything being initialized to zero.
125 .handle_cb_data = NULL,
128 #define UNIX_PATH_MAX 108
130 /* Also in guestfsd.c */
131 #define VMCHANNEL_PORT 6666
132 #define VMCHANNEL_ADDR "10.0.2.4"
134 /* GuestFS handle and connection. */
135 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
139 struct guestfs_h *next; /* Linked list of open handles. */
141 /* State: see the state machine diagram in the man page guestfs(3). */
144 int fd[2]; /* Stdin/stdout of qemu. */
145 int sock; /* Daemon communications socket. */
146 int pid; /* Qemu PID. */
147 time_t start_t; /* The time when we started qemu. */
149 int stdout_watch; /* Watches qemu stdout for log messages. */
150 int sock_watch; /* Watches daemon comm socket. */
152 char *tmpdir; /* Temporary directory containing socket. */
154 char **cmdline; /* Qemu command line. */
166 guestfs_abort_cb abort_cb;
167 guestfs_error_handler_cb error_cb;
168 void * error_cb_data;
169 guestfs_send_cb send_cb;
171 guestfs_reply_cb reply_cb;
172 void * reply_cb_data;
173 guestfs_log_message_cb log_message_cb;
174 void * log_message_cb_data;
175 guestfs_subprocess_quit_cb subprocess_quit_cb;
176 void * subprocess_quit_cb_data;
177 guestfs_launch_done_cb launch_done_cb;
178 void * launch_done_cb_data;
180 /* Main loop used by this handle. */
181 guestfs_main_loop *main_loop;
183 /* Messages sent and received from the daemon. */
185 int msg_in_size, msg_in_allocated;
187 int msg_out_size, msg_out_pos;
192 static guestfs_h *handles = NULL;
193 static int atexit_handler_set = 0;
196 guestfs_create (void)
201 g = malloc (sizeof (*g));
204 memset (g, 0, sizeof (*g));
211 g->stdout_watch = -1;
215 g->error_cb = default_error_cb;
216 g->error_cb_data = NULL;
218 str = getenv ("LIBGUESTFS_DEBUG");
219 g->verbose = str != NULL && strcmp (str, "1") == 0;
221 str = getenv ("LIBGUESTFS_PATH");
222 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
224 str = getenv ("LIBGUESTFS_QEMU");
225 g->qemu = str != NULL ? str : QEMU;
227 g->main_loop = guestfs_get_default_main_loop ();
229 /* Start with large serial numbers so they are easy to spot
230 * inside the protocol.
232 g->msg_next_serial = 0x00123400;
234 /* Link the handles onto a global list. This is the one area
235 * where the library needs to be made thread-safe. (XXX)
237 /* acquire mutex (XXX) */
240 if (!atexit_handler_set) {
241 atexit (close_handles);
242 atexit_handler_set = 1;
244 /* release mutex (XXX) */
247 fprintf (stderr, "new guestfs handle %p\n", g);
253 guestfs_close (guestfs_h *g)
259 if (g->state == NO_HANDLE) {
260 /* Not safe to call 'error' here, so ... */
261 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
266 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
268 /* Try to sync if autosync flag is set. */
269 if (g->autosync && g->state == READY)
272 /* Remove any handlers that might be called back before we kill the
275 g->log_message_cb = NULL;
277 if (g->state != CONFIG)
278 guestfs_kill_subprocess (g);
281 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
290 for (i = 0; i < g->cmdline_size; ++i)
291 free (g->cmdline[i]);
295 /* Mark the handle as dead before freeing it. */
296 g->state = NO_HANDLE;
298 /* acquire mutex (XXX) */
302 for (gg = handles; gg->next != g; gg = gg->next)
306 /* release mutex (XXX) */
308 free (g->last_error);
312 /* Close all open handles (called from atexit(3)). */
316 while (handles) guestfs_close (handles);
320 guestfs_last_error (guestfs_h *g)
322 return g->last_error;
326 set_last_error (guestfs_h *g, const char *msg)
328 free (g->last_error);
329 g->last_error = strdup (msg);
333 default_error_cb (guestfs_h *g, void *data, const char *msg)
335 fprintf (stderr, "libguestfs: error: %s\n", msg);
339 guestfs_error (guestfs_h *g, const char *fs, ...)
345 vasprintf (&msg, fs, args);
348 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
349 set_last_error (g, msg);
355 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
362 vasprintf (&msg, fs, args);
367 strerror_r (err, buf, sizeof buf);
371 buf = strerror_r (err, _buf, sizeof _buf);
374 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
378 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
379 set_last_error (g, msg);
385 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
387 void *ptr = malloc (nbytes);
388 if (!ptr) g->abort_cb ();
393 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
395 void *p = realloc (ptr, nbytes);
396 if (!p) g->abort_cb ();
401 guestfs_safe_strdup (guestfs_h *g, const char *str)
403 char *s = strdup (str);
404 if (!s) g->abort_cb ();
409 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
411 void *p = malloc (size);
412 if (!p) g->abort_cb ();
413 memcpy (p, ptr, size);
418 xwrite (int fd, const void *buf, size_t len)
423 r = write (fd, buf, len);
435 xread (int fd, void *buf, size_t len)
440 r = read (fd, buf, len);
452 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
458 guestfs_get_out_of_memory_handler (guestfs_h *g)
464 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
467 g->error_cb_data = data;
470 guestfs_error_handler_cb
471 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
473 if (data_rtn) *data_rtn = g->error_cb_data;
478 guestfs_set_verbose (guestfs_h *g, int v)
485 guestfs_get_verbose (guestfs_h *g)
491 guestfs_set_autosync (guestfs_h *g, int a)
498 guestfs_get_autosync (guestfs_h *g)
504 guestfs_set_path (guestfs_h *g, const char *path)
507 g->path = GUESTFS_DEFAULT_PATH;
514 guestfs_get_path (guestfs_h *g)
520 guestfs_set_qemu (guestfs_h *g, const char *qemu)
530 guestfs_get_qemu (guestfs_h *g)
535 /* Add a string to the current command line. */
537 incr_cmdline_size (guestfs_h *g)
539 if (g->cmdline == NULL) {
540 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
542 g->cmdline = safe_malloc (g, sizeof (char *));
543 g->cmdline[0] = NULL;
547 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
551 add_cmdline (guestfs_h *g, const char *str)
553 if (g->state != CONFIG) {
554 error (g, "command line cannot be altered after qemu subprocess launched");
558 incr_cmdline_size (g);
559 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
564 guestfs_config (guestfs_h *g,
565 const char *qemu_param, const char *qemu_value)
567 if (qemu_param[0] != '-') {
568 error (g, "guestfs_config: parameter must begin with '-' character");
572 /* A bit fascist, but the user will probably break the extra
573 * parameters that we add if they try to set any of these.
575 if (strcmp (qemu_param, "-kernel") == 0 ||
576 strcmp (qemu_param, "-initrd") == 0 ||
577 strcmp (qemu_param, "-nographic") == 0 ||
578 strcmp (qemu_param, "-serial") == 0 ||
579 strcmp (qemu_param, "-vnc") == 0 ||
580 strcmp (qemu_param, "-full-screen") == 0 ||
581 strcmp (qemu_param, "-std-vga") == 0 ||
582 strcmp (qemu_param, "-vnc") == 0) {
583 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
587 if (add_cmdline (g, qemu_param) != 0) return -1;
589 if (qemu_value != NULL) {
590 if (add_cmdline (g, qemu_value) != 0) return -1;
597 guestfs_add_drive (guestfs_h *g, const char *filename)
599 int len = strlen (filename) + 64;
602 if (strchr (filename, ',') != NULL) {
603 error (g, "filename cannot contain ',' (comma) character");
607 if (access (filename, F_OK) == -1) {
608 perrorf (g, "%s", filename);
612 snprintf (buf, len, "file=%s", filename);
614 return guestfs_config (g, "-drive", buf);
618 guestfs_add_cdrom (guestfs_h *g, const char *filename)
620 if (strchr (filename, ',') != NULL) {
621 error (g, "filename cannot contain ',' (comma) character");
625 if (access (filename, F_OK) == -1) {
626 perrorf (g, "%s", filename);
630 return guestfs_config (g, "-cdrom", filename);
634 guestfs_launch (guestfs_h *g)
636 static const char *dir_template = "/tmp/libguestfsXXXXXX";
637 int r, i, len, pmore, memsize;
640 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
641 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
642 char *path, *pelem, *pend;
643 char *kernel = NULL, *initrd = NULL;
645 struct sockaddr_un addr;
650 error (g, "you must call guestfs_add_drive before guestfs_launch");
654 if (g->state != CONFIG) {
655 error (g, "qemu has already been launched");
659 /* Search g->path for the kernel and initrd. */
660 pelem = path = safe_strdup (g, g->path);
662 pend = strchrnul (pelem, ':');
663 pmore = *pend == ':';
667 /* Empty element or "." means cwd. */
668 if (len == 0 || (len == 1 && *pelem == '.')) {
671 "looking for kernel and initrd in current directory\n");
672 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
673 kernel = safe_strdup (g, kernel_name);
674 initrd = safe_strdup (g, initrd_name);
678 /* Look at <path>/kernel etc. */
680 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
681 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
682 sprintf (kernel, "%s/%s", pelem, kernel_name);
683 sprintf (initrd, "%s/%s", pelem, initrd_name);
686 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
688 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
692 kernel = initrd = NULL;
700 if (kernel == NULL || initrd == NULL) {
701 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
702 kernel_name, initrd_name, g->path);
706 /* Choose a suitable memory size (in MB). This is more art
707 * than science, but you can help by doing
708 * ./configure --enable-debug-command
712 * and seeing how much free memory is left for particular
715 * It's also helpful to report both the compressed and uncompressed
716 * size of the initramfs (ls -lh initramfs*.img; du -sh initramfs).
718 * XXX KVM virtio balloon driver?
720 if (stat (initrd, &statbuf) != -1) {
721 /* Approximate size of the initramfs after it is decompressed
722 * in kernel memory. The compression factor is ~2.5-3.
724 memsize = 3 * statbuf.st_size / 1024 / 1024;
726 /* Approximate size used by the kernel. */
729 /* Want to give userspace some room, so: */
733 /* On 64 bit, assume some overhead. */
740 /* Make the temporary directory containing the socket. */
742 g->tmpdir = safe_strdup (g, dir_template);
743 if (mkdtemp (g->tmpdir) == NULL) {
744 perrorf (g, "%s: cannot create temporary directory", dir_template);
749 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
752 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
767 if (r == 0) { /* Child (qemu). */
770 char memsize_str[256];
772 /* Set up the full command line. Do this in the subprocess so we
773 * don't need to worry about cleaning up.
775 g->cmdline[0] = (char *) g->qemu;
777 /* Construct the -net channel parameter for qemu. */
778 snprintf (vmchannel, sizeof vmchannel,
779 "channel,%d:unix:%s,server,nowait",
780 VMCHANNEL_PORT, unixsock);
782 /* Linux kernel command line. */
783 snprintf (append, sizeof append,
784 "console=ttyS0 guestfs=%s:%d%s",
785 VMCHANNEL_ADDR, VMCHANNEL_PORT,
786 g->verbose ? " guestfs_verbose=1" : "");
788 snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
790 add_cmdline (g, "-m");
791 add_cmdline (g, memsize_str);
793 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
795 add_cmdline (g, "-kernel");
796 add_cmdline (g, (char *) kernel);
797 add_cmdline (g, "-initrd");
798 add_cmdline (g, (char *) initrd);
799 add_cmdline (g, "-append");
800 add_cmdline (g, append);
801 add_cmdline (g, "-nographic");
802 add_cmdline (g, "-serial");
803 add_cmdline (g, "stdio");
804 add_cmdline (g, "-net");
805 add_cmdline (g, vmchannel);
806 add_cmdline (g, "-net");
807 add_cmdline (g, "user,vlan=0");
808 add_cmdline (g, "-net");
809 add_cmdline (g, "nic,model=rtl8139,vlan=0");
810 incr_cmdline_size (g);
811 g->cmdline[g->cmdline_size-1] = NULL;
814 fprintf (stderr, "%s", g->qemu);
815 for (i = 0; g->cmdline[i]; ++i)
816 fprintf (stderr, " %s", g->cmdline[i]);
817 fprintf (stderr, "\n");
820 /* Set up stdin, stdout. */
831 /* Set up a new process group, so we can signal this process
832 * and all subprocesses (eg. if qemu is really a shell script).
837 execv (g->qemu, g->cmdline); /* Run qemu. */
842 /* Parent (library). */
845 /* Start the clock ... */
848 /* Close the other ends of the pipe. */
852 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
853 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
854 perrorf (g, "fcntl");
858 g->fd[0] = wfd[1]; /* stdin of child */
859 g->fd[1] = rfd[0]; /* stdout of child */
861 /* Open the Unix socket. The vmchannel implementation that got
862 * merged with qemu sucks in a number of ways. Both ends do
863 * connect(2), which means that no one knows what, if anything, is
864 * connected to the other end, or if it becomes disconnected. Even
865 * worse, we have to wait some indeterminate time for qemu to create
866 * the socket and connect to it (which happens very early in qemu's
867 * start-up), so any code that uses vmchannel is inherently racy.
868 * Hence this silly loop.
870 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
872 perrorf (g, "socket");
876 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
877 perrorf (g, "fcntl");
881 addr.sun_family = AF_UNIX;
882 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
883 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
887 /* Always sleep at least once to give qemu a small chance to start up. */
890 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
891 if ((r == -1 && errno == EINPROGRESS) || r == 0)
895 perrorf (g, "connect");
899 error (g, "failed to connect to vmchannel socket");
903 /* Watch the file descriptors. */
906 g->msg_in_size = g->msg_in_allocated = 0;
914 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
915 GUESTFS_HANDLE_READABLE,
917 if (g->stdout_watch == -1) {
918 error (g, "could not watch qemu stdout");
922 if (guestfs__switch_to_receiving (g) == -1)
925 g->state = LAUNCHING;
929 if (g->stdout_watch >= 0)
930 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
931 if (g->sock_watch >= 0)
932 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
941 waitpid (g->pid, NULL, 0);
947 g->stdout_watch = -1;
957 finish_wait_ready (guestfs_h *g, void *vp)
960 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
963 g->main_loop->main_loop_quit (g->main_loop, g);
967 guestfs_wait_ready (guestfs_h *g)
971 if (g->state == READY) return 0;
973 if (g->state == BUSY) {
974 error (g, "qemu has finished launching already");
978 if (g->state != LAUNCHING) {
979 error (g, "qemu has not been launched yet");
983 g->launch_done_cb = finish_wait_ready;
984 g->launch_done_cb_data = &finished;
985 r = g->main_loop->main_loop_run (g->main_loop, g);
986 g->launch_done_cb = NULL;
987 g->launch_done_cb_data = NULL;
989 if (r == -1) return -1;
992 error (g, "guestfs_wait_ready failed, see earlier error messages");
996 /* This is possible in some really strange situations, such as
997 * guestfsd starts up OK but then qemu immediately exits. Check for
998 * it because the caller is probably expecting to be able to send
999 * commands after this function returns.
1001 if (g->state != READY) {
1002 error (g, "qemu launched and contacted daemon, but state != READY");
1010 guestfs_kill_subprocess (guestfs_h *g)
1012 if (g->state == CONFIG) {
1013 error (g, "no subprocess to kill");
1018 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1020 kill (g->pid, SIGTERM);
1025 /* Access current state. */
1027 guestfs_is_config (guestfs_h *g)
1029 return g->state == CONFIG;
1033 guestfs_is_launching (guestfs_h *g)
1035 return g->state == LAUNCHING;
1039 guestfs_is_ready (guestfs_h *g)
1041 return g->state == READY;
1045 guestfs_is_busy (guestfs_h *g)
1047 return g->state == BUSY;
1051 guestfs_get_state (guestfs_h *g)
1057 guestfs_set_ready (guestfs_h *g)
1059 if (g->state != BUSY) {
1060 error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1068 guestfs_set_busy (guestfs_h *g)
1070 if (g->state != READY) {
1071 error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1078 /* Structure-freeing functions. These rely on the fact that the
1079 * structure format is identical to the XDR format. See note in
1083 guestfs_free_int_bool (struct guestfs_int_bool *x)
1089 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1091 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1096 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1098 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1103 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1105 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1109 /* This function is called whenever qemu prints something on stdout.
1110 * Qemu's stdout is also connected to the guest's serial console, so
1111 * we see kernel messages here too.
1114 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1115 int watch, int fd, int events)
1123 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1124 g, g->state, fd, events);
1127 if (g->fd[1] != fd) {
1128 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1132 n = read (fd, buf, sizeof buf);
1134 /* Hopefully this indicates the qemu child process has died. */
1136 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1137 /*kill (g->pid, SIGTERM);*/
1138 waitpid (g->pid, NULL, 0);
1139 if (g->stdout_watch >= 0)
1140 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1141 if (g->sock_watch >= 0)
1142 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1151 g->stdout_watch = -1;
1154 if (g->subprocess_quit_cb)
1155 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1160 if (errno != EAGAIN)
1161 perrorf (g, "read");
1165 /* In verbose mode, copy all log messages to stderr. */
1169 /* It's an actual log message, send it upwards if anyone is listening. */
1170 if (g->log_message_cb)
1171 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1174 /* The function is called whenever we can read something on the
1175 * guestfsd (daemon inside the guest) communication socket.
1178 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1179 int watch, int fd, int events)
1187 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1188 g, g->state, fd, events);
1190 if (g->sock != fd) {
1191 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1195 if (g->msg_in_size <= g->msg_in_allocated) {
1196 g->msg_in_allocated += 4096;
1197 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1199 n = read (g->sock, g->msg_in + g->msg_in_size,
1200 g->msg_in_allocated - g->msg_in_size);
1202 /* Disconnected? Ignore it because stdout_watch will get called
1203 * and will do the cleanup.
1208 if (errno != EAGAIN)
1209 perrorf (g, "read");
1213 g->msg_in_size += n;
1215 /* Have we got enough of a message to be able to process it yet? */
1217 if (g->msg_in_size < 4) return;
1219 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1220 if (!xdr_uint32_t (&xdr, &len)) {
1221 error (g, "can't decode length word");
1225 /* Length is normally the length of the message, but when guestfsd
1226 * starts up it sends a "magic" value (longer than any possible
1227 * message). Check for this.
1229 if (len == GUESTFS_LAUNCH_FLAG) {
1230 if (g->state != LAUNCHING)
1231 error (g, "received magic signature from guestfsd, but in state %d",
1233 else if (g->msg_in_size != 4)
1234 error (g, "received magic signature from guestfsd, but msg size is %d",
1238 if (g->launch_done_cb)
1239 g->launch_done_cb (g, g->launch_done_cb_data);
1245 /* This can happen if a cancellation happens right at the end
1246 * of us sending a FileIn parameter to the daemon. Discard. The
1247 * daemon should send us an error message next.
1249 if (len == GUESTFS_CANCEL_FLAG) {
1250 g->msg_in_size -= 4;
1251 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1255 /* If this happens, it's pretty bad and we've probably lost
1258 if (len > GUESTFS_MESSAGE_MAX) {
1259 error (g, "message length (%u) > maximum possible size (%d)",
1260 len, GUESTFS_MESSAGE_MAX);
1264 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1266 /* Got the full message, begin processing it. */
1270 for (i = 0; i < g->msg_in_size; i += 16) {
1271 printf ("%04x: ", i);
1272 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1273 printf ("%02x ", (unsigned char) g->msg_in[j]);
1274 for (; j < i+16; ++j)
1277 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1278 if (isprint (g->msg_in[j]))
1279 printf ("%c", g->msg_in[j]);
1282 for (; j < i+16; ++j)
1288 /* Not in the expected state. */
1289 if (g->state != BUSY)
1290 error (g, "state %d != BUSY", g->state);
1292 /* Push the message up to the higher layer. */
1294 g->reply_cb (g, g->reply_cb_data, &xdr);
1296 g->msg_in_size -= len + 4;
1297 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1298 if (g->msg_in_size > 0) goto again;
1301 /* Free the message buffer if it's grown excessively large. */
1302 if (g->msg_in_allocated > 65536) {
1305 g->msg_in_size = g->msg_in_allocated = 0;
1312 /* The function is called whenever we can write something on the
1313 * guestfsd (daemon inside the guest) communication socket.
1316 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1317 int watch, int fd, int events)
1323 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1324 g, g->state, fd, events);
1326 if (g->sock != fd) {
1327 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1331 if (g->state != BUSY) {
1332 error (g, "sock_write_event: state %d != BUSY", g->state);
1337 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1338 g->msg_out_size - g->msg_out_pos);
1340 n = write (g->sock, g->msg_out + g->msg_out_pos,
1341 g->msg_out_size - g->msg_out_pos);
1343 if (errno != EAGAIN)
1344 perrorf (g, "write");
1349 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1351 g->msg_out_pos += n;
1353 /* More to write? */
1354 if (g->msg_out_pos < g->msg_out_size)
1358 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1362 g->msg_out_pos = g->msg_out_size = 0;
1364 /* Done writing, call the higher layer. */
1366 g->send_cb (g, g->send_cb_data);
1370 guestfs_set_send_callback (guestfs_h *g,
1371 guestfs_send_cb cb, void *opaque)
1374 g->send_cb_data = opaque;
1378 guestfs_set_reply_callback (guestfs_h *g,
1379 guestfs_reply_cb cb, void *opaque)
1382 g->reply_cb_data = opaque;
1386 guestfs_set_log_message_callback (guestfs_h *g,
1387 guestfs_log_message_cb cb, void *opaque)
1389 g->log_message_cb = cb;
1390 g->log_message_cb_data = opaque;
1394 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1395 guestfs_subprocess_quit_cb cb, void *opaque)
1397 g->subprocess_quit_cb = cb;
1398 g->subprocess_quit_cb_data = opaque;
1402 guestfs_set_launch_done_callback (guestfs_h *g,
1403 guestfs_launch_done_cb cb, void *opaque)
1405 g->launch_done_cb = cb;
1406 g->launch_done_cb_data = opaque;
1409 /* Access to the handle's main loop and the default main loop. */
1411 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1413 g->main_loop = main_loop;
1417 guestfs_get_main_loop (guestfs_h *g)
1419 return g->main_loop;
1423 guestfs_get_default_main_loop (void)
1425 return (guestfs_main_loop *) &default_main_loop;
1428 /* Change the daemon socket handler so that we are now writing.
1429 * This sets the handle to sock_write_event.
1432 guestfs__switch_to_sending (guestfs_h *g)
1434 if (g->sock_watch >= 0) {
1435 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1436 error (g, "remove_handle failed");
1443 g->main_loop->add_handle (g->main_loop, g, g->sock,
1444 GUESTFS_HANDLE_WRITABLE,
1445 sock_write_event, NULL);
1446 if (g->sock_watch == -1) {
1447 error (g, "add_handle failed");
1455 guestfs__switch_to_receiving (guestfs_h *g)
1457 if (g->sock_watch >= 0) {
1458 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1459 error (g, "remove_handle failed");
1466 g->main_loop->add_handle (g->main_loop, g, g->sock,
1467 GUESTFS_HANDLE_READABLE,
1468 sock_read_event, NULL);
1469 if (g->sock_watch == -1) {
1470 error (g, "add_handle failed");
1477 /* Dispatch a call (len + header + args) to the remote daemon,
1478 * synchronously (ie. using the guest's main loop to wait until
1479 * it has been sent). Returns -1 for error, or the serial
1480 * number of the message.
1483 send_cb (guestfs_h *g, void *data)
1485 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1488 ml->main_loop_quit (ml, g);
1492 guestfs__send_sync (guestfs_h *g, int proc_nr,
1493 xdrproc_t xdrp, char *args)
1495 struct guestfs_message_header hdr;
1498 int serial = g->msg_next_serial++;
1500 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1502 if (g->state != BUSY) {
1503 error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1507 /* This is probably an internal error. Or perhaps we should just
1508 * free the buffer anyway?
1510 if (g->msg_out != NULL) {
1511 error (g, "guestfs__send_sync: msg_out should be NULL");
1515 /* We have to allocate this message buffer on the heap because
1516 * it is quite large (although will be mostly unused). We
1517 * can't allocate it on the stack because in some environments
1518 * we have quite limited stack space available, notably when
1519 * running in the JVM.
1521 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1522 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1524 /* Serialize the header. */
1525 hdr.prog = GUESTFS_PROGRAM;
1526 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1528 hdr.direction = GUESTFS_DIRECTION_CALL;
1529 hdr.serial = serial;
1530 hdr.status = GUESTFS_STATUS_OK;
1532 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1533 error (g, "xdr_guestfs_message_header failed");
1537 /* Serialize the args. If any, because some message types
1538 * have no parameters.
1541 if (!(*xdrp) (&xdr, args)) {
1542 error (g, "dispatch failed to marshal args");
1547 /* Get the actual length of the message, resize the buffer to match
1548 * the actual length, and write the length word at the beginning.
1550 len = xdr_getpos (&xdr);
1553 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1554 g->msg_out_size = len + 4;
1557 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1558 xdr_uint32_t (&xdr, &len);
1560 if (guestfs__switch_to_sending (g) == -1)
1564 guestfs_set_send_callback (g, send_cb, &sent);
1565 if (ml->main_loop_run (ml, g) == -1)
1568 error (g, "send failed, see earlier error messages");
1577 g->msg_out_size = 0;
1581 static int cancel = 0; /* XXX Implement file cancellation. */
1582 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1583 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1584 static int send_file_cancellation_sync (guestfs_h *g);
1585 static int send_file_complete_sync (guestfs_h *g);
1587 /* Synchronously send a file.
1591 * -2 daemon cancelled (we must read the error message)
1594 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1596 char buf[GUESTFS_MAX_CHUNK_SIZE];
1599 fd = open (filename, O_RDONLY);
1601 perrorf (g, "open: %s", filename);
1602 send_file_cancellation_sync (g);
1603 /* Daemon sees cancellation and won't reply, so caller can
1609 /* Send file in chunked encoding. */
1610 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1611 err = send_file_data_sync (g, buf, r);
1613 if (err == -2) /* daemon sent cancellation */
1614 send_file_cancellation_sync (g);
1619 if (cancel) { /* cancel from either end */
1620 send_file_cancellation_sync (g);
1625 perrorf (g, "read: %s", filename);
1626 send_file_cancellation_sync (g);
1630 /* End of file, but before we send that, we need to close
1631 * the file and check for errors.
1633 if (close (fd) == -1) {
1634 perrorf (g, "close: %s", filename);
1635 send_file_cancellation_sync (g);
1639 return send_file_complete_sync (g);
1642 /* Send a chunk of file data. */
1644 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1646 return send_file_chunk_sync (g, 0, buf, len);
1649 /* Send a cancellation message. */
1651 send_file_cancellation_sync (guestfs_h *g)
1653 return send_file_chunk_sync (g, 1, NULL, 0);
1656 /* Send a file complete chunk. */
1658 send_file_complete_sync (guestfs_h *g)
1661 return send_file_chunk_sync (g, 0, buf, 0);
1664 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1667 static int check_for_daemon_cancellation (guestfs_h *g);
1670 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len)
1672 char data[GUESTFS_MAX_CHUNK_SIZE + 48];
1675 guestfs_chunk chunk;
1677 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1679 if (g->state != BUSY) {
1680 error (g, "send_file_chunk_sync: state %d != READY", g->state);
1684 /* Did the daemon send a cancellation message? */
1685 if (check_for_daemon_cancellation (g)) {
1687 fprintf (stderr, "got daemon cancellation\n");
1691 /* Serialize the chunk. */
1692 chunk.cancel = cancel;
1693 chunk.data.data_len = len;
1694 chunk.data.data_val = (char *) buf;
1698 "library sending chunk cancel = %d, len = %zu, buf = %p\n",
1701 xdrmem_create (&xdr, data, sizeof data, XDR_ENCODE);
1702 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1703 error (g, "xdr_guestfs_chunk failed (buf = %p, len = %zu)", buf, len);
1708 datalen = xdr_getpos (&xdr);
1711 /* Allocate outgoing message buffer. */
1712 g->msg_out = safe_malloc (g, datalen + 4);
1713 g->msg_out_size = datalen + 4;
1716 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1717 xdr_uint32_t (&xdr, &datalen);
1719 memcpy (g->msg_out + 4, data, datalen);
1721 if (guestfs__switch_to_sending (g) == -1)
1725 guestfs_set_send_callback (g, send_cb, &sent);
1726 if (ml->main_loop_run (ml, g) == -1)
1729 error (g, "send file chunk failed, see earlier error messages");
1738 g->msg_out_size = 0;
1742 /* At this point we are sending FileIn file(s) to the guest, and not
1743 * expecting to read anything, so if we do read anything, it must be
1744 * a cancellation message. This checks for this case without blocking.
1747 check_for_daemon_cancellation (guestfs_h *g)
1757 FD_SET (g->sock, &rset);
1760 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1762 perrorf (g, "select");
1768 /* Read the message from the daemon. */
1769 r = xread (g->sock, buf, sizeof buf);
1771 perrorf (g, "read");
1775 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1776 xdr_uint32_t (&xdr, &flag);
1779 if (flag != GUESTFS_CANCEL_FLAG) {
1780 error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1781 flag, GUESTFS_CANCEL_FLAG);
1788 /* Synchronously receive a file. */
1790 static int receive_file_data_sync (guestfs_h *g, void **buf);
1793 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1798 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1800 perrorf (g, "open: %s", filename);
1804 /* Receive the file in chunked encoding. */
1805 while ((r = receive_file_data_sync (g, &buf)) > 0) {
1806 if (xwrite (fd, buf, r) == -1) {
1807 perrorf (g, "%s: write", filename);
1815 error (g, "%s: error in chunked encoding", filename);
1819 if (close (fd) == -1) {
1820 perrorf (g, "close: %s", filename);
1827 /* Send cancellation message to daemon, then wait until it
1828 * cancels (just throwing away data).
1832 uint32_t flag = GUESTFS_CANCEL_FLAG;
1834 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1835 xdr_uint32_t (&xdr, &flag);
1838 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1839 perrorf (g, "write to daemon socket");
1843 while ((r = receive_file_data_sync (g, &buf)) > 0)
1844 free (buf); /* just discard it */
1849 struct receive_file_ctx {
1855 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1857 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1858 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1859 guestfs_chunk chunk;
1861 ml->main_loop_quit (ml, g);
1863 memset (&chunk, 0, sizeof chunk);
1865 if (!xdr_guestfs_chunk (xdr, &chunk)) {
1866 error (g, "failed to parse file chunk");
1871 error (g, "file receive cancelled by daemon");
1875 if (chunk.data.data_len == 0) { /* end of transfer */
1880 ctx->code = chunk.data.data_len;
1881 *ctx->buf = chunk.data.data_val; /* caller frees */
1884 /* Receive a chunk of file data. */
1886 receive_file_data_sync (guestfs_h *g, void **buf)
1888 struct receive_file_ctx ctx;
1889 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1894 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
1895 (void) ml->main_loop_run (ml, g);
1896 guestfs_set_reply_callback (g, NULL, NULL);
1899 fprintf (stderr, "receive_file_data_sync: code %d\n", ctx.code);
1902 case 0: /* end of file */
1907 error (g, "failed to call receive_file_cb");
1909 default: /* received n bytes of data */
1914 /* This is the default main loop implementation, using select(2). */
1917 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1918 guestfs_handle_event_cb cb, void *data)
1920 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1922 if (fd < 0 || fd >= FD_SETSIZE) {
1923 error (g, "fd %d is out of range", fd);
1927 if ((events & ~(GUESTFS_HANDLE_READABLE |
1928 GUESTFS_HANDLE_WRITABLE |
1929 GUESTFS_HANDLE_HANGUP |
1930 GUESTFS_HANDLE_ERROR)) != 0) {
1931 error (g, "set of events (0x%x) contains unknown events", events);
1936 error (g, "set of events is empty");
1940 if (FD_ISSET (fd, &ml->rset) ||
1941 FD_ISSET (fd, &ml->wset) ||
1942 FD_ISSET (fd, &ml->xset)) {
1943 error (g, "fd %d is already registered", fd);
1948 error (g, "callback is NULL");
1952 if ((events & GUESTFS_HANDLE_READABLE))
1953 FD_SET (fd, &ml->rset);
1954 if ((events & GUESTFS_HANDLE_WRITABLE))
1955 FD_SET (fd, &ml->wset);
1956 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1957 FD_SET (fd, &ml->xset);
1959 if (fd > ml->max_fd) {
1961 ml->handle_cb_data =
1962 safe_realloc (g, ml->handle_cb_data,
1963 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1965 ml->handle_cb_data[fd].cb = cb;
1966 ml->handle_cb_data[fd].g = g;
1967 ml->handle_cb_data[fd].data = data;
1971 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1976 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1978 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1980 if (fd < 0 || fd >= FD_SETSIZE) {
1981 error (g, "fd %d is out of range", fd);
1985 if (!FD_ISSET (fd, &ml->rset) &&
1986 !FD_ISSET (fd, &ml->wset) &&
1987 !FD_ISSET (fd, &ml->xset)) {
1988 error (g, "fd %d was not registered", fd);
1992 FD_CLR (fd, &ml->rset);
1993 FD_CLR (fd, &ml->wset);
1994 FD_CLR (fd, &ml->xset);
1996 if (fd == ml->max_fd) {
1998 ml->handle_cb_data =
1999 safe_realloc (g, ml->handle_cb_data,
2000 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2009 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2010 guestfs_handle_timeout_cb cb, void *data)
2012 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2014 abort (); /* XXX not implemented yet */
2018 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2020 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2022 abort (); /* XXX not implemented yet */
2025 /* The 'g' parameter is just used for error reporting. Events
2026 * for multiple handles can be dispatched by running the main
2030 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2032 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2034 fd_set rset2, wset2, xset2;
2036 if (ml->is_running) {
2037 error (g, "select_main_loop_run: this cannot be called recursively");
2043 while (ml->is_running) {
2044 if (ml->nr_fds == 0)
2050 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2052 perrorf (g, "select");
2057 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2059 if (FD_ISSET (fd, &rset2))
2060 events |= GUESTFS_HANDLE_READABLE;
2061 if (FD_ISSET (fd, &wset2))
2062 events |= GUESTFS_HANDLE_WRITABLE;
2063 if (FD_ISSET (fd, &xset2))
2064 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2067 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2068 ml->handle_cb_data[fd].g,
2069 ml->handle_cb_data[fd].data,
2080 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2082 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2084 /* Note that legitimately ml->is_running can be zero when
2085 * this function is called.