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 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
734 add_cmdline (g, "-kernel");
735 add_cmdline (g, (char *) kernel);
736 add_cmdline (g, "-initrd");
737 add_cmdline (g, (char *) initrd);
738 add_cmdline (g, "-append");
739 add_cmdline (g, append);
740 add_cmdline (g, "-nographic");
741 add_cmdline (g, "-serial");
742 add_cmdline (g, "stdio");
743 add_cmdline (g, "-net");
744 add_cmdline (g, vmchannel);
745 add_cmdline (g, "-net");
746 add_cmdline (g, "user,vlan=0");
747 add_cmdline (g, "-net");
748 add_cmdline (g, "nic,vlan=0");
749 incr_cmdline_size (g);
750 g->cmdline[g->cmdline_size-1] = NULL;
753 fprintf (stderr, "%s", QEMU);
754 for (i = 0; g->cmdline[i]; ++i)
755 fprintf (stderr, " %s", g->cmdline[i]);
756 fprintf (stderr, "\n");
759 /* Set up stdin, stdout. */
770 /* Set up a new process group, so we can signal this process
771 * and all subprocesses (eg. if qemu is really a shell script).
776 execv (QEMU, g->cmdline); /* Run qemu. */
781 /* Parent (library). */
784 /* Start the clock ... */
787 /* Close the other ends of the pipe. */
791 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
792 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
793 perrorf (g, "fcntl");
797 g->fd[0] = wfd[1]; /* stdin of child */
798 g->fd[1] = rfd[0]; /* stdout of child */
800 /* Open the Unix socket. The vmchannel implementation that got
801 * merged with qemu sucks in a number of ways. Both ends do
802 * connect(2), which means that no one knows what, if anything, is
803 * connected to the other end, or if it becomes disconnected. Even
804 * worse, we have to wait some indeterminate time for qemu to create
805 * the socket and connect to it (which happens very early in qemu's
806 * start-up), so any code that uses vmchannel is inherently racy.
807 * Hence this silly loop.
809 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
811 perrorf (g, "socket");
815 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
816 perrorf (g, "fcntl");
820 addr.sun_family = AF_UNIX;
821 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
822 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
826 /* Always sleep at least once to give qemu a small chance to start up. */
829 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
830 if ((r == -1 && errno == EINPROGRESS) || r == 0)
834 perrorf (g, "connect");
838 error (g, "failed to connect to vmchannel socket");
842 /* Watch the file descriptors. */
845 g->msg_in_size = g->msg_in_allocated = 0;
853 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
854 GUESTFS_HANDLE_READABLE,
856 if (g->stdout_watch == -1) {
857 error (g, "could not watch qemu stdout");
861 if (guestfs__switch_to_receiving (g) == -1)
864 g->state = LAUNCHING;
868 if (g->stdout_watch >= 0)
869 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
870 if (g->sock_watch >= 0)
871 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
880 waitpid (g->pid, NULL, 0);
886 g->stdout_watch = -1;
896 finish_wait_ready (guestfs_h *g, void *vp)
899 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
902 g->main_loop->main_loop_quit (g->main_loop, g);
906 guestfs_wait_ready (guestfs_h *g)
910 if (g->state == READY) return 0;
912 if (g->state == BUSY) {
913 error (g, "qemu has finished launching already");
917 if (g->state != LAUNCHING) {
918 error (g, "qemu has not been launched yet");
922 g->launch_done_cb = finish_wait_ready;
923 g->launch_done_cb_data = &finished;
924 r = g->main_loop->main_loop_run (g->main_loop, g);
925 g->launch_done_cb = NULL;
926 g->launch_done_cb_data = NULL;
928 if (r == -1) return -1;
931 error (g, "guestfs_wait_ready failed, see earlier error messages");
935 /* This is possible in some really strange situations, such as
936 * guestfsd starts up OK but then qemu immediately exits. Check for
937 * it because the caller is probably expecting to be able to send
938 * commands after this function returns.
940 if (g->state != READY) {
941 error (g, "qemu launched and contacted daemon, but state != READY");
949 guestfs_kill_subprocess (guestfs_h *g)
951 if (g->state == CONFIG) {
952 error (g, "no subprocess to kill");
957 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
959 kill (g->pid, SIGTERM);
964 /* Access current state. */
966 guestfs_is_config (guestfs_h *g)
968 return g->state == CONFIG;
972 guestfs_is_launching (guestfs_h *g)
974 return g->state == LAUNCHING;
978 guestfs_is_ready (guestfs_h *g)
980 return g->state == READY;
984 guestfs_is_busy (guestfs_h *g)
986 return g->state == BUSY;
990 guestfs_get_state (guestfs_h *g)
996 guestfs_set_ready (guestfs_h *g)
998 if (g->state != BUSY) {
999 error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1007 guestfs_set_busy (guestfs_h *g)
1009 if (g->state != READY) {
1010 error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1017 /* Structure-freeing functions. These rely on the fact that the
1018 * structure format is identical to the XDR format. See note in
1022 guestfs_free_int_bool (struct guestfs_int_bool *x)
1028 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1030 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1035 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1037 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1042 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1044 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1048 /* This function is called whenever qemu prints something on stdout.
1049 * Qemu's stdout is also connected to the guest's serial console, so
1050 * we see kernel messages here too.
1053 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1054 int watch, int fd, int events)
1062 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1063 g, g->state, fd, events);
1066 if (g->fd[1] != fd) {
1067 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1071 n = read (fd, buf, sizeof buf);
1073 /* Hopefully this indicates the qemu child process has died. */
1075 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1076 /*kill (g->pid, SIGTERM);*/
1077 waitpid (g->pid, NULL, 0);
1078 if (g->stdout_watch >= 0)
1079 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1080 if (g->sock_watch >= 0)
1081 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1090 g->stdout_watch = -1;
1093 if (g->subprocess_quit_cb)
1094 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1099 if (errno != EAGAIN)
1100 perrorf (g, "read");
1104 /* In verbose mode, copy all log messages to stderr. */
1108 /* It's an actual log message, send it upwards if anyone is listening. */
1109 if (g->log_message_cb)
1110 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1113 /* The function is called whenever we can read something on the
1114 * guestfsd (daemon inside the guest) communication socket.
1117 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1118 int watch, int fd, int events)
1126 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1127 g, g->state, fd, events);
1129 if (g->sock != fd) {
1130 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1134 if (g->msg_in_size <= g->msg_in_allocated) {
1135 g->msg_in_allocated += 4096;
1136 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1138 n = read (g->sock, g->msg_in + g->msg_in_size,
1139 g->msg_in_allocated - g->msg_in_size);
1141 /* Disconnected? Ignore it because stdout_watch will get called
1142 * and will do the cleanup.
1147 if (errno != EAGAIN)
1148 perrorf (g, "read");
1152 g->msg_in_size += n;
1154 /* Have we got enough of a message to be able to process it yet? */
1156 if (g->msg_in_size < 4) return;
1158 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1159 if (!xdr_uint32_t (&xdr, &len)) {
1160 error (g, "can't decode length word");
1164 /* Length is normally the length of the message, but when guestfsd
1165 * starts up it sends a "magic" value (longer than any possible
1166 * message). Check for this.
1168 if (len == GUESTFS_LAUNCH_FLAG) {
1169 if (g->state != LAUNCHING)
1170 error (g, "received magic signature from guestfsd, but in state %d",
1172 else if (g->msg_in_size != 4)
1173 error (g, "received magic signature from guestfsd, but msg size is %d",
1177 if (g->launch_done_cb)
1178 g->launch_done_cb (g, g->launch_done_cb_data);
1184 /* This can happen if a cancellation happens right at the end
1185 * of us sending a FileIn parameter to the daemon. Discard. The
1186 * daemon should send us an error message next.
1188 if (len == GUESTFS_CANCEL_FLAG) {
1189 g->msg_in_size -= 4;
1190 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1194 /* If this happens, it's pretty bad and we've probably lost
1197 if (len > GUESTFS_MESSAGE_MAX) {
1198 error (g, "message length (%u) > maximum possible size (%d)",
1199 len, GUESTFS_MESSAGE_MAX);
1203 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1205 /* Got the full message, begin processing it. */
1209 for (i = 0; i < g->msg_in_size; i += 16) {
1210 printf ("%04x: ", i);
1211 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1212 printf ("%02x ", (unsigned char) g->msg_in[j]);
1213 for (; j < i+16; ++j)
1216 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1217 if (isprint (g->msg_in[j]))
1218 printf ("%c", g->msg_in[j]);
1221 for (; j < i+16; ++j)
1227 /* Not in the expected state. */
1228 if (g->state != BUSY)
1229 error (g, "state %d != BUSY", g->state);
1231 /* Push the message up to the higher layer. */
1233 g->reply_cb (g, g->reply_cb_data, &xdr);
1235 g->msg_in_size -= len + 4;
1236 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1237 if (g->msg_in_size > 0) goto again;
1240 /* Free the message buffer if it's grown excessively large. */
1241 if (g->msg_in_allocated > 65536) {
1244 g->msg_in_size = g->msg_in_allocated = 0;
1251 /* The function is called whenever we can write something on the
1252 * guestfsd (daemon inside the guest) communication socket.
1255 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1256 int watch, int fd, int events)
1262 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1263 g, g->state, fd, events);
1265 if (g->sock != fd) {
1266 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1270 if (g->state != BUSY) {
1271 error (g, "sock_write_event: state %d != BUSY", g->state);
1276 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1277 g->msg_out_size - g->msg_out_pos);
1279 n = write (g->sock, g->msg_out + g->msg_out_pos,
1280 g->msg_out_size - g->msg_out_pos);
1282 if (errno != EAGAIN)
1283 perrorf (g, "write");
1288 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1290 g->msg_out_pos += n;
1292 /* More to write? */
1293 if (g->msg_out_pos < g->msg_out_size)
1297 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1301 g->msg_out_pos = g->msg_out_size = 0;
1303 /* Done writing, call the higher layer. */
1305 g->send_cb (g, g->send_cb_data);
1309 guestfs_set_send_callback (guestfs_h *g,
1310 guestfs_send_cb cb, void *opaque)
1313 g->send_cb_data = opaque;
1317 guestfs_set_reply_callback (guestfs_h *g,
1318 guestfs_reply_cb cb, void *opaque)
1321 g->reply_cb_data = opaque;
1325 guestfs_set_log_message_callback (guestfs_h *g,
1326 guestfs_log_message_cb cb, void *opaque)
1328 g->log_message_cb = cb;
1329 g->log_message_cb_data = opaque;
1333 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1334 guestfs_subprocess_quit_cb cb, void *opaque)
1336 g->subprocess_quit_cb = cb;
1337 g->subprocess_quit_cb_data = opaque;
1341 guestfs_set_launch_done_callback (guestfs_h *g,
1342 guestfs_launch_done_cb cb, void *opaque)
1344 g->launch_done_cb = cb;
1345 g->launch_done_cb_data = opaque;
1348 /* Access to the handle's main loop and the default main loop. */
1350 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1352 g->main_loop = main_loop;
1356 guestfs_get_main_loop (guestfs_h *g)
1358 return g->main_loop;
1362 guestfs_get_default_main_loop (void)
1364 return (guestfs_main_loop *) &default_main_loop;
1367 /* Change the daemon socket handler so that we are now writing.
1368 * This sets the handle to sock_write_event.
1371 guestfs__switch_to_sending (guestfs_h *g)
1373 if (g->sock_watch >= 0) {
1374 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1375 error (g, "remove_handle failed");
1382 g->main_loop->add_handle (g->main_loop, g, g->sock,
1383 GUESTFS_HANDLE_WRITABLE,
1384 sock_write_event, NULL);
1385 if (g->sock_watch == -1) {
1386 error (g, "add_handle failed");
1394 guestfs__switch_to_receiving (guestfs_h *g)
1396 if (g->sock_watch >= 0) {
1397 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1398 error (g, "remove_handle failed");
1405 g->main_loop->add_handle (g->main_loop, g, g->sock,
1406 GUESTFS_HANDLE_READABLE,
1407 sock_read_event, NULL);
1408 if (g->sock_watch == -1) {
1409 error (g, "add_handle failed");
1416 /* Dispatch a call (len + header + args) to the remote daemon,
1417 * synchronously (ie. using the guest's main loop to wait until
1418 * it has been sent). Returns -1 for error, or the serial
1419 * number of the message.
1422 send_cb (guestfs_h *g, void *data)
1424 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1427 ml->main_loop_quit (ml, g);
1431 guestfs__send_sync (guestfs_h *g, int proc_nr,
1432 xdrproc_t xdrp, char *args)
1434 char buffer[GUESTFS_MESSAGE_MAX];
1435 struct guestfs_message_header hdr;
1438 int serial = g->msg_next_serial++;
1440 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1442 if (g->state != BUSY) {
1443 error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1447 /* Serialize the header. */
1448 hdr.prog = GUESTFS_PROGRAM;
1449 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1451 hdr.direction = GUESTFS_DIRECTION_CALL;
1452 hdr.serial = serial;
1453 hdr.status = GUESTFS_STATUS_OK;
1455 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1456 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1457 error (g, "xdr_guestfs_message_header failed");
1461 /* Serialize the args. If any, because some message types
1462 * have no parameters.
1465 if (!(*xdrp) (&xdr, args)) {
1466 error (g, "dispatch failed to marshal args");
1471 len = xdr_getpos (&xdr);
1474 /* Allocate the outgoing message buffer. */
1475 g->msg_out = safe_malloc (g, len + 4);
1477 g->msg_out_size = len + 4;
1480 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1481 xdr_uint32_t (&xdr, &len);
1483 memcpy (g->msg_out + 4, buffer, len);
1485 if (guestfs__switch_to_sending (g) == -1)
1489 guestfs_set_send_callback (g, send_cb, &sent);
1490 if (ml->main_loop_run (ml, g) == -1)
1493 error (g, "send failed, see earlier error messages");
1502 g->msg_out_size = 0;
1506 static int cancel = 0; /* XXX Implement file cancellation. */
1507 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1508 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1509 static int send_file_cancellation_sync (guestfs_h *g);
1510 static int send_file_complete_sync (guestfs_h *g);
1512 /* Synchronously send a file.
1516 * -2 daemon cancelled (we must read the error message)
1519 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1521 char buf[GUESTFS_MAX_CHUNK_SIZE];
1524 fd = open (filename, O_RDONLY);
1526 perrorf (g, "open: %s", filename);
1527 send_file_cancellation_sync (g);
1528 /* Daemon sees cancellation and won't reply, so caller can
1534 /* Send file in chunked encoding. */
1535 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1536 err = send_file_data_sync (g, buf, r);
1538 if (err == -2) /* daemon sent cancellation */
1539 send_file_cancellation_sync (g);
1544 if (cancel) { /* cancel from either end */
1545 send_file_cancellation_sync (g);
1550 perrorf (g, "read: %s", filename);
1551 send_file_cancellation_sync (g);
1555 /* End of file, but before we send that, we need to close
1556 * the file and check for errors.
1558 if (close (fd) == -1) {
1559 perrorf (g, "close: %s", filename);
1560 send_file_cancellation_sync (g);
1564 return send_file_complete_sync (g);
1567 /* Send a chunk of file data. */
1569 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1571 return send_file_chunk_sync (g, 0, buf, len);
1574 /* Send a cancellation message. */
1576 send_file_cancellation_sync (guestfs_h *g)
1578 return send_file_chunk_sync (g, 1, NULL, 0);
1581 /* Send a file complete chunk. */
1583 send_file_complete_sync (guestfs_h *g)
1586 return send_file_chunk_sync (g, 0, buf, 0);
1589 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1592 static int check_for_daemon_cancellation (guestfs_h *g);
1595 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len)
1597 char data[GUESTFS_MAX_CHUNK_SIZE + 48];
1600 guestfs_chunk chunk;
1602 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1604 if (g->state != BUSY) {
1605 error (g, "send_file_chunk_sync: state %d != READY", g->state);
1609 /* Did the daemon send a cancellation message? */
1610 if (check_for_daemon_cancellation (g)) {
1612 fprintf (stderr, "got daemon cancellation\n");
1616 /* Serialize the chunk. */
1617 chunk.cancel = cancel;
1618 chunk.data.data_len = len;
1619 chunk.data.data_val = (char *) buf;
1623 "library sending chunk cancel = %d, len = %zu, buf = %p\n",
1626 xdrmem_create (&xdr, data, sizeof data, XDR_ENCODE);
1627 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1628 error (g, "xdr_guestfs_chunk failed (buf = %p, len = %zu)", buf, len);
1633 datalen = xdr_getpos (&xdr);
1636 /* Allocate outgoing message buffer. */
1637 g->msg_out = safe_malloc (g, datalen + 4);
1638 g->msg_out_size = datalen + 4;
1641 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1642 xdr_uint32_t (&xdr, &datalen);
1644 memcpy (g->msg_out + 4, data, datalen);
1646 if (guestfs__switch_to_sending (g) == -1)
1650 guestfs_set_send_callback (g, send_cb, &sent);
1651 if (ml->main_loop_run (ml, g) == -1)
1654 error (g, "send file chunk failed, see earlier error messages");
1663 g->msg_out_size = 0;
1667 /* At this point we are sending FileIn file(s) to the guest, and not
1668 * expecting to read anything, so if we do read anything, it must be
1669 * a cancellation message. This checks for this case without blocking.
1672 check_for_daemon_cancellation (guestfs_h *g)
1682 FD_SET (g->sock, &rset);
1685 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1687 perrorf (g, "select");
1693 /* Read the message from the daemon. */
1694 r = xread (g->sock, buf, sizeof buf);
1696 perrorf (g, "read");
1700 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1701 xdr_uint32_t (&xdr, &flag);
1704 if (flag != GUESTFS_CANCEL_FLAG) {
1705 error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1706 flag, GUESTFS_CANCEL_FLAG);
1713 /* Synchronously receive a file. */
1715 static int receive_file_data_sync (guestfs_h *g, void **buf);
1718 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1723 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1725 perrorf (g, "open: %s", filename);
1729 /* Receive the file in chunked encoding. */
1730 while ((r = receive_file_data_sync (g, &buf)) > 0) {
1731 if (xwrite (fd, buf, r) == -1) {
1732 perrorf (g, "%s: write", filename);
1740 error (g, "%s: error in chunked encoding", filename);
1744 if (close (fd) == -1) {
1745 perrorf (g, "close: %s", filename);
1752 /* Send cancellation message to daemon, then wait until it
1753 * cancels (just throwing away data).
1757 uint32_t flag = GUESTFS_CANCEL_FLAG;
1759 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1760 xdr_uint32_t (&xdr, &flag);
1763 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1764 perrorf (g, "write to daemon socket");
1768 while ((r = receive_file_data_sync (g, &buf)) > 0)
1769 free (buf); /* just discard it */
1774 struct receive_file_ctx {
1780 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1782 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1783 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1784 guestfs_chunk chunk;
1786 ml->main_loop_quit (ml, g);
1788 memset (&chunk, 0, sizeof chunk);
1790 if (!xdr_guestfs_chunk (xdr, &chunk)) {
1791 error (g, "failed to parse file chunk");
1796 error (g, "file receive cancelled by daemon");
1800 if (chunk.data.data_len == 0) { /* end of transfer */
1805 ctx->code = chunk.data.data_len;
1806 *ctx->buf = chunk.data.data_val; /* caller frees */
1809 /* Receive a chunk of file data. */
1811 receive_file_data_sync (guestfs_h *g, void **buf)
1813 struct receive_file_ctx ctx;
1814 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1819 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
1820 (void) ml->main_loop_run (ml, g);
1821 guestfs_set_reply_callback (g, NULL, NULL);
1824 fprintf (stderr, "receive_file_data_sync: code %d\n", ctx.code);
1827 case 0: /* end of file */
1832 error (g, "failed to call receive_file_cb");
1834 default: /* received n bytes of data */
1839 /* This is the default main loop implementation, using select(2). */
1842 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1843 guestfs_handle_event_cb cb, void *data)
1845 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1847 if (fd < 0 || fd >= FD_SETSIZE) {
1848 error (g, "fd %d is out of range", fd);
1852 if ((events & ~(GUESTFS_HANDLE_READABLE |
1853 GUESTFS_HANDLE_WRITABLE |
1854 GUESTFS_HANDLE_HANGUP |
1855 GUESTFS_HANDLE_ERROR)) != 0) {
1856 error (g, "set of events (0x%x) contains unknown events", events);
1861 error (g, "set of events is empty");
1865 if (FD_ISSET (fd, &ml->rset) ||
1866 FD_ISSET (fd, &ml->wset) ||
1867 FD_ISSET (fd, &ml->xset)) {
1868 error (g, "fd %d is already registered", fd);
1873 error (g, "callback is NULL");
1877 if ((events & GUESTFS_HANDLE_READABLE))
1878 FD_SET (fd, &ml->rset);
1879 if ((events & GUESTFS_HANDLE_WRITABLE))
1880 FD_SET (fd, &ml->wset);
1881 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1882 FD_SET (fd, &ml->xset);
1884 if (fd > ml->max_fd) {
1886 ml->handle_cb_data =
1887 safe_realloc (g, ml->handle_cb_data,
1888 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1890 ml->handle_cb_data[fd].cb = cb;
1891 ml->handle_cb_data[fd].g = g;
1892 ml->handle_cb_data[fd].data = data;
1896 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1901 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1903 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1905 if (fd < 0 || fd >= FD_SETSIZE) {
1906 error (g, "fd %d is out of range", fd);
1910 if (!FD_ISSET (fd, &ml->rset) &&
1911 !FD_ISSET (fd, &ml->wset) &&
1912 !FD_ISSET (fd, &ml->xset)) {
1913 error (g, "fd %d was not registered", fd);
1917 FD_CLR (fd, &ml->rset);
1918 FD_CLR (fd, &ml->wset);
1919 FD_CLR (fd, &ml->xset);
1921 if (fd == ml->max_fd) {
1923 ml->handle_cb_data =
1924 safe_realloc (g, ml->handle_cb_data,
1925 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1934 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1935 guestfs_handle_timeout_cb cb, void *data)
1937 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1939 abort (); /* XXX not implemented yet */
1943 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1945 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1947 abort (); /* XXX not implemented yet */
1950 /* The 'g' parameter is just used for error reporting. Events
1951 * for multiple handles can be dispatched by running the main
1955 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1957 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1959 fd_set rset2, wset2, xset2;
1961 if (ml->is_running) {
1962 error (g, "select_main_loop_run: this cannot be called recursively");
1968 while (ml->is_running) {
1969 if (ml->nr_fds == 0)
1975 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1977 perrorf (g, "select");
1982 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1984 if (FD_ISSET (fd, &rset2))
1985 events |= GUESTFS_HANDLE_READABLE;
1986 if (FD_ISSET (fd, &wset2))
1987 events |= GUESTFS_HANDLE_WRITABLE;
1988 if (FD_ISSET (fd, &xset2))
1989 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1992 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1993 ml->handle_cb_data[fd].g,
1994 ml->handle_cb_data[fd].data,
2005 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2007 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2009 /* Note that legitimately ml->is_running can be zero when
2010 * this function is called.