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. */
164 guestfs_abort_cb abort_cb;
165 guestfs_error_handler_cb error_cb;
166 void * error_cb_data;
167 guestfs_send_cb send_cb;
169 guestfs_reply_cb reply_cb;
170 void * reply_cb_data;
171 guestfs_log_message_cb log_message_cb;
172 void * log_message_cb_data;
173 guestfs_subprocess_quit_cb subprocess_quit_cb;
174 void * subprocess_quit_cb_data;
175 guestfs_launch_done_cb launch_done_cb;
176 void * launch_done_cb_data;
178 /* Main loop used by this handle. */
179 guestfs_main_loop *main_loop;
181 /* Messages sent and received from the daemon. */
183 int msg_in_size, msg_in_allocated;
185 int msg_out_size, msg_out_pos;
190 static guestfs_h *handles = NULL;
191 static int atexit_handler_set = 0;
194 guestfs_create (void)
199 g = malloc (sizeof (*g));
202 memset (g, 0, sizeof (*g));
209 g->stdout_watch = -1;
213 g->error_cb = default_error_cb;
214 g->error_cb_data = NULL;
216 str = getenv ("LIBGUESTFS_DEBUG");
217 g->verbose = str != NULL && strcmp (str, "1") == 0;
219 str = getenv ("LIBGUESTFS_PATH");
220 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
222 str = getenv ("LIBGUESTFS_QEMU");
223 g->qemu = str != NULL ? str : QEMU;
225 g->main_loop = guestfs_get_default_main_loop ();
227 /* Start with large serial numbers so they are easy to spot
228 * inside the protocol.
230 g->msg_next_serial = 0x00123400;
232 /* Link the handles onto a global list. This is the one area
233 * where the library needs to be made thread-safe. (XXX)
235 /* acquire mutex (XXX) */
238 if (!atexit_handler_set) {
239 atexit (close_handles);
240 atexit_handler_set = 1;
242 /* release mutex (XXX) */
245 fprintf (stderr, "new guestfs handle %p\n", g);
251 guestfs_close (guestfs_h *g)
257 if (g->state == NO_HANDLE) {
258 /* Not safe to call 'error' here, so ... */
259 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
264 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
266 /* Try to sync if autosync flag is set. */
267 if (g->autosync && g->state == READY)
270 /* Remove any handlers that might be called back before we kill the
273 g->log_message_cb = NULL;
275 if (g->state != CONFIG)
276 guestfs_kill_subprocess (g);
279 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
288 for (i = 0; i < g->cmdline_size; ++i)
289 free (g->cmdline[i]);
293 /* Mark the handle as dead before freeing it. */
294 g->state = NO_HANDLE;
296 /* acquire mutex (XXX) */
300 for (gg = handles; gg->next != g; gg = gg->next)
304 /* release mutex (XXX) */
306 free (g->last_error);
310 /* Close all open handles (called from atexit(3)). */
314 while (handles) guestfs_close (handles);
318 guestfs_last_error (guestfs_h *g)
320 return g->last_error;
324 set_last_error (guestfs_h *g, const char *msg)
326 free (g->last_error);
327 g->last_error = strdup (msg);
331 default_error_cb (guestfs_h *g, void *data, const char *msg)
333 fprintf (stderr, "libguestfs: error: %s\n", msg);
337 guestfs_error (guestfs_h *g, const char *fs, ...)
343 vasprintf (&msg, fs, args);
346 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
347 set_last_error (g, msg);
353 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
360 vasprintf (&msg, fs, args);
365 strerror_r (err, buf, sizeof buf);
369 buf = strerror_r (err, _buf, sizeof _buf);
372 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
376 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
377 set_last_error (g, msg);
383 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
385 void *ptr = malloc (nbytes);
386 if (!ptr) g->abort_cb ();
391 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
393 void *p = realloc (ptr, nbytes);
394 if (!p) g->abort_cb ();
399 guestfs_safe_strdup (guestfs_h *g, const char *str)
401 char *s = strdup (str);
402 if (!s) g->abort_cb ();
407 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
409 void *p = malloc (size);
410 if (!p) g->abort_cb ();
411 memcpy (p, ptr, size);
416 xwrite (int fd, const void *buf, size_t len)
421 r = write (fd, buf, len);
433 xread (int fd, void *buf, size_t len)
438 r = read (fd, buf, len);
450 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
456 guestfs_get_out_of_memory_handler (guestfs_h *g)
462 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
465 g->error_cb_data = data;
468 guestfs_error_handler_cb
469 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
471 if (data_rtn) *data_rtn = g->error_cb_data;
476 guestfs_set_verbose (guestfs_h *g, int v)
483 guestfs_get_verbose (guestfs_h *g)
489 guestfs_set_autosync (guestfs_h *g, int a)
496 guestfs_get_autosync (guestfs_h *g)
502 guestfs_set_path (guestfs_h *g, const char *path)
505 g->path = GUESTFS_DEFAULT_PATH;
512 guestfs_get_path (guestfs_h *g)
518 guestfs_set_qemu (guestfs_h *g, const char *qemu)
528 guestfs_get_qemu (guestfs_h *g)
533 /* Add a string to the current command line. */
535 incr_cmdline_size (guestfs_h *g)
537 if (g->cmdline == NULL) {
538 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
540 g->cmdline = safe_malloc (g, sizeof (char *));
541 g->cmdline[0] = NULL;
545 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
549 add_cmdline (guestfs_h *g, const char *str)
551 if (g->state != CONFIG) {
552 error (g, "command line cannot be altered after qemu subprocess launched");
556 incr_cmdline_size (g);
557 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
562 guestfs_config (guestfs_h *g,
563 const char *qemu_param, const char *qemu_value)
565 if (qemu_param[0] != '-') {
566 error (g, "guestfs_config: parameter must begin with '-' character");
570 /* A bit fascist, but the user will probably break the extra
571 * parameters that we add if they try to set any of these.
573 if (strcmp (qemu_param, "-kernel") == 0 ||
574 strcmp (qemu_param, "-initrd") == 0 ||
575 strcmp (qemu_param, "-nographic") == 0 ||
576 strcmp (qemu_param, "-serial") == 0 ||
577 strcmp (qemu_param, "-vnc") == 0 ||
578 strcmp (qemu_param, "-full-screen") == 0 ||
579 strcmp (qemu_param, "-std-vga") == 0 ||
580 strcmp (qemu_param, "-vnc") == 0) {
581 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
585 if (add_cmdline (g, qemu_param) != 0) return -1;
587 if (qemu_value != NULL) {
588 if (add_cmdline (g, qemu_value) != 0) return -1;
595 guestfs_add_drive (guestfs_h *g, const char *filename)
597 int len = strlen (filename) + 64;
600 if (strchr (filename, ',') != NULL) {
601 error (g, "filename cannot contain ',' (comma) character");
605 if (access (filename, F_OK) == -1) {
606 perrorf (g, "%s", filename);
610 snprintf (buf, len, "file=%s", filename);
612 return guestfs_config (g, "-drive", buf);
616 guestfs_add_cdrom (guestfs_h *g, const char *filename)
618 if (strchr (filename, ',') != NULL) {
619 error (g, "filename cannot contain ',' (comma) character");
623 if (access (filename, F_OK) == -1) {
624 perrorf (g, "%s", filename);
628 return guestfs_config (g, "-cdrom", filename);
632 guestfs_launch (guestfs_h *g)
634 static const char *dir_template = "/tmp/libguestfsXXXXXX";
635 int r, i, len, pmore;
638 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
639 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
640 char *path, *pelem, *pend;
641 char *kernel = NULL, *initrd = NULL;
643 struct sockaddr_un addr;
647 error (g, "you must call guestfs_add_drive before guestfs_launch");
651 if (g->state != CONFIG) {
652 error (g, "qemu has already been launched");
656 /* Search g->path for the kernel and initrd. */
657 pelem = path = safe_strdup (g, g->path);
659 pend = strchrnul (pelem, ':');
660 pmore = *pend == ':';
664 /* Empty element or "." means cwd. */
665 if (len == 0 || (len == 1 && *pelem == '.')) {
668 "looking for kernel and initrd in current directory\n");
669 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
670 kernel = safe_strdup (g, kernel_name);
671 initrd = safe_strdup (g, initrd_name);
675 /* Look at <path>/kernel etc. */
677 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
678 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
679 sprintf (kernel, "%s/%s", pelem, kernel_name);
680 sprintf (initrd, "%s/%s", pelem, initrd_name);
683 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
685 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
689 kernel = initrd = NULL;
697 if (kernel == NULL || initrd == NULL) {
698 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
699 kernel_name, initrd_name, g->path);
703 /* Make the temporary directory containing the socket. */
705 g->tmpdir = safe_strdup (g, dir_template);
706 if (mkdtemp (g->tmpdir) == NULL) {
707 perrorf (g, "%s: cannot create temporary directory", dir_template);
712 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
715 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
730 if (r == 0) { /* Child (qemu). */
734 /* Set up the full command line. Do this in the subprocess so we
735 * don't need to worry about cleaning up.
737 g->cmdline[0] = (char *) g->qemu;
739 /* Construct the -net channel parameter for qemu. */
740 snprintf (vmchannel, sizeof vmchannel,
741 "channel,%d:unix:%s,server,nowait",
742 VMCHANNEL_PORT, unixsock);
744 /* Linux kernel command line. */
745 snprintf (append, sizeof append,
746 "console=ttyS0 guestfs=%s:%d%s",
747 VMCHANNEL_ADDR, VMCHANNEL_PORT,
748 g->verbose ? " guestfs_verbose=1" : "");
750 add_cmdline (g, "-m");
751 add_cmdline (g, "384"); /* XXX Choose best size. */
753 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
755 add_cmdline (g, "-kernel");
756 add_cmdline (g, (char *) kernel);
757 add_cmdline (g, "-initrd");
758 add_cmdline (g, (char *) initrd);
759 add_cmdline (g, "-append");
760 add_cmdline (g, append);
761 add_cmdline (g, "-nographic");
762 add_cmdline (g, "-serial");
763 add_cmdline (g, "stdio");
764 add_cmdline (g, "-net");
765 add_cmdline (g, vmchannel);
766 add_cmdline (g, "-net");
767 add_cmdline (g, "user,vlan=0");
768 add_cmdline (g, "-net");
769 add_cmdline (g, "nic,model=rtl8139,vlan=0");
770 incr_cmdline_size (g);
771 g->cmdline[g->cmdline_size-1] = NULL;
774 fprintf (stderr, "%s", g->qemu);
775 for (i = 0; g->cmdline[i]; ++i)
776 fprintf (stderr, " %s", g->cmdline[i]);
777 fprintf (stderr, "\n");
780 /* Set up stdin, stdout. */
791 /* Set up a new process group, so we can signal this process
792 * and all subprocesses (eg. if qemu is really a shell script).
797 execv (g->qemu, g->cmdline); /* Run qemu. */
802 /* Parent (library). */
805 /* Start the clock ... */
808 /* Close the other ends of the pipe. */
812 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
813 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
814 perrorf (g, "fcntl");
818 g->fd[0] = wfd[1]; /* stdin of child */
819 g->fd[1] = rfd[0]; /* stdout of child */
821 /* Open the Unix socket. The vmchannel implementation that got
822 * merged with qemu sucks in a number of ways. Both ends do
823 * connect(2), which means that no one knows what, if anything, is
824 * connected to the other end, or if it becomes disconnected. Even
825 * worse, we have to wait some indeterminate time for qemu to create
826 * the socket and connect to it (which happens very early in qemu's
827 * start-up), so any code that uses vmchannel is inherently racy.
828 * Hence this silly loop.
830 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
832 perrorf (g, "socket");
836 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
837 perrorf (g, "fcntl");
841 addr.sun_family = AF_UNIX;
842 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
843 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
847 /* Always sleep at least once to give qemu a small chance to start up. */
850 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
851 if ((r == -1 && errno == EINPROGRESS) || r == 0)
855 perrorf (g, "connect");
859 error (g, "failed to connect to vmchannel socket");
863 /* Watch the file descriptors. */
866 g->msg_in_size = g->msg_in_allocated = 0;
874 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
875 GUESTFS_HANDLE_READABLE,
877 if (g->stdout_watch == -1) {
878 error (g, "could not watch qemu stdout");
882 if (guestfs__switch_to_receiving (g) == -1)
885 g->state = LAUNCHING;
889 if (g->stdout_watch >= 0)
890 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
891 if (g->sock_watch >= 0)
892 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
901 waitpid (g->pid, NULL, 0);
907 g->stdout_watch = -1;
917 finish_wait_ready (guestfs_h *g, void *vp)
920 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
923 g->main_loop->main_loop_quit (g->main_loop, g);
927 guestfs_wait_ready (guestfs_h *g)
931 if (g->state == READY) return 0;
933 if (g->state == BUSY) {
934 error (g, "qemu has finished launching already");
938 if (g->state != LAUNCHING) {
939 error (g, "qemu has not been launched yet");
943 g->launch_done_cb = finish_wait_ready;
944 g->launch_done_cb_data = &finished;
945 r = g->main_loop->main_loop_run (g->main_loop, g);
946 g->launch_done_cb = NULL;
947 g->launch_done_cb_data = NULL;
949 if (r == -1) return -1;
952 error (g, "guestfs_wait_ready failed, see earlier error messages");
956 /* This is possible in some really strange situations, such as
957 * guestfsd starts up OK but then qemu immediately exits. Check for
958 * it because the caller is probably expecting to be able to send
959 * commands after this function returns.
961 if (g->state != READY) {
962 error (g, "qemu launched and contacted daemon, but state != READY");
970 guestfs_kill_subprocess (guestfs_h *g)
972 if (g->state == CONFIG) {
973 error (g, "no subprocess to kill");
978 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
980 kill (g->pid, SIGTERM);
985 /* Access current state. */
987 guestfs_is_config (guestfs_h *g)
989 return g->state == CONFIG;
993 guestfs_is_launching (guestfs_h *g)
995 return g->state == LAUNCHING;
999 guestfs_is_ready (guestfs_h *g)
1001 return g->state == READY;
1005 guestfs_is_busy (guestfs_h *g)
1007 return g->state == BUSY;
1011 guestfs_get_state (guestfs_h *g)
1017 guestfs_set_ready (guestfs_h *g)
1019 if (g->state != BUSY) {
1020 error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1028 guestfs_set_busy (guestfs_h *g)
1030 if (g->state != READY) {
1031 error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1038 /* Structure-freeing functions. These rely on the fact that the
1039 * structure format is identical to the XDR format. See note in
1043 guestfs_free_int_bool (struct guestfs_int_bool *x)
1049 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1051 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1056 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1058 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1063 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1065 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1069 /* This function is called whenever qemu prints something on stdout.
1070 * Qemu's stdout is also connected to the guest's serial console, so
1071 * we see kernel messages here too.
1074 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1075 int watch, int fd, int events)
1083 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1084 g, g->state, fd, events);
1087 if (g->fd[1] != fd) {
1088 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1092 n = read (fd, buf, sizeof buf);
1094 /* Hopefully this indicates the qemu child process has died. */
1096 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1097 /*kill (g->pid, SIGTERM);*/
1098 waitpid (g->pid, NULL, 0);
1099 if (g->stdout_watch >= 0)
1100 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1101 if (g->sock_watch >= 0)
1102 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1111 g->stdout_watch = -1;
1114 if (g->subprocess_quit_cb)
1115 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1120 if (errno != EAGAIN)
1121 perrorf (g, "read");
1125 /* In verbose mode, copy all log messages to stderr. */
1129 /* It's an actual log message, send it upwards if anyone is listening. */
1130 if (g->log_message_cb)
1131 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1134 /* The function is called whenever we can read something on the
1135 * guestfsd (daemon inside the guest) communication socket.
1138 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1139 int watch, int fd, int events)
1147 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1148 g, g->state, fd, events);
1150 if (g->sock != fd) {
1151 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1155 if (g->msg_in_size <= g->msg_in_allocated) {
1156 g->msg_in_allocated += 4096;
1157 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1159 n = read (g->sock, g->msg_in + g->msg_in_size,
1160 g->msg_in_allocated - g->msg_in_size);
1162 /* Disconnected? Ignore it because stdout_watch will get called
1163 * and will do the cleanup.
1168 if (errno != EAGAIN)
1169 perrorf (g, "read");
1173 g->msg_in_size += n;
1175 /* Have we got enough of a message to be able to process it yet? */
1177 if (g->msg_in_size < 4) return;
1179 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1180 if (!xdr_uint32_t (&xdr, &len)) {
1181 error (g, "can't decode length word");
1185 /* Length is normally the length of the message, but when guestfsd
1186 * starts up it sends a "magic" value (longer than any possible
1187 * message). Check for this.
1189 if (len == GUESTFS_LAUNCH_FLAG) {
1190 if (g->state != LAUNCHING)
1191 error (g, "received magic signature from guestfsd, but in state %d",
1193 else if (g->msg_in_size != 4)
1194 error (g, "received magic signature from guestfsd, but msg size is %d",
1198 if (g->launch_done_cb)
1199 g->launch_done_cb (g, g->launch_done_cb_data);
1205 /* This can happen if a cancellation happens right at the end
1206 * of us sending a FileIn parameter to the daemon. Discard. The
1207 * daemon should send us an error message next.
1209 if (len == GUESTFS_CANCEL_FLAG) {
1210 g->msg_in_size -= 4;
1211 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1215 /* If this happens, it's pretty bad and we've probably lost
1218 if (len > GUESTFS_MESSAGE_MAX) {
1219 error (g, "message length (%u) > maximum possible size (%d)",
1220 len, GUESTFS_MESSAGE_MAX);
1224 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1226 /* Got the full message, begin processing it. */
1230 for (i = 0; i < g->msg_in_size; i += 16) {
1231 printf ("%04x: ", i);
1232 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1233 printf ("%02x ", (unsigned char) g->msg_in[j]);
1234 for (; j < i+16; ++j)
1237 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1238 if (isprint (g->msg_in[j]))
1239 printf ("%c", g->msg_in[j]);
1242 for (; j < i+16; ++j)
1248 /* Not in the expected state. */
1249 if (g->state != BUSY)
1250 error (g, "state %d != BUSY", g->state);
1252 /* Push the message up to the higher layer. */
1254 g->reply_cb (g, g->reply_cb_data, &xdr);
1256 g->msg_in_size -= len + 4;
1257 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1258 if (g->msg_in_size > 0) goto again;
1261 /* Free the message buffer if it's grown excessively large. */
1262 if (g->msg_in_allocated > 65536) {
1265 g->msg_in_size = g->msg_in_allocated = 0;
1272 /* The function is called whenever we can write something on the
1273 * guestfsd (daemon inside the guest) communication socket.
1276 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1277 int watch, int fd, int events)
1283 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1284 g, g->state, fd, events);
1286 if (g->sock != fd) {
1287 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1291 if (g->state != BUSY) {
1292 error (g, "sock_write_event: state %d != BUSY", g->state);
1297 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1298 g->msg_out_size - g->msg_out_pos);
1300 n = write (g->sock, g->msg_out + g->msg_out_pos,
1301 g->msg_out_size - g->msg_out_pos);
1303 if (errno != EAGAIN)
1304 perrorf (g, "write");
1309 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1311 g->msg_out_pos += n;
1313 /* More to write? */
1314 if (g->msg_out_pos < g->msg_out_size)
1318 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1322 g->msg_out_pos = g->msg_out_size = 0;
1324 /* Done writing, call the higher layer. */
1326 g->send_cb (g, g->send_cb_data);
1330 guestfs_set_send_callback (guestfs_h *g,
1331 guestfs_send_cb cb, void *opaque)
1334 g->send_cb_data = opaque;
1338 guestfs_set_reply_callback (guestfs_h *g,
1339 guestfs_reply_cb cb, void *opaque)
1342 g->reply_cb_data = opaque;
1346 guestfs_set_log_message_callback (guestfs_h *g,
1347 guestfs_log_message_cb cb, void *opaque)
1349 g->log_message_cb = cb;
1350 g->log_message_cb_data = opaque;
1354 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1355 guestfs_subprocess_quit_cb cb, void *opaque)
1357 g->subprocess_quit_cb = cb;
1358 g->subprocess_quit_cb_data = opaque;
1362 guestfs_set_launch_done_callback (guestfs_h *g,
1363 guestfs_launch_done_cb cb, void *opaque)
1365 g->launch_done_cb = cb;
1366 g->launch_done_cb_data = opaque;
1369 /* Access to the handle's main loop and the default main loop. */
1371 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1373 g->main_loop = main_loop;
1377 guestfs_get_main_loop (guestfs_h *g)
1379 return g->main_loop;
1383 guestfs_get_default_main_loop (void)
1385 return (guestfs_main_loop *) &default_main_loop;
1388 /* Change the daemon socket handler so that we are now writing.
1389 * This sets the handle to sock_write_event.
1392 guestfs__switch_to_sending (guestfs_h *g)
1394 if (g->sock_watch >= 0) {
1395 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1396 error (g, "remove_handle failed");
1403 g->main_loop->add_handle (g->main_loop, g, g->sock,
1404 GUESTFS_HANDLE_WRITABLE,
1405 sock_write_event, NULL);
1406 if (g->sock_watch == -1) {
1407 error (g, "add_handle failed");
1415 guestfs__switch_to_receiving (guestfs_h *g)
1417 if (g->sock_watch >= 0) {
1418 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1419 error (g, "remove_handle failed");
1426 g->main_loop->add_handle (g->main_loop, g, g->sock,
1427 GUESTFS_HANDLE_READABLE,
1428 sock_read_event, NULL);
1429 if (g->sock_watch == -1) {
1430 error (g, "add_handle failed");
1437 /* Dispatch a call (len + header + args) to the remote daemon,
1438 * synchronously (ie. using the guest's main loop to wait until
1439 * it has been sent). Returns -1 for error, or the serial
1440 * number of the message.
1443 send_cb (guestfs_h *g, void *data)
1445 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1448 ml->main_loop_quit (ml, g);
1452 guestfs__send_sync (guestfs_h *g, int proc_nr,
1453 xdrproc_t xdrp, char *args)
1455 char buffer[GUESTFS_MESSAGE_MAX];
1456 struct guestfs_message_header hdr;
1459 int serial = g->msg_next_serial++;
1461 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1463 if (g->state != BUSY) {
1464 error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1468 /* Serialize the header. */
1469 hdr.prog = GUESTFS_PROGRAM;
1470 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1472 hdr.direction = GUESTFS_DIRECTION_CALL;
1473 hdr.serial = serial;
1474 hdr.status = GUESTFS_STATUS_OK;
1476 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1477 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1478 error (g, "xdr_guestfs_message_header failed");
1482 /* Serialize the args. If any, because some message types
1483 * have no parameters.
1486 if (!(*xdrp) (&xdr, args)) {
1487 error (g, "dispatch failed to marshal args");
1492 len = xdr_getpos (&xdr);
1495 /* Allocate the outgoing message buffer. */
1496 g->msg_out = safe_malloc (g, len + 4);
1498 g->msg_out_size = len + 4;
1501 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1502 xdr_uint32_t (&xdr, &len);
1504 memcpy (g->msg_out + 4, buffer, len);
1506 if (guestfs__switch_to_sending (g) == -1)
1510 guestfs_set_send_callback (g, send_cb, &sent);
1511 if (ml->main_loop_run (ml, g) == -1)
1514 error (g, "send failed, see earlier error messages");
1523 g->msg_out_size = 0;
1527 static int cancel = 0; /* XXX Implement file cancellation. */
1528 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1529 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1530 static int send_file_cancellation_sync (guestfs_h *g);
1531 static int send_file_complete_sync (guestfs_h *g);
1533 /* Synchronously send a file.
1537 * -2 daemon cancelled (we must read the error message)
1540 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1542 char buf[GUESTFS_MAX_CHUNK_SIZE];
1545 fd = open (filename, O_RDONLY);
1547 perrorf (g, "open: %s", filename);
1548 send_file_cancellation_sync (g);
1549 /* Daemon sees cancellation and won't reply, so caller can
1555 /* Send file in chunked encoding. */
1556 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1557 err = send_file_data_sync (g, buf, r);
1559 if (err == -2) /* daemon sent cancellation */
1560 send_file_cancellation_sync (g);
1565 if (cancel) { /* cancel from either end */
1566 send_file_cancellation_sync (g);
1571 perrorf (g, "read: %s", filename);
1572 send_file_cancellation_sync (g);
1576 /* End of file, but before we send that, we need to close
1577 * the file and check for errors.
1579 if (close (fd) == -1) {
1580 perrorf (g, "close: %s", filename);
1581 send_file_cancellation_sync (g);
1585 return send_file_complete_sync (g);
1588 /* Send a chunk of file data. */
1590 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1592 return send_file_chunk_sync (g, 0, buf, len);
1595 /* Send a cancellation message. */
1597 send_file_cancellation_sync (guestfs_h *g)
1599 return send_file_chunk_sync (g, 1, NULL, 0);
1602 /* Send a file complete chunk. */
1604 send_file_complete_sync (guestfs_h *g)
1607 return send_file_chunk_sync (g, 0, buf, 0);
1610 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1613 static int check_for_daemon_cancellation (guestfs_h *g);
1616 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len)
1618 char data[GUESTFS_MAX_CHUNK_SIZE + 48];
1621 guestfs_chunk chunk;
1623 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1625 if (g->state != BUSY) {
1626 error (g, "send_file_chunk_sync: state %d != READY", g->state);
1630 /* Did the daemon send a cancellation message? */
1631 if (check_for_daemon_cancellation (g)) {
1633 fprintf (stderr, "got daemon cancellation\n");
1637 /* Serialize the chunk. */
1638 chunk.cancel = cancel;
1639 chunk.data.data_len = len;
1640 chunk.data.data_val = (char *) buf;
1644 "library sending chunk cancel = %d, len = %zu, buf = %p\n",
1647 xdrmem_create (&xdr, data, sizeof data, XDR_ENCODE);
1648 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1649 error (g, "xdr_guestfs_chunk failed (buf = %p, len = %zu)", buf, len);
1654 datalen = xdr_getpos (&xdr);
1657 /* Allocate outgoing message buffer. */
1658 g->msg_out = safe_malloc (g, datalen + 4);
1659 g->msg_out_size = datalen + 4;
1662 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1663 xdr_uint32_t (&xdr, &datalen);
1665 memcpy (g->msg_out + 4, data, datalen);
1667 if (guestfs__switch_to_sending (g) == -1)
1671 guestfs_set_send_callback (g, send_cb, &sent);
1672 if (ml->main_loop_run (ml, g) == -1)
1675 error (g, "send file chunk failed, see earlier error messages");
1684 g->msg_out_size = 0;
1688 /* At this point we are sending FileIn file(s) to the guest, and not
1689 * expecting to read anything, so if we do read anything, it must be
1690 * a cancellation message. This checks for this case without blocking.
1693 check_for_daemon_cancellation (guestfs_h *g)
1703 FD_SET (g->sock, &rset);
1706 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1708 perrorf (g, "select");
1714 /* Read the message from the daemon. */
1715 r = xread (g->sock, buf, sizeof buf);
1717 perrorf (g, "read");
1721 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1722 xdr_uint32_t (&xdr, &flag);
1725 if (flag != GUESTFS_CANCEL_FLAG) {
1726 error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1727 flag, GUESTFS_CANCEL_FLAG);
1734 /* Synchronously receive a file. */
1736 static int receive_file_data_sync (guestfs_h *g, void **buf);
1739 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1744 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1746 perrorf (g, "open: %s", filename);
1750 /* Receive the file in chunked encoding. */
1751 while ((r = receive_file_data_sync (g, &buf)) > 0) {
1752 if (xwrite (fd, buf, r) == -1) {
1753 perrorf (g, "%s: write", filename);
1761 error (g, "%s: error in chunked encoding", filename);
1765 if (close (fd) == -1) {
1766 perrorf (g, "close: %s", filename);
1773 /* Send cancellation message to daemon, then wait until it
1774 * cancels (just throwing away data).
1778 uint32_t flag = GUESTFS_CANCEL_FLAG;
1780 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1781 xdr_uint32_t (&xdr, &flag);
1784 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1785 perrorf (g, "write to daemon socket");
1789 while ((r = receive_file_data_sync (g, &buf)) > 0)
1790 free (buf); /* just discard it */
1795 struct receive_file_ctx {
1801 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1803 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1804 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1805 guestfs_chunk chunk;
1807 ml->main_loop_quit (ml, g);
1809 memset (&chunk, 0, sizeof chunk);
1811 if (!xdr_guestfs_chunk (xdr, &chunk)) {
1812 error (g, "failed to parse file chunk");
1817 error (g, "file receive cancelled by daemon");
1821 if (chunk.data.data_len == 0) { /* end of transfer */
1826 ctx->code = chunk.data.data_len;
1827 *ctx->buf = chunk.data.data_val; /* caller frees */
1830 /* Receive a chunk of file data. */
1832 receive_file_data_sync (guestfs_h *g, void **buf)
1834 struct receive_file_ctx ctx;
1835 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1840 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
1841 (void) ml->main_loop_run (ml, g);
1842 guestfs_set_reply_callback (g, NULL, NULL);
1845 fprintf (stderr, "receive_file_data_sync: code %d\n", ctx.code);
1848 case 0: /* end of file */
1853 error (g, "failed to call receive_file_cb");
1855 default: /* received n bytes of data */
1860 /* This is the default main loop implementation, using select(2). */
1863 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1864 guestfs_handle_event_cb cb, void *data)
1866 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1868 if (fd < 0 || fd >= FD_SETSIZE) {
1869 error (g, "fd %d is out of range", fd);
1873 if ((events & ~(GUESTFS_HANDLE_READABLE |
1874 GUESTFS_HANDLE_WRITABLE |
1875 GUESTFS_HANDLE_HANGUP |
1876 GUESTFS_HANDLE_ERROR)) != 0) {
1877 error (g, "set of events (0x%x) contains unknown events", events);
1882 error (g, "set of events is empty");
1886 if (FD_ISSET (fd, &ml->rset) ||
1887 FD_ISSET (fd, &ml->wset) ||
1888 FD_ISSET (fd, &ml->xset)) {
1889 error (g, "fd %d is already registered", fd);
1894 error (g, "callback is NULL");
1898 if ((events & GUESTFS_HANDLE_READABLE))
1899 FD_SET (fd, &ml->rset);
1900 if ((events & GUESTFS_HANDLE_WRITABLE))
1901 FD_SET (fd, &ml->wset);
1902 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1903 FD_SET (fd, &ml->xset);
1905 if (fd > ml->max_fd) {
1907 ml->handle_cb_data =
1908 safe_realloc (g, ml->handle_cb_data,
1909 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1911 ml->handle_cb_data[fd].cb = cb;
1912 ml->handle_cb_data[fd].g = g;
1913 ml->handle_cb_data[fd].data = data;
1917 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1922 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1924 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1926 if (fd < 0 || fd >= FD_SETSIZE) {
1927 error (g, "fd %d is out of range", fd);
1931 if (!FD_ISSET (fd, &ml->rset) &&
1932 !FD_ISSET (fd, &ml->wset) &&
1933 !FD_ISSET (fd, &ml->xset)) {
1934 error (g, "fd %d was not registered", fd);
1938 FD_CLR (fd, &ml->rset);
1939 FD_CLR (fd, &ml->wset);
1940 FD_CLR (fd, &ml->xset);
1942 if (fd == ml->max_fd) {
1944 ml->handle_cb_data =
1945 safe_realloc (g, ml->handle_cb_data,
1946 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1955 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1956 guestfs_handle_timeout_cb cb, void *data)
1958 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1960 abort (); /* XXX not implemented yet */
1964 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1966 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1968 abort (); /* XXX not implemented yet */
1971 /* The 'g' parameter is just used for error reporting. Events
1972 * for multiple handles can be dispatched by running the main
1976 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1978 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1980 fd_set rset2, wset2, xset2;
1982 if (ml->is_running) {
1983 error (g, "select_main_loop_run: this cannot be called recursively");
1989 while (ml->is_running) {
1990 if (ml->nr_fds == 0)
1996 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1998 perrorf (g, "select");
2003 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2005 if (FD_ISSET (fd, &rset2))
2006 events |= GUESTFS_HANDLE_READABLE;
2007 if (FD_ISSET (fd, &wset2))
2008 events |= GUESTFS_HANDLE_WRITABLE;
2009 if (FD_ISSET (fd, &xset2))
2010 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2013 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2014 ml->handle_cb_data[fd].g,
2015 ml->handle_cb_data[fd].data,
2026 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2028 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2030 /* Note that legitimately ml->is_running can be zero when
2031 * this function is called.