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 */
32 #include <sys/select.h>
33 #include <rpc/types.h>
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
44 #ifdef HAVE_SYS_WAIT_H
48 #ifdef HAVE_SYS_SOCKET_H
49 #include <sys/socket.h>
57 #include "guestfs_protocol.h"
59 #define error guestfs_error
60 #define perrorf guestfs_perrorf
61 #define safe_malloc guestfs_safe_malloc
62 #define safe_realloc guestfs_safe_realloc
63 #define safe_strdup guestfs_safe_strdup
64 #define safe_memdup guestfs_safe_memdup
66 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
67 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
68 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
69 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
71 static void close_handles (void);
73 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
74 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
75 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
76 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
77 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
78 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
80 /* Default select-based main loop. */
81 struct select_handle_cb_data {
82 guestfs_handle_event_cb cb;
87 struct select_main_loop {
88 /* NB. These fields must be the same as in struct guestfs_main_loop: */
89 guestfs_add_handle_cb add_handle;
90 guestfs_remove_handle_cb remove_handle;
91 guestfs_add_timeout_cb add_timeout;
92 guestfs_remove_timeout_cb remove_timeout;
93 guestfs_main_loop_run_cb main_loop_run;
94 guestfs_main_loop_quit_cb main_loop_quit;
96 /* Additional private data: */
105 struct select_handle_cb_data *handle_cb_data;
108 /* Default main loop. */
109 static struct select_main_loop default_main_loop = {
110 .add_handle = select_add_handle,
111 .remove_handle = select_remove_handle,
112 .add_timeout = select_add_timeout,
113 .remove_timeout = select_remove_timeout,
114 .main_loop_run = select_main_loop_run,
115 .main_loop_quit = select_main_loop_quit,
117 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
118 * set by the normal action of everything being initialized to zero.
123 .handle_cb_data = NULL,
126 #define UNIX_PATH_MAX 108
128 /* Also in guestfsd.c */
129 #define VMCHANNEL_PORT 6666
130 #define VMCHANNEL_ADDR "10.0.2.4"
132 /* GuestFS handle and connection. */
133 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
137 struct guestfs_h *next; /* Linked list of open handles. */
139 /* State: see the state machine diagram in the man page guestfs(3). */
142 int fd[2]; /* Stdin/stdout of qemu. */
143 int sock; /* Daemon communications socket. */
144 int pid; /* Qemu PID. */
145 time_t start_t; /* The time when we started qemu. */
147 int stdout_watch; /* Watches qemu stdout for log messages. */
148 int sock_watch; /* Watches daemon comm socket. */
150 char *tmpdir; /* Temporary directory containing socket. */
152 char **cmdline; /* Qemu command line. */
163 guestfs_abort_cb abort_cb;
164 guestfs_error_handler_cb error_cb;
165 void * error_cb_data;
166 guestfs_send_cb send_cb;
168 guestfs_reply_cb reply_cb;
169 void * reply_cb_data;
170 guestfs_log_message_cb log_message_cb;
171 void * log_message_cb_data;
172 guestfs_subprocess_quit_cb subprocess_quit_cb;
173 void * subprocess_quit_cb_data;
174 guestfs_launch_done_cb launch_done_cb;
175 void * launch_done_cb_data;
177 /* Main loop used by this handle. */
178 guestfs_main_loop *main_loop;
180 /* Messages sent and received from the daemon. */
182 int msg_in_size, msg_in_allocated;
184 int msg_out_size, msg_out_pos;
189 static guestfs_h *handles = NULL;
190 static int atexit_handler_set = 0;
193 guestfs_create (void)
198 g = malloc (sizeof (*g));
201 memset (g, 0, sizeof (*g));
208 g->stdout_watch = -1;
212 g->error_cb = default_error_cb;
213 g->error_cb_data = NULL;
215 str = getenv ("LIBGUESTFS_DEBUG");
216 g->verbose = str != NULL && strcmp (str, "1") == 0;
218 str = getenv ("LIBGUESTFS_PATH");
219 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
220 /* XXX We should probably make QEMU configurable as well. */
222 g->main_loop = guestfs_get_default_main_loop ();
224 /* Start with large serial numbers so they are easy to spot
225 * inside the protocol.
227 g->msg_next_serial = 0x00123400;
229 /* Link the handles onto a global list. This is the one area
230 * where the library needs to be made thread-safe. (XXX)
232 /* acquire mutex (XXX) */
235 if (!atexit_handler_set) {
236 atexit (close_handles);
237 atexit_handler_set = 1;
239 /* release mutex (XXX) */
242 fprintf (stderr, "new guestfs handle %p\n", g);
248 guestfs_close (guestfs_h *g)
254 if (g->state == NO_HANDLE) {
255 /* Not safe to call 'error' here, so ... */
256 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
261 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
263 /* Try to sync if autosync flag is set. */
264 if (g->autosync && g->state == READY)
267 /* Remove any handlers that might be called back before we kill the
270 g->log_message_cb = NULL;
272 if (g->state != CONFIG)
273 guestfs_kill_subprocess (g);
276 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
285 for (i = 0; i < g->cmdline_size; ++i)
286 free (g->cmdline[i]);
290 /* Mark the handle as dead before freeing it. */
291 g->state = NO_HANDLE;
293 /* acquire mutex (XXX) */
297 for (gg = handles; gg->next != g; gg = gg->next)
301 /* release mutex (XXX) */
303 free (g->last_error);
307 /* Close all open handles (called from atexit(3)). */
311 while (handles) guestfs_close (handles);
315 guestfs_last_error (guestfs_h *g)
317 return g->last_error;
321 set_last_error (guestfs_h *g, const char *msg)
323 free (g->last_error);
324 g->last_error = strdup (msg);
328 default_error_cb (guestfs_h *g, void *data, const char *msg)
330 fprintf (stderr, "libguestfs: error: %s\n", msg);
334 guestfs_error (guestfs_h *g, const char *fs, ...)
340 vasprintf (&msg, fs, args);
343 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
344 set_last_error (g, msg);
350 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
357 vasprintf (&msg, fs, args);
362 strerror_r (err, buf, sizeof buf);
366 buf = strerror_r (err, _buf, sizeof _buf);
369 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
373 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
374 set_last_error (g, msg);
380 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
382 void *ptr = malloc (nbytes);
383 if (!ptr) g->abort_cb ();
388 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
390 void *p = realloc (ptr, nbytes);
391 if (!p) g->abort_cb ();
396 guestfs_safe_strdup (guestfs_h *g, const char *str)
398 char *s = strdup (str);
399 if (!s) g->abort_cb ();
404 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
406 void *p = malloc (size);
407 if (!p) g->abort_cb ();
408 memcpy (p, ptr, size);
413 xwrite (int fd, const void *buf, size_t len)
418 r = write (fd, buf, len);
430 xread (int fd, void *buf, size_t len)
435 r = read (fd, buf, len);
447 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
453 guestfs_get_out_of_memory_handler (guestfs_h *g)
459 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
462 g->error_cb_data = data;
465 guestfs_error_handler_cb
466 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
468 if (data_rtn) *data_rtn = g->error_cb_data;
473 guestfs_set_verbose (guestfs_h *g, int v)
480 guestfs_get_verbose (guestfs_h *g)
486 guestfs_set_autosync (guestfs_h *g, int a)
493 guestfs_get_autosync (guestfs_h *g)
499 guestfs_set_path (guestfs_h *g, const char *path)
502 g->path = GUESTFS_DEFAULT_PATH;
509 guestfs_get_path (guestfs_h *g)
514 /* Add a string to the current command line. */
516 incr_cmdline_size (guestfs_h *g)
518 if (g->cmdline == NULL) {
519 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
521 g->cmdline = safe_malloc (g, sizeof (char *));
522 g->cmdline[0] = NULL;
526 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
530 add_cmdline (guestfs_h *g, const char *str)
532 if (g->state != CONFIG) {
533 error (g, "command line cannot be altered after qemu subprocess launched");
537 incr_cmdline_size (g);
538 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
543 guestfs_config (guestfs_h *g,
544 const char *qemu_param, const char *qemu_value)
546 if (qemu_param[0] != '-') {
547 error (g, "guestfs_config: parameter must begin with '-' character");
551 /* A bit fascist, but the user will probably break the extra
552 * parameters that we add if they try to set any of these.
554 if (strcmp (qemu_param, "-kernel") == 0 ||
555 strcmp (qemu_param, "-initrd") == 0 ||
556 strcmp (qemu_param, "-nographic") == 0 ||
557 strcmp (qemu_param, "-serial") == 0 ||
558 strcmp (qemu_param, "-vnc") == 0 ||
559 strcmp (qemu_param, "-full-screen") == 0 ||
560 strcmp (qemu_param, "-std-vga") == 0 ||
561 strcmp (qemu_param, "-vnc") == 0) {
562 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
566 if (add_cmdline (g, qemu_param) != 0) return -1;
568 if (qemu_value != NULL) {
569 if (add_cmdline (g, qemu_value) != 0) return -1;
576 guestfs_add_drive (guestfs_h *g, const char *filename)
578 int len = strlen (filename) + 64;
581 if (strchr (filename, ',') != NULL) {
582 error (g, "filename cannot contain ',' (comma) character");
586 if (access (filename, F_OK) == -1) {
587 perrorf (g, "%s", filename);
591 snprintf (buf, len, "file=%s", filename);
593 return guestfs_config (g, "-drive", buf);
597 guestfs_add_cdrom (guestfs_h *g, const char *filename)
599 if (strchr (filename, ',') != NULL) {
600 error (g, "filename cannot contain ',' (comma) character");
604 if (access (filename, F_OK) == -1) {
605 perrorf (g, "%s", filename);
609 return guestfs_config (g, "-cdrom", filename);
613 guestfs_launch (guestfs_h *g)
615 static const char *dir_template = "/tmp/libguestfsXXXXXX";
616 int r, i, len, pmore;
619 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
620 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
621 char *path, *pelem, *pend;
622 char *kernel = NULL, *initrd = NULL;
624 struct sockaddr_un addr;
628 error (g, "you must call guestfs_add_drive before guestfs_launch");
632 if (g->state != CONFIG) {
633 error (g, "qemu has already been launched");
637 /* Search g->path for the kernel and initrd. */
638 pelem = path = safe_strdup (g, g->path);
640 pend = strchrnul (pelem, ':');
641 pmore = *pend == ':';
645 /* Empty element or "." means cwd. */
646 if (len == 0 || (len == 1 && *pelem == '.')) {
649 "looking for kernel and initrd in current directory\n");
650 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
651 kernel = safe_strdup (g, kernel_name);
652 initrd = safe_strdup (g, initrd_name);
656 /* Look at <path>/kernel etc. */
658 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
659 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
660 sprintf (kernel, "%s/%s", pelem, kernel_name);
661 sprintf (initrd, "%s/%s", pelem, initrd_name);
664 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
666 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
670 kernel = initrd = NULL;
678 if (kernel == NULL || initrd == NULL) {
679 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
680 kernel_name, initrd_name, g->path);
684 /* Make the temporary directory containing the socket. */
686 g->tmpdir = safe_strdup (g, dir_template);
687 if (mkdtemp (g->tmpdir) == NULL) {
688 perrorf (g, "%s: cannot create temporary directory", dir_template);
693 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
696 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
711 if (r == 0) { /* Child (qemu). */
715 /* Set up the full command line. Do this in the subprocess so we
716 * don't need to worry about cleaning up.
718 g->cmdline[0] = (char *) QEMU;
720 /* Construct the -net channel parameter for qemu. */
721 snprintf (vmchannel, sizeof vmchannel,
722 "channel,%d:unix:%s,server,nowait",
723 VMCHANNEL_PORT, unixsock);
725 /* Linux kernel command line. */
726 snprintf (append, sizeof append,
727 "console=ttyS0 guestfs=%s:%d%s",
728 VMCHANNEL_ADDR, VMCHANNEL_PORT,
729 g->verbose ? " guestfs_verbose=1" : "");
731 add_cmdline (g, "-m");
732 add_cmdline (g, "384"); /* XXX Choose best size. */
733 #if defined(__i386__) || defined(__x86_64)
734 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
736 add_cmdline (g, "-kernel");
737 add_cmdline (g, (char *) kernel);
738 add_cmdline (g, "-initrd");
739 add_cmdline (g, (char *) initrd);
740 add_cmdline (g, "-append");
741 add_cmdline (g, append);
742 add_cmdline (g, "-nographic");
743 add_cmdline (g, "-serial");
744 add_cmdline (g, "stdio");
745 add_cmdline (g, "-net");
746 add_cmdline (g, vmchannel);
747 add_cmdline (g, "-net");
748 add_cmdline (g, "user,vlan=0");
749 add_cmdline (g, "-net");
750 add_cmdline (g, "nic,vlan=0");
751 incr_cmdline_size (g);
752 g->cmdline[g->cmdline_size-1] = NULL;
755 fprintf (stderr, "%s", QEMU);
756 for (i = 0; g->cmdline[i]; ++i)
757 fprintf (stderr, " %s", g->cmdline[i]);
758 fprintf (stderr, "\n");
761 /* Set up stdin, stdout. */
772 /* Set up a new process group, so we can signal this process
773 * and all subprocesses (eg. if qemu is really a shell script).
778 execv (QEMU, g->cmdline); /* Run qemu. */
783 /* Parent (library). */
786 /* Start the clock ... */
789 /* Close the other ends of the pipe. */
793 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
794 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
795 perrorf (g, "fcntl");
799 g->fd[0] = wfd[1]; /* stdin of child */
800 g->fd[1] = rfd[0]; /* stdout of child */
802 /* Open the Unix socket. The vmchannel implementation that got
803 * merged with qemu sucks in a number of ways. Both ends do
804 * connect(2), which means that no one knows what, if anything, is
805 * connected to the other end, or if it becomes disconnected. Even
806 * worse, we have to wait some indeterminate time for qemu to create
807 * the socket and connect to it (which happens very early in qemu's
808 * start-up), so any code that uses vmchannel is inherently racy.
809 * Hence this silly loop.
811 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
813 perrorf (g, "socket");
817 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
818 perrorf (g, "fcntl");
822 addr.sun_family = AF_UNIX;
823 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
824 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
828 /* Always sleep at least once to give qemu a small chance to start up. */
831 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
832 if ((r == -1 && errno == EINPROGRESS) || r == 0)
836 perrorf (g, "connect");
840 error (g, "failed to connect to vmchannel socket");
844 /* Watch the file descriptors. */
847 g->msg_in_size = g->msg_in_allocated = 0;
855 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
856 GUESTFS_HANDLE_READABLE,
858 if (g->stdout_watch == -1) {
859 error (g, "could not watch qemu stdout");
863 if (guestfs__switch_to_receiving (g) == -1)
866 g->state = LAUNCHING;
870 if (g->stdout_watch >= 0)
871 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
872 if (g->sock_watch >= 0)
873 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
882 waitpid (g->pid, NULL, 0);
888 g->stdout_watch = -1;
898 finish_wait_ready (guestfs_h *g, void *vp)
901 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
904 g->main_loop->main_loop_quit (g->main_loop, g);
908 guestfs_wait_ready (guestfs_h *g)
912 if (g->state == READY) return 0;
914 if (g->state == BUSY) {
915 error (g, "qemu has finished launching already");
919 if (g->state != LAUNCHING) {
920 error (g, "qemu has not been launched yet");
924 g->launch_done_cb = finish_wait_ready;
925 g->launch_done_cb_data = &finished;
926 r = g->main_loop->main_loop_run (g->main_loop, g);
927 g->launch_done_cb = NULL;
928 g->launch_done_cb_data = NULL;
930 if (r == -1) return -1;
933 error (g, "guestfs_wait_ready failed, see earlier error messages");
937 /* This is possible in some really strange situations, such as
938 * guestfsd starts up OK but then qemu immediately exits. Check for
939 * it because the caller is probably expecting to be able to send
940 * commands after this function returns.
942 if (g->state != READY) {
943 error (g, "qemu launched and contacted daemon, but state != READY");
951 guestfs_kill_subprocess (guestfs_h *g)
953 if (g->state == CONFIG) {
954 error (g, "no subprocess to kill");
959 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
961 kill (g->pid, SIGTERM);
966 /* Access current state. */
968 guestfs_is_config (guestfs_h *g)
970 return g->state == CONFIG;
974 guestfs_is_launching (guestfs_h *g)
976 return g->state == LAUNCHING;
980 guestfs_is_ready (guestfs_h *g)
982 return g->state == READY;
986 guestfs_is_busy (guestfs_h *g)
988 return g->state == BUSY;
992 guestfs_get_state (guestfs_h *g)
998 guestfs_set_ready (guestfs_h *g)
1000 if (g->state != BUSY) {
1001 error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1009 guestfs_set_busy (guestfs_h *g)
1011 if (g->state != READY) {
1012 error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1019 /* Structure-freeing functions. These rely on the fact that the
1020 * structure format is identical to the XDR format. See note in
1024 guestfs_free_int_bool (struct guestfs_int_bool *x)
1030 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1032 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1037 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1039 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1044 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1046 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1050 /* This function is called whenever qemu prints something on stdout.
1051 * Qemu's stdout is also connected to the guest's serial console, so
1052 * we see kernel messages here too.
1055 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1056 int watch, int fd, int events)
1064 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1065 g, g->state, fd, events);
1068 if (g->fd[1] != fd) {
1069 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1073 n = read (fd, buf, sizeof buf);
1075 /* Hopefully this indicates the qemu child process has died. */
1077 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1078 /*kill (g->pid, SIGTERM);*/
1079 waitpid (g->pid, NULL, 0);
1080 if (g->stdout_watch >= 0)
1081 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1082 if (g->sock_watch >= 0)
1083 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1092 g->stdout_watch = -1;
1095 if (g->subprocess_quit_cb)
1096 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1101 if (errno != EAGAIN)
1102 perrorf (g, "read");
1106 /* In verbose mode, copy all log messages to stderr. */
1110 /* It's an actual log message, send it upwards if anyone is listening. */
1111 if (g->log_message_cb)
1112 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1115 /* The function is called whenever we can read something on the
1116 * guestfsd (daemon inside the guest) communication socket.
1119 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1120 int watch, int fd, int events)
1128 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1129 g, g->state, fd, events);
1131 if (g->sock != fd) {
1132 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1136 if (g->msg_in_size <= g->msg_in_allocated) {
1137 g->msg_in_allocated += 4096;
1138 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1140 n = read (g->sock, g->msg_in + g->msg_in_size,
1141 g->msg_in_allocated - g->msg_in_size);
1143 /* Disconnected? Ignore it because stdout_watch will get called
1144 * and will do the cleanup.
1149 if (errno != EAGAIN)
1150 perrorf (g, "read");
1154 g->msg_in_size += n;
1156 /* Have we got enough of a message to be able to process it yet? */
1158 if (g->msg_in_size < 4) return;
1160 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1161 if (!xdr_uint32_t (&xdr, &len)) {
1162 error (g, "can't decode length word");
1166 /* Length is normally the length of the message, but when guestfsd
1167 * starts up it sends a "magic" value (longer than any possible
1168 * message). Check for this.
1170 if (len == GUESTFS_LAUNCH_FLAG) {
1171 if (g->state != LAUNCHING)
1172 error (g, "received magic signature from guestfsd, but in state %d",
1174 else if (g->msg_in_size != 4)
1175 error (g, "received magic signature from guestfsd, but msg size is %d",
1179 if (g->launch_done_cb)
1180 g->launch_done_cb (g, g->launch_done_cb_data);
1186 /* This can happen if a cancellation happens right at the end
1187 * of us sending a FileIn parameter to the daemon. Discard. The
1188 * daemon should send us an error message next.
1190 if (len == GUESTFS_CANCEL_FLAG) {
1191 g->msg_in_size -= 4;
1192 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1196 /* If this happens, it's pretty bad and we've probably lost
1199 if (len > GUESTFS_MESSAGE_MAX) {
1200 error (g, "message length (%u) > maximum possible size (%d)",
1201 len, GUESTFS_MESSAGE_MAX);
1205 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1207 /* Got the full message, begin processing it. */
1211 for (i = 0; i < g->msg_in_size; i += 16) {
1212 printf ("%04x: ", i);
1213 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1214 printf ("%02x ", (unsigned char) g->msg_in[j]);
1215 for (; j < i+16; ++j)
1218 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1219 if (isprint (g->msg_in[j]))
1220 printf ("%c", g->msg_in[j]);
1223 for (; j < i+16; ++j)
1229 /* Not in the expected state. */
1230 if (g->state != BUSY)
1231 error (g, "state %d != BUSY", g->state);
1233 /* Push the message up to the higher layer. */
1235 g->reply_cb (g, g->reply_cb_data, &xdr);
1237 g->msg_in_size -= len + 4;
1238 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1239 if (g->msg_in_size > 0) goto again;
1242 /* Free the message buffer if it's grown excessively large. */
1243 if (g->msg_in_allocated > 65536) {
1246 g->msg_in_size = g->msg_in_allocated = 0;
1253 /* The function is called whenever we can write something on the
1254 * guestfsd (daemon inside the guest) communication socket.
1257 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1258 int watch, int fd, int events)
1264 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1265 g, g->state, fd, events);
1267 if (g->sock != fd) {
1268 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1272 if (g->state != BUSY) {
1273 error (g, "sock_write_event: state %d != BUSY", g->state);
1278 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1279 g->msg_out_size - g->msg_out_pos);
1281 n = write (g->sock, g->msg_out + g->msg_out_pos,
1282 g->msg_out_size - g->msg_out_pos);
1284 if (errno != EAGAIN)
1285 perrorf (g, "write");
1290 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1292 g->msg_out_pos += n;
1294 /* More to write? */
1295 if (g->msg_out_pos < g->msg_out_size)
1299 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1303 g->msg_out_pos = g->msg_out_size = 0;
1305 /* Done writing, call the higher layer. */
1307 g->send_cb (g, g->send_cb_data);
1311 guestfs_set_send_callback (guestfs_h *g,
1312 guestfs_send_cb cb, void *opaque)
1315 g->send_cb_data = opaque;
1319 guestfs_set_reply_callback (guestfs_h *g,
1320 guestfs_reply_cb cb, void *opaque)
1323 g->reply_cb_data = opaque;
1327 guestfs_set_log_message_callback (guestfs_h *g,
1328 guestfs_log_message_cb cb, void *opaque)
1330 g->log_message_cb = cb;
1331 g->log_message_cb_data = opaque;
1335 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1336 guestfs_subprocess_quit_cb cb, void *opaque)
1338 g->subprocess_quit_cb = cb;
1339 g->subprocess_quit_cb_data = opaque;
1343 guestfs_set_launch_done_callback (guestfs_h *g,
1344 guestfs_launch_done_cb cb, void *opaque)
1346 g->launch_done_cb = cb;
1347 g->launch_done_cb_data = opaque;
1350 /* Access to the handle's main loop and the default main loop. */
1352 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1354 g->main_loop = main_loop;
1358 guestfs_get_main_loop (guestfs_h *g)
1360 return g->main_loop;
1364 guestfs_get_default_main_loop (void)
1366 return (guestfs_main_loop *) &default_main_loop;
1369 /* Change the daemon socket handler so that we are now writing.
1370 * This sets the handle to sock_write_event.
1373 guestfs__switch_to_sending (guestfs_h *g)
1375 if (g->sock_watch >= 0) {
1376 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1377 error (g, "remove_handle failed");
1384 g->main_loop->add_handle (g->main_loop, g, g->sock,
1385 GUESTFS_HANDLE_WRITABLE,
1386 sock_write_event, NULL);
1387 if (g->sock_watch == -1) {
1388 error (g, "add_handle failed");
1396 guestfs__switch_to_receiving (guestfs_h *g)
1398 if (g->sock_watch >= 0) {
1399 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1400 error (g, "remove_handle failed");
1407 g->main_loop->add_handle (g->main_loop, g, g->sock,
1408 GUESTFS_HANDLE_READABLE,
1409 sock_read_event, NULL);
1410 if (g->sock_watch == -1) {
1411 error (g, "add_handle failed");
1418 /* Dispatch a call (len + header + args) to the remote daemon,
1419 * synchronously (ie. using the guest's main loop to wait until
1420 * it has been sent). Returns -1 for error, or the serial
1421 * number of the message.
1424 send_cb (guestfs_h *g, void *data)
1426 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1429 ml->main_loop_quit (ml, g);
1433 guestfs__send_sync (guestfs_h *g, int proc_nr,
1434 xdrproc_t xdrp, char *args)
1436 char buffer[GUESTFS_MESSAGE_MAX];
1437 struct guestfs_message_header hdr;
1440 int serial = g->msg_next_serial++;
1442 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1444 if (g->state != BUSY) {
1445 error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1449 /* Serialize the header. */
1450 hdr.prog = GUESTFS_PROGRAM;
1451 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1453 hdr.direction = GUESTFS_DIRECTION_CALL;
1454 hdr.serial = serial;
1455 hdr.status = GUESTFS_STATUS_OK;
1457 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1458 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1459 error (g, "xdr_guestfs_message_header failed");
1463 /* Serialize the args. If any, because some message types
1464 * have no parameters.
1467 if (!(*xdrp) (&xdr, args)) {
1468 error (g, "dispatch failed to marshal args");
1473 len = xdr_getpos (&xdr);
1476 /* Allocate the outgoing message buffer. */
1477 g->msg_out = safe_malloc (g, len + 4);
1479 g->msg_out_size = len + 4;
1482 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1483 xdr_uint32_t (&xdr, &len);
1485 memcpy (g->msg_out + 4, buffer, len);
1487 if (guestfs__switch_to_sending (g) == -1)
1491 guestfs_set_send_callback (g, send_cb, &sent);
1492 if (ml->main_loop_run (ml, g) == -1)
1495 error (g, "send failed, see earlier error messages");
1504 g->msg_out_size = 0;
1508 static int cancel = 0; /* XXX Implement file cancellation. */
1509 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1510 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1511 static int send_file_cancellation_sync (guestfs_h *g);
1512 static int send_file_complete_sync (guestfs_h *g);
1514 /* Synchronously send a file.
1518 * -2 daemon cancelled (we must read the error message)
1521 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1523 char buf[GUESTFS_MAX_CHUNK_SIZE];
1526 fd = open (filename, O_RDONLY);
1528 perrorf (g, "open: %s", filename);
1529 send_file_cancellation_sync (g);
1530 /* Daemon sees cancellation and won't reply, so caller can
1536 /* Send file in chunked encoding. */
1537 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1538 err = send_file_data_sync (g, buf, r);
1540 if (err == -2) /* daemon sent cancellation */
1541 send_file_cancellation_sync (g);
1546 if (cancel) { /* cancel from either end */
1547 send_file_cancellation_sync (g);
1552 perrorf (g, "read: %s", filename);
1553 send_file_cancellation_sync (g);
1557 /* End of file, but before we send that, we need to close
1558 * the file and check for errors.
1560 if (close (fd) == -1) {
1561 perrorf (g, "close: %s", filename);
1562 send_file_cancellation_sync (g);
1566 return send_file_complete_sync (g);
1569 /* Send a chunk of file data. */
1571 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1573 return send_file_chunk_sync (g, 0, buf, len);
1576 /* Send a cancellation message. */
1578 send_file_cancellation_sync (guestfs_h *g)
1580 return send_file_chunk_sync (g, 1, NULL, 0);
1583 /* Send a file complete chunk. */
1585 send_file_complete_sync (guestfs_h *g)
1588 return send_file_chunk_sync (g, 0, buf, 0);
1591 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1594 static int check_for_daemon_cancellation (guestfs_h *g);
1597 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len)
1599 char data[GUESTFS_MAX_CHUNK_SIZE + 48];
1602 guestfs_chunk chunk;
1604 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1606 if (g->state != BUSY) {
1607 error (g, "send_file_chunk_sync: state %d != READY", g->state);
1611 /* Did the daemon send a cancellation message? */
1612 if (check_for_daemon_cancellation (g)) {
1614 fprintf (stderr, "got daemon cancellation\n");
1618 /* Serialize the chunk. */
1619 chunk.cancel = cancel;
1620 chunk.data.data_len = len;
1621 chunk.data.data_val = (char *) buf;
1625 "library sending chunk cancel = %d, len = %zu, buf = %p\n",
1628 xdrmem_create (&xdr, data, sizeof data, XDR_ENCODE);
1629 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1630 error (g, "xdr_guestfs_chunk failed (buf = %p, len = %zu)", buf, len);
1635 datalen = xdr_getpos (&xdr);
1638 /* Allocate outgoing message buffer. */
1639 g->msg_out = safe_malloc (g, datalen + 4);
1640 g->msg_out_size = datalen + 4;
1643 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1644 xdr_uint32_t (&xdr, &datalen);
1646 memcpy (g->msg_out + 4, data, datalen);
1648 if (guestfs__switch_to_sending (g) == -1)
1652 guestfs_set_send_callback (g, send_cb, &sent);
1653 if (ml->main_loop_run (ml, g) == -1)
1656 error (g, "send file chunk failed, see earlier error messages");
1665 g->msg_out_size = 0;
1669 /* At this point we are sending FileIn file(s) to the guest, and not
1670 * expecting to read anything, so if we do read anything, it must be
1671 * a cancellation message. This checks for this case without blocking.
1674 check_for_daemon_cancellation (guestfs_h *g)
1684 FD_SET (g->sock, &rset);
1687 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1689 perrorf (g, "select");
1695 /* Read the message from the daemon. */
1696 r = xread (g->sock, buf, sizeof buf);
1698 perrorf (g, "read");
1702 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1703 xdr_uint32_t (&xdr, &flag);
1706 if (flag != GUESTFS_CANCEL_FLAG) {
1707 error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1708 flag, GUESTFS_CANCEL_FLAG);
1715 /* Synchronously receive a file. */
1717 static int receive_file_data_sync (guestfs_h *g, void **buf);
1720 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1725 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1727 perrorf (g, "open: %s", filename);
1731 /* Receive the file in chunked encoding. */
1732 while ((r = receive_file_data_sync (g, &buf)) > 0) {
1733 if (xwrite (fd, buf, r) == -1) {
1734 perrorf (g, "%s: write", filename);
1742 error (g, "%s: error in chunked encoding", filename);
1746 if (close (fd) == -1) {
1747 perrorf (g, "close: %s", filename);
1754 /* Send cancellation message to daemon, then wait until it
1755 * cancels (just throwing away data).
1759 uint32_t flag = GUESTFS_CANCEL_FLAG;
1761 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1762 xdr_uint32_t (&xdr, &flag);
1765 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1766 perrorf (g, "write to daemon socket");
1770 while ((r = receive_file_data_sync (g, &buf)) > 0)
1771 free (buf); /* just discard it */
1776 struct receive_file_ctx {
1782 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1784 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1785 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1786 guestfs_chunk chunk;
1788 ml->main_loop_quit (ml, g);
1790 memset (&chunk, 0, sizeof chunk);
1792 if (!xdr_guestfs_chunk (xdr, &chunk)) {
1793 error (g, "failed to parse file chunk");
1798 error (g, "file receive cancelled by daemon");
1802 if (chunk.data.data_len == 0) { /* end of transfer */
1807 ctx->code = chunk.data.data_len;
1808 *ctx->buf = chunk.data.data_val; /* caller frees */
1811 /* Receive a chunk of file data. */
1813 receive_file_data_sync (guestfs_h *g, void **buf)
1815 struct receive_file_ctx ctx;
1816 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1821 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
1822 (void) ml->main_loop_run (ml, g);
1823 guestfs_set_reply_callback (g, NULL, NULL);
1826 fprintf (stderr, "receive_file_data_sync: code %d\n", ctx.code);
1829 case 0: /* end of file */
1834 error (g, "failed to call receive_file_cb");
1836 default: /* received n bytes of data */
1841 /* This is the default main loop implementation, using select(2). */
1844 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1845 guestfs_handle_event_cb cb, void *data)
1847 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1849 if (fd < 0 || fd >= FD_SETSIZE) {
1850 error (g, "fd %d is out of range", fd);
1854 if ((events & ~(GUESTFS_HANDLE_READABLE |
1855 GUESTFS_HANDLE_WRITABLE |
1856 GUESTFS_HANDLE_HANGUP |
1857 GUESTFS_HANDLE_ERROR)) != 0) {
1858 error (g, "set of events (0x%x) contains unknown events", events);
1863 error (g, "set of events is empty");
1867 if (FD_ISSET (fd, &ml->rset) ||
1868 FD_ISSET (fd, &ml->wset) ||
1869 FD_ISSET (fd, &ml->xset)) {
1870 error (g, "fd %d is already registered", fd);
1875 error (g, "callback is NULL");
1879 if ((events & GUESTFS_HANDLE_READABLE))
1880 FD_SET (fd, &ml->rset);
1881 if ((events & GUESTFS_HANDLE_WRITABLE))
1882 FD_SET (fd, &ml->wset);
1883 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1884 FD_SET (fd, &ml->xset);
1886 if (fd > ml->max_fd) {
1888 ml->handle_cb_data =
1889 safe_realloc (g, ml->handle_cb_data,
1890 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1892 ml->handle_cb_data[fd].cb = cb;
1893 ml->handle_cb_data[fd].g = g;
1894 ml->handle_cb_data[fd].data = data;
1898 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1903 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1905 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1907 if (fd < 0 || fd >= FD_SETSIZE) {
1908 error (g, "fd %d is out of range", fd);
1912 if (!FD_ISSET (fd, &ml->rset) &&
1913 !FD_ISSET (fd, &ml->wset) &&
1914 !FD_ISSET (fd, &ml->xset)) {
1915 error (g, "fd %d was not registered", fd);
1919 FD_CLR (fd, &ml->rset);
1920 FD_CLR (fd, &ml->wset);
1921 FD_CLR (fd, &ml->xset);
1923 if (fd == ml->max_fd) {
1925 ml->handle_cb_data =
1926 safe_realloc (g, ml->handle_cb_data,
1927 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1936 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1937 guestfs_handle_timeout_cb cb, void *data)
1939 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1941 abort (); /* XXX not implemented yet */
1945 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1947 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1949 abort (); /* XXX not implemented yet */
1952 /* The 'g' parameter is just used for error reporting. Events
1953 * for multiple handles can be dispatched by running the main
1957 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1959 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1961 fd_set rset2, wset2, xset2;
1963 if (ml->is_running) {
1964 error (g, "select_main_loop_run: this cannot be called recursively");
1970 while (ml->is_running) {
1971 if (ml->nr_fds == 0)
1977 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1979 perrorf (g, "select");
1984 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1986 if (FD_ISSET (fd, &rset2))
1987 events |= GUESTFS_HANDLE_READABLE;
1988 if (FD_ISSET (fd, &wset2))
1989 events |= GUESTFS_HANDLE_WRITABLE;
1990 if (FD_ISSET (fd, &xset2))
1991 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1994 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1995 ml->handle_cb_data[fd].g,
1996 ml->handle_cb_data[fd].data,
2007 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2009 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2011 /* Note that legitimately ml->is_running can be zero when
2012 * this function is called.