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 void guestfs_error (guestfs_h *g, const char *fs, ...);
60 void guestfs_perrorf (guestfs_h *g, const char *fs, ...);
61 void *guestfs_safe_malloc (guestfs_h *g, size_t nbytes);
62 void *guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes);
63 char *guestfs_safe_strdup (guestfs_h *g, const char *str);
64 void *guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size);
66 #define error guestfs_error
67 #define perrorf guestfs_perrorf
68 #define safe_malloc guestfs_safe_malloc
69 #define safe_realloc guestfs_safe_realloc
70 #define safe_strdup guestfs_safe_strdup
71 #define safe_memdup guestfs_safe_memdup
73 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
74 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
75 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
76 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
78 static void close_handles (void);
80 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
81 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
82 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
83 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
84 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
85 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
87 /* Default select-based main loop. */
88 struct select_handle_cb_data {
89 guestfs_handle_event_cb cb;
94 struct select_main_loop {
95 /* NB. These fields must be the same as in struct guestfs_main_loop: */
96 guestfs_add_handle_cb add_handle;
97 guestfs_remove_handle_cb remove_handle;
98 guestfs_add_timeout_cb add_timeout;
99 guestfs_remove_timeout_cb remove_timeout;
100 guestfs_main_loop_run_cb main_loop_run;
101 guestfs_main_loop_quit_cb main_loop_quit;
103 /* Additional private data: */
112 struct select_handle_cb_data *handle_cb_data;
115 /* Default main loop. */
116 static struct select_main_loop default_main_loop = {
117 .add_handle = select_add_handle,
118 .remove_handle = select_remove_handle,
119 .add_timeout = select_add_timeout,
120 .remove_timeout = select_remove_timeout,
121 .main_loop_run = select_main_loop_run,
122 .main_loop_quit = select_main_loop_quit,
124 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
125 * set by the normal action of everything being initialized to zero.
130 .handle_cb_data = NULL,
133 #define UNIX_PATH_MAX 108
135 /* Also in guestfsd.c */
136 #define VMCHANNEL_PORT 6666
137 #define VMCHANNEL_ADDR "10.0.2.4"
139 /* GuestFS handle and connection. */
140 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
144 struct guestfs_h *next; /* Linked list of open handles. */
146 /* State: see the state machine diagram in the man page guestfs(3). */
149 int fd[2]; /* Stdin/stdout of qemu. */
150 int sock; /* Daemon communications socket. */
151 int pid; /* Qemu PID. */
152 time_t start_t; /* The time when we started qemu. */
154 int stdout_watch; /* Watches qemu stdout for log messages. */
155 int sock_watch; /* Watches daemon comm socket. */
157 char *tmpdir; /* Temporary directory containing socket. */
159 char **cmdline; /* Qemu command line. */
170 guestfs_abort_cb abort_cb;
171 guestfs_error_handler_cb error_cb;
172 void * error_cb_data;
173 guestfs_send_cb send_cb;
175 guestfs_reply_cb reply_cb;
176 void * reply_cb_data;
177 guestfs_log_message_cb log_message_cb;
178 void * log_message_cb_data;
179 guestfs_subprocess_quit_cb subprocess_quit_cb;
180 void * subprocess_quit_cb_data;
181 guestfs_launch_done_cb launch_done_cb;
182 void * launch_done_cb_data;
184 /* Main loop used by this handle. */
185 guestfs_main_loop *main_loop;
187 /* Messages sent and received from the daemon. */
189 int msg_in_size, msg_in_allocated;
191 int msg_out_size, msg_out_pos;
196 static guestfs_h *handles = NULL;
197 static int atexit_handler_set = 0;
200 guestfs_create (void)
205 g = malloc (sizeof (*g));
208 memset (g, 0, sizeof (*g));
215 g->stdout_watch = -1;
219 g->error_cb = default_error_cb;
220 g->error_cb_data = NULL;
222 str = getenv ("LIBGUESTFS_DEBUG");
223 g->verbose = str != NULL && strcmp (str, "1") == 0;
225 str = getenv ("LIBGUESTFS_PATH");
226 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
227 /* XXX We should probably make QEMU configurable as well. */
229 g->main_loop = guestfs_get_default_main_loop ();
231 /* Start with large serial numbers so they are easy to spot
232 * inside the protocol.
234 g->msg_next_serial = 0x00123400;
236 /* Link the handles onto a global list. This is the one area
237 * where the library needs to be made thread-safe. (XXX)
239 /* acquire mutex (XXX) */
242 if (!atexit_handler_set) {
243 atexit (close_handles);
244 atexit_handler_set = 1;
246 /* release mutex (XXX) */
249 fprintf (stderr, "new guestfs handle %p\n", g);
255 guestfs_close (guestfs_h *g)
261 if (g->state == NO_HANDLE) {
262 /* Not safe to call 'error' here, so ... */
263 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
268 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
270 /* Try to sync if autosync flag is set. */
271 if (g->autosync && g->state == READY)
274 /* Remove any handlers that might be called back before we kill the
277 g->log_message_cb = NULL;
279 if (g->state != CONFIG)
280 guestfs_kill_subprocess (g);
283 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
292 for (i = 0; i < g->cmdline_size; ++i)
293 free (g->cmdline[i]);
297 /* Mark the handle as dead before freeing it. */
298 g->state = NO_HANDLE;
300 /* acquire mutex (XXX) */
304 for (gg = handles; gg->next != g; gg = gg->next)
308 /* release mutex (XXX) */
310 free (g->last_error);
314 /* Close all open handles (called from atexit(3)). */
318 while (handles) guestfs_close (handles);
322 guestfs_last_error (guestfs_h *g)
324 return g->last_error;
328 set_last_error (guestfs_h *g, const char *msg)
330 free (g->last_error);
331 g->last_error = strdup (msg);
335 default_error_cb (guestfs_h *g, void *data, const char *msg)
337 fprintf (stderr, "libguestfs: error: %s\n", msg);
341 guestfs_error (guestfs_h *g, const char *fs, ...)
347 vasprintf (&msg, fs, args);
350 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
351 set_last_error (g, msg);
357 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
364 vasprintf (&msg, fs, args);
369 strerror_r (err, buf, sizeof buf);
373 buf = strerror_r (err, _buf, sizeof _buf);
376 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
380 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
381 set_last_error (g, msg);
387 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
389 void *ptr = malloc (nbytes);
390 if (!ptr) g->abort_cb ();
395 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
397 void *p = realloc (ptr, nbytes);
398 if (!p) g->abort_cb ();
403 guestfs_safe_strdup (guestfs_h *g, const char *str)
405 char *s = strdup (str);
406 if (!s) g->abort_cb ();
411 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
413 void *p = malloc (size);
414 if (!p) g->abort_cb ();
415 memcpy (p, ptr, size);
420 xwrite (int fd, const void *buf, size_t len)
425 r = write (fd, buf, len);
438 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
444 guestfs_get_out_of_memory_handler (guestfs_h *g)
450 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
453 g->error_cb_data = data;
456 guestfs_error_handler_cb
457 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
459 if (data_rtn) *data_rtn = g->error_cb_data;
464 guestfs_set_verbose (guestfs_h *g, int v)
471 guestfs_get_verbose (guestfs_h *g)
477 guestfs_set_autosync (guestfs_h *g, int a)
484 guestfs_get_autosync (guestfs_h *g)
490 guestfs_set_path (guestfs_h *g, const char *path)
493 g->path = GUESTFS_DEFAULT_PATH;
500 guestfs_get_path (guestfs_h *g)
505 /* Add a string to the current command line. */
507 incr_cmdline_size (guestfs_h *g)
509 if (g->cmdline == NULL) {
510 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
512 g->cmdline = safe_malloc (g, sizeof (char *));
513 g->cmdline[0] = NULL;
517 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
521 add_cmdline (guestfs_h *g, const char *str)
523 if (g->state != CONFIG) {
524 error (g, "command line cannot be altered after qemu subprocess launched");
528 incr_cmdline_size (g);
529 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
534 guestfs_config (guestfs_h *g,
535 const char *qemu_param, const char *qemu_value)
537 if (qemu_param[0] != '-') {
538 error (g, "guestfs_config: parameter must begin with '-' character");
542 /* A bit fascist, but the user will probably break the extra
543 * parameters that we add if they try to set any of these.
545 if (strcmp (qemu_param, "-kernel") == 0 ||
546 strcmp (qemu_param, "-initrd") == 0 ||
547 strcmp (qemu_param, "-nographic") == 0 ||
548 strcmp (qemu_param, "-serial") == 0 ||
549 strcmp (qemu_param, "-vnc") == 0 ||
550 strcmp (qemu_param, "-full-screen") == 0 ||
551 strcmp (qemu_param, "-std-vga") == 0 ||
552 strcmp (qemu_param, "-vnc") == 0) {
553 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
557 if (add_cmdline (g, qemu_param) != 0) return -1;
559 if (qemu_value != NULL) {
560 if (add_cmdline (g, qemu_value) != 0) return -1;
567 guestfs_add_drive (guestfs_h *g, const char *filename)
569 int len = strlen (filename) + 64;
572 if (strchr (filename, ',') != NULL) {
573 error (g, "filename cannot contain ',' (comma) character");
577 if (access (filename, F_OK) == -1) {
578 perrorf (g, "%s", filename);
582 snprintf (buf, len, "file=%s", filename);
584 return guestfs_config (g, "-drive", buf);
588 guestfs_add_cdrom (guestfs_h *g, const char *filename)
590 if (strchr (filename, ',') != NULL) {
591 error (g, "filename cannot contain ',' (comma) character");
595 if (access (filename, F_OK) == -1) {
596 perrorf (g, "%s", filename);
600 return guestfs_config (g, "-cdrom", filename);
604 guestfs_launch (guestfs_h *g)
606 static const char *dir_template = "/tmp/libguestfsXXXXXX";
607 int r, i, len, pmore;
610 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
611 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
612 char *path, *pelem, *pend;
613 char *kernel = NULL, *initrd = NULL;
615 struct sockaddr_un addr;
619 error (g, "you must call guestfs_add_drive before guestfs_launch");
623 if (g->state != CONFIG) {
624 error (g, "qemu has already been launched");
628 /* Search g->path for the kernel and initrd. */
629 pelem = path = safe_strdup (g, g->path);
631 pend = strchrnul (pelem, ':');
632 pmore = *pend == ':';
636 /* Empty element or "." means cwd. */
637 if (len == 0 || (len == 1 && *pelem == '.')) {
640 "looking for kernel and initrd in current directory\n");
641 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
642 kernel = safe_strdup (g, kernel_name);
643 initrd = safe_strdup (g, initrd_name);
647 /* Look at <path>/kernel etc. */
649 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
650 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
651 sprintf (kernel, "%s/%s", pelem, kernel_name);
652 sprintf (initrd, "%s/%s", pelem, initrd_name);
655 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
657 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
661 kernel = initrd = NULL;
669 if (kernel == NULL || initrd == NULL) {
670 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
671 kernel_name, initrd_name, g->path);
675 /* Make the temporary directory containing the socket. */
677 g->tmpdir = safe_strdup (g, dir_template);
678 if (mkdtemp (g->tmpdir) == NULL) {
679 perrorf (g, "%s: cannot create temporary directory", dir_template);
684 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
687 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
702 if (r == 0) { /* Child (qemu). */
706 /* Set up the full command line. Do this in the subprocess so we
707 * don't need to worry about cleaning up.
709 g->cmdline[0] = (char *) QEMU;
711 /* Construct the -net channel parameter for qemu. */
712 snprintf (vmchannel, sizeof vmchannel,
713 "channel,%d:unix:%s,server,nowait",
714 VMCHANNEL_PORT, unixsock);
716 /* Linux kernel command line. */
717 snprintf (append, sizeof append,
718 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
720 add_cmdline (g, "-m");
721 add_cmdline (g, "384"); /* XXX Choose best size. */
722 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
723 add_cmdline (g, "-kernel");
724 add_cmdline (g, (char *) kernel);
725 add_cmdline (g, "-initrd");
726 add_cmdline (g, (char *) initrd);
727 add_cmdline (g, "-append");
728 add_cmdline (g, append);
729 add_cmdline (g, "-nographic");
730 add_cmdline (g, "-serial");
731 add_cmdline (g, "stdio");
732 add_cmdline (g, "-net");
733 add_cmdline (g, vmchannel);
734 add_cmdline (g, "-net");
735 add_cmdline (g, "user,vlan=0");
736 add_cmdline (g, "-net");
737 add_cmdline (g, "nic,vlan=0");
738 incr_cmdline_size (g);
739 g->cmdline[g->cmdline_size-1] = NULL;
742 fprintf (stderr, "%s", QEMU);
743 for (i = 0; g->cmdline[i]; ++i)
744 fprintf (stderr, " %s", g->cmdline[i]);
745 fprintf (stderr, "\n");
748 /* Set up stdin, stdout. */
759 /* Set up a new process group, so we can signal this process
760 * and all subprocesses (eg. if qemu is really a shell script).
765 execv (QEMU, g->cmdline); /* Run qemu. */
770 /* Parent (library). */
773 /* Start the clock ... */
776 /* Close the other ends of the pipe. */
780 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
781 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
782 perrorf (g, "fcntl");
786 g->fd[0] = wfd[1]; /* stdin of child */
787 g->fd[1] = rfd[0]; /* stdout of child */
789 /* Open the Unix socket. The vmchannel implementation that got
790 * merged with qemu sucks in a number of ways. Both ends do
791 * connect(2), which means that no one knows what, if anything, is
792 * connected to the other end, or if it becomes disconnected. Even
793 * worse, we have to wait some indeterminate time for qemu to create
794 * the socket and connect to it (which happens very early in qemu's
795 * start-up), so any code that uses vmchannel is inherently racy.
796 * Hence this silly loop.
798 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
800 perrorf (g, "socket");
804 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
805 perrorf (g, "fcntl");
809 addr.sun_family = AF_UNIX;
810 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
811 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
815 /* Always sleep at least once to give qemu a small chance to start up. */
818 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
819 if ((r == -1 && errno == EINPROGRESS) || r == 0)
823 perrorf (g, "connect");
827 error (g, "failed to connect to vmchannel socket");
831 /* Watch the file descriptors. */
834 g->msg_in_size = g->msg_in_allocated = 0;
842 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
843 GUESTFS_HANDLE_READABLE,
845 if (g->stdout_watch == -1) {
846 error (g, "could not watch qemu stdout");
850 if (guestfs__switch_to_receiving (g) == -1)
853 g->state = LAUNCHING;
857 if (g->stdout_watch >= 0)
858 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
859 if (g->sock_watch >= 0)
860 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
869 waitpid (g->pid, NULL, 0);
875 g->stdout_watch = -1;
885 finish_wait_ready (guestfs_h *g, void *vp)
888 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
891 g->main_loop->main_loop_quit (g->main_loop, g);
895 guestfs_wait_ready (guestfs_h *g)
899 if (g->state == READY) return 0;
901 if (g->state == BUSY) {
902 error (g, "qemu has finished launching already");
906 if (g->state != LAUNCHING) {
907 error (g, "qemu has not been launched yet");
911 g->launch_done_cb = finish_wait_ready;
912 g->launch_done_cb_data = &finished;
913 r = g->main_loop->main_loop_run (g->main_loop, g);
914 g->launch_done_cb = NULL;
915 g->launch_done_cb_data = NULL;
917 if (r == -1) return -1;
920 error (g, "guestfs_wait_ready failed, see earlier error messages");
924 /* This is possible in some really strange situations, such as
925 * guestfsd starts up OK but then qemu immediately exits. Check for
926 * it because the caller is probably expecting to be able to send
927 * commands after this function returns.
929 if (g->state != READY) {
930 error (g, "qemu launched and contacted daemon, but state != READY");
938 guestfs_kill_subprocess (guestfs_h *g)
940 if (g->state == CONFIG) {
941 error (g, "no subprocess to kill");
946 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
948 kill (g->pid, SIGTERM);
953 /* Access current state. */
955 guestfs_is_config (guestfs_h *g)
957 return g->state == CONFIG;
961 guestfs_is_launching (guestfs_h *g)
963 return g->state == LAUNCHING;
967 guestfs_is_ready (guestfs_h *g)
969 return g->state == READY;
973 guestfs_is_busy (guestfs_h *g)
975 return g->state == BUSY;
979 guestfs_get_state (guestfs_h *g)
984 /* Structure-freeing functions. These rely on the fact that the
985 * structure format is identical to the XDR format. See note in
989 guestfs_free_int_bool (struct guestfs_int_bool *x)
995 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
997 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1002 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1004 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1009 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1011 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1015 /* This function is called whenever qemu prints something on stdout.
1016 * Qemu's stdout is also connected to the guest's serial console, so
1017 * we see kernel messages here too.
1020 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1021 int watch, int fd, int events)
1029 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1030 g, g->state, fd, events);
1033 if (g->fd[1] != fd) {
1034 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1038 n = read (fd, buf, sizeof buf);
1040 /* Hopefully this indicates the qemu child process has died. */
1042 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1043 /*kill (g->pid, SIGTERM);*/
1044 waitpid (g->pid, NULL, 0);
1045 if (g->stdout_watch >= 0)
1046 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1047 if (g->sock_watch >= 0)
1048 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1057 g->stdout_watch = -1;
1060 if (g->subprocess_quit_cb)
1061 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1066 if (errno != EAGAIN)
1067 perrorf (g, "read");
1071 /* In verbose mode, copy all log messages to stderr. */
1075 /* It's an actual log message, send it upwards if anyone is listening. */
1076 if (g->log_message_cb)
1077 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1080 /* The function is called whenever we can read something on the
1081 * guestfsd (daemon inside the guest) communication socket.
1084 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1085 int watch, int fd, int events)
1093 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1094 g, g->state, fd, events);
1096 if (g->sock != fd) {
1097 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1101 if (g->msg_in_size <= g->msg_in_allocated) {
1102 g->msg_in_allocated += 4096;
1103 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1105 n = read (g->sock, g->msg_in + g->msg_in_size,
1106 g->msg_in_allocated - g->msg_in_size);
1108 /* Disconnected? Ignore it because stdout_watch will get called
1109 * and will do the cleanup.
1114 if (errno != EAGAIN)
1115 perrorf (g, "read");
1119 g->msg_in_size += n;
1121 /* Have we got enough of a message to be able to process it yet? */
1122 if (g->msg_in_size < 4) return;
1124 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1125 if (!xdr_uint32_t (&xdr, &len)) {
1126 error (g, "can't decode length word");
1130 /* Length is normally the length of the message, but when guestfsd
1131 * starts up it sends a "magic" value (longer than any possible
1132 * message). Check for this.
1134 if (len == 0xf5f55ff5) {
1135 if (g->state != LAUNCHING)
1136 error (g, "received magic signature from guestfsd, but in state %d",
1138 else if (g->msg_in_size != 4)
1139 error (g, "received magic signature from guestfsd, but msg size is %d",
1143 if (g->launch_done_cb)
1144 g->launch_done_cb (g, g->launch_done_cb_data);
1150 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1151 if (len > GUESTFS_MESSAGE_MAX) {
1152 error (g, "message length (%u) > maximum possible size (%d)",
1153 len, GUESTFS_MESSAGE_MAX);
1157 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1159 /* This should not happen, and if it does it probably means we've
1160 * lost all hope of synchronization.
1162 if (g->msg_in_size-4 > len) {
1163 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1167 /* Got the full message, begin processing it. */
1171 for (i = 0; i < g->msg_in_size; i += 16) {
1172 printf ("%04x: ", i);
1173 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1174 printf ("%02x ", (unsigned char) g->msg_in[j]);
1175 for (; j < i+16; ++j)
1178 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1179 if (isprint (g->msg_in[j]))
1180 printf ("%c", g->msg_in[j]);
1183 for (; j < i+16; ++j)
1189 /* Not in the expected state. */
1190 if (g->state != BUSY)
1191 error (g, "state %d != BUSY", g->state);
1193 /* Push the message up to the higher layer. */
1196 g->reply_cb (g, g->reply_cb_data, &xdr);
1199 /* Free the message buffer if it's grown excessively large. */
1200 if (g->msg_in_allocated > 65536) {
1203 g->msg_in_size = g->msg_in_allocated = 0;
1210 /* The function is called whenever we can write something on the
1211 * guestfsd (daemon inside the guest) communication socket.
1214 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1215 int watch, int fd, int events)
1221 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1222 g, g->state, fd, events);
1224 if (g->sock != fd) {
1225 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1229 if (g->state != BUSY) {
1230 error (g, "sock_write_event: state %d != BUSY", g->state);
1235 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1236 g->msg_out_size - g->msg_out_pos);
1238 n = write (g->sock, g->msg_out + g->msg_out_pos,
1239 g->msg_out_size - g->msg_out_pos);
1241 if (errno != EAGAIN)
1242 perrorf (g, "write");
1247 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1249 g->msg_out_pos += n;
1251 /* More to write? */
1252 if (g->msg_out_pos < g->msg_out_size)
1256 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1260 g->msg_out_pos = g->msg_out_size = 0;
1262 /* Done writing, call the higher layer. */
1264 g->send_cb (g, g->send_cb_data);
1268 guestfs_set_send_callback (guestfs_h *g,
1269 guestfs_send_cb cb, void *opaque)
1272 g->send_cb_data = opaque;
1276 guestfs_set_reply_callback (guestfs_h *g,
1277 guestfs_reply_cb cb, void *opaque)
1280 g->reply_cb_data = opaque;
1284 guestfs_set_log_message_callback (guestfs_h *g,
1285 guestfs_log_message_cb cb, void *opaque)
1287 g->log_message_cb = cb;
1288 g->log_message_cb_data = opaque;
1292 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1293 guestfs_subprocess_quit_cb cb, void *opaque)
1295 g->subprocess_quit_cb = cb;
1296 g->subprocess_quit_cb_data = opaque;
1300 guestfs_set_launch_done_callback (guestfs_h *g,
1301 guestfs_launch_done_cb cb, void *opaque)
1303 g->launch_done_cb = cb;
1304 g->launch_done_cb_data = opaque;
1307 /* Access to the handle's main loop and the default main loop. */
1309 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1311 g->main_loop = main_loop;
1315 guestfs_get_main_loop (guestfs_h *g)
1317 return g->main_loop;
1321 guestfs_get_default_main_loop (void)
1323 return (guestfs_main_loop *) &default_main_loop;
1326 /* Change the daemon socket handler so that we are now writing.
1327 * This sets the handle to sock_write_event.
1330 guestfs__switch_to_sending (guestfs_h *g)
1332 if (g->sock_watch >= 0) {
1333 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1334 error (g, "remove_handle failed");
1341 g->main_loop->add_handle (g->main_loop, g, g->sock,
1342 GUESTFS_HANDLE_WRITABLE,
1343 sock_write_event, NULL);
1344 if (g->sock_watch == -1) {
1345 error (g, "add_handle failed");
1353 guestfs__switch_to_receiving (guestfs_h *g)
1355 if (g->sock_watch >= 0) {
1356 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1357 error (g, "remove_handle failed");
1364 g->main_loop->add_handle (g->main_loop, g, g->sock,
1365 GUESTFS_HANDLE_READABLE,
1366 sock_read_event, NULL);
1367 if (g->sock_watch == -1) {
1368 error (g, "add_handle failed");
1375 /* Dispatch a call (len + header + args) to the remote daemon,
1376 * synchronously (ie. using the guest's main loop to wait until
1377 * it has been sent). Returns -1 for error, or the serial
1378 * number of the message.
1381 send_cb (guestfs_h *g, void *data)
1383 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1386 ml->main_loop_quit (ml, g);
1390 guestfs__send_sync (guestfs_h *g, int proc_nr,
1391 xdrproc_t xdrp, char *args)
1393 char buffer[GUESTFS_MESSAGE_MAX];
1394 struct guestfs_message_header hdr;
1397 int serial = g->msg_next_serial++;
1399 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1401 if (g->state != READY) {
1402 error (g, "dispatch: state %d != READY", g->state);
1406 /* Serialize the header. */
1407 hdr.prog = GUESTFS_PROGRAM;
1408 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1410 hdr.direction = GUESTFS_DIRECTION_CALL;
1411 hdr.serial = serial;
1412 hdr.status = GUESTFS_STATUS_OK;
1414 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1415 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1416 error (g, "xdr_guestfs_message_header failed");
1420 /* Serialize the args. If any, because some message types
1421 * have no parameters.
1424 if (!(*xdrp) (&xdr, args)) {
1425 error (g, "dispatch failed to marshal args");
1430 len = xdr_getpos (&xdr);
1433 /* Allocate the outgoing message buffer. */
1434 g->msg_out = safe_malloc (g, len + 4);
1436 g->msg_out_size = len + 4;
1440 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1441 if (!xdr_uint32_t (&xdr, &len)) {
1442 error (g, "xdr_uint32_t failed in dispatch");
1446 memcpy (g->msg_out + 4, buffer, len);
1448 if (guestfs__switch_to_sending (g) == -1)
1452 guestfs_set_send_callback (g, send_cb, &sent);
1453 if (ml->main_loop_run (ml, g) == -1)
1456 error (g, "send failed, see earlier error messages");
1465 g->msg_out_size = 0;
1470 static int cancel = 0; /* XXX Implement file cancellation. */
1471 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1472 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1473 static int send_file_cancellation_sync (guestfs_h *g);
1474 static int send_file_complete_sync (guestfs_h *g);
1476 /* Synchronously send a file. */
1478 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1480 char buf[GUESTFS_MAX_CHUNK_SIZE];
1483 fd = open (filename, O_RDONLY);
1485 perrorf (g, "open: %s", filename);
1486 send_file_cancellation_sync (g);
1487 /* Daemon sees cancellation and won't reply, so caller can
1493 /* Send file in chunked encoding. */
1494 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1495 if (send_file_data_sync (g, buf, r) == -1)
1500 send_file_cancellation_sync (g);
1505 perrorf (g, "read: %s", filename);
1506 send_file_cancellation_sync (g);
1510 /* End of file, but before we send that, we need to close
1511 * the file and check for errors.
1513 if (close (fd) == -1) {
1514 perrorf (g, "close: %s", filename);
1515 send_file_cancellation_sync (g);
1519 return send_file_complete_sync (g);
1522 /* Send a chunk of file data. */
1524 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1526 return send_file_chunk_sync (g, 0, buf, len);
1529 /* Send a cancellation message. */
1531 send_file_cancellation_sync (guestfs_h *g)
1534 return send_file_chunk_sync (g, 1, buf, 0);
1537 /* Send a file complete chunk. */
1539 send_file_complete_sync (guestfs_h *g)
1542 return send_file_chunk_sync (g, 0, buf, 0);
1545 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1549 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len)
1554 guestfs_chunk chunk;
1556 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1558 if (g->state != BUSY) {
1559 error (g, "send_file_chunk: state %d != READY", g->state);
1563 /* Serialize the chunk. */
1564 chunk.cancel = cancel;
1565 chunk.data.data_len = len;
1566 chunk.data.data_val = (char *) buf;
1568 data = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 48);
1569 xdrmem_create (&xdr, data, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1570 if (xdr_guestfs_chunk (&xdr, &chunk)) {
1571 error (g, "xdr_guestfs_chunk failed");
1576 datalen = xdr_getpos (&xdr);
1579 data = safe_realloc (g, data, datalen);
1581 g->msg_out_size = datalen;
1584 if (guestfs__switch_to_sending (g) == -1)
1588 guestfs_set_send_callback (g, send_cb, &sent);
1589 if (ml->main_loop_run (ml, g) == -1)
1592 error (g, "send file chunk failed, see earlier error messages");
1601 g->msg_out_size = 0;
1606 /* Synchronously receive a file.
1607 * XXX No way to cancel file receives. We would need to send an
1608 * error to the daemon and have it see this and stop sending.
1610 static int receive_file_data_sync (guestfs_h *g, void **buf);
1613 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1618 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY);
1620 perrorf (g, "open: %s", filename);
1624 /* Receive the file in chunked encoding. */
1625 while ((r = receive_file_data_sync (g, &buf)) > 0) {
1626 if (xwrite (fd, buf, r) == -1) {
1634 error (g, "%s: error in chunked encoding", filename);
1638 if (close (fd) == -1) {
1639 perrorf (g, "close: %s", filename);
1646 struct receive_file_ctx {
1652 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1654 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1655 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1656 guestfs_chunk chunk;
1658 ml->main_loop_quit (ml, g);
1660 if (!xdr_guestfs_chunk (xdr, &chunk)) {
1661 error (g, "failed to parse file chunk");
1666 error (g, "file receive cancelled by daemon");
1670 if (chunk.data.data_len == 0) { /* end of transfer */
1675 ctx->code = chunk.data.data_len;
1676 *ctx->buf = chunk.data.data_val; /* caller frees */
1679 /* Receive a chunk of file data. */
1681 receive_file_data_sync (guestfs_h *g, void **buf)
1683 struct receive_file_ctx ctx;
1684 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1689 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
1690 (void) ml->main_loop_run (ml, g);
1691 guestfs_set_reply_callback (g, NULL, NULL);
1693 case 0: /* end of file */
1698 error (g, "failed to call receive_file_cb");
1700 default: /* received n bytes of data */
1705 /* This is the default main loop implementation, using select(2). */
1708 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1709 guestfs_handle_event_cb cb, void *data)
1711 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1713 if (fd < 0 || fd >= FD_SETSIZE) {
1714 error (g, "fd %d is out of range", fd);
1718 if ((events & ~(GUESTFS_HANDLE_READABLE |
1719 GUESTFS_HANDLE_WRITABLE |
1720 GUESTFS_HANDLE_HANGUP |
1721 GUESTFS_HANDLE_ERROR)) != 0) {
1722 error (g, "set of events (0x%x) contains unknown events", events);
1727 error (g, "set of events is empty");
1731 if (FD_ISSET (fd, &ml->rset) ||
1732 FD_ISSET (fd, &ml->wset) ||
1733 FD_ISSET (fd, &ml->xset)) {
1734 error (g, "fd %d is already registered", fd);
1739 error (g, "callback is NULL");
1743 if ((events & GUESTFS_HANDLE_READABLE))
1744 FD_SET (fd, &ml->rset);
1745 if ((events & GUESTFS_HANDLE_WRITABLE))
1746 FD_SET (fd, &ml->wset);
1747 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1748 FD_SET (fd, &ml->xset);
1750 if (fd > ml->max_fd) {
1752 ml->handle_cb_data =
1753 safe_realloc (g, ml->handle_cb_data,
1754 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1756 ml->handle_cb_data[fd].cb = cb;
1757 ml->handle_cb_data[fd].g = g;
1758 ml->handle_cb_data[fd].data = data;
1762 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1767 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1769 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1771 if (fd < 0 || fd >= FD_SETSIZE) {
1772 error (g, "fd %d is out of range", fd);
1776 if (!FD_ISSET (fd, &ml->rset) &&
1777 !FD_ISSET (fd, &ml->wset) &&
1778 !FD_ISSET (fd, &ml->xset)) {
1779 error (g, "fd %d was not registered", fd);
1783 FD_CLR (fd, &ml->rset);
1784 FD_CLR (fd, &ml->wset);
1785 FD_CLR (fd, &ml->xset);
1787 if (fd == ml->max_fd) {
1789 ml->handle_cb_data =
1790 safe_realloc (g, ml->handle_cb_data,
1791 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1800 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1801 guestfs_handle_timeout_cb cb, void *data)
1803 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1805 abort (); /* XXX not implemented yet */
1809 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1811 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1813 abort (); /* XXX not implemented yet */
1816 /* The 'g' parameter is just used for error reporting. Events
1817 * for multiple handles can be dispatched by running the main
1821 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1823 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1825 fd_set rset2, wset2, xset2;
1827 if (ml->is_running) {
1828 error (g, "select_main_loop_run: this cannot be called recursively");
1834 while (ml->is_running) {
1835 if (ml->nr_fds == 0)
1841 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1843 perrorf (g, "select");
1848 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1850 if (FD_ISSET (fd, &rset2))
1851 events |= GUESTFS_HANDLE_READABLE;
1852 if (FD_ISSET (fd, &wset2))
1853 events |= GUESTFS_HANDLE_WRITABLE;
1854 if (FD_ISSET (fd, &xset2))
1855 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1858 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1859 ml->handle_cb_data[fd].g,
1860 ml->handle_cb_data[fd].data,
1871 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1873 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1875 if (!ml->is_running) {
1876 error (g, "cannot quit, we are not running in a main loop");