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 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
426 guestfs_get_out_of_memory_handler (guestfs_h *g)
432 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
435 g->error_cb_data = data;
438 guestfs_error_handler_cb
439 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
441 if (data_rtn) *data_rtn = g->error_cb_data;
446 guestfs_set_verbose (guestfs_h *g, int v)
453 guestfs_get_verbose (guestfs_h *g)
459 guestfs_set_autosync (guestfs_h *g, int a)
466 guestfs_get_autosync (guestfs_h *g)
472 guestfs_set_path (guestfs_h *g, const char *path)
475 g->path = GUESTFS_DEFAULT_PATH;
482 guestfs_get_path (guestfs_h *g)
487 /* Add a string to the current command line. */
489 incr_cmdline_size (guestfs_h *g)
491 if (g->cmdline == NULL) {
492 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
494 g->cmdline = safe_malloc (g, sizeof (char *));
495 g->cmdline[0] = NULL;
499 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
503 add_cmdline (guestfs_h *g, const char *str)
505 if (g->state != CONFIG) {
506 error (g, "command line cannot be altered after qemu subprocess launched");
510 incr_cmdline_size (g);
511 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
516 guestfs_config (guestfs_h *g,
517 const char *qemu_param, const char *qemu_value)
519 if (qemu_param[0] != '-') {
520 error (g, "guestfs_config: parameter must begin with '-' character");
524 /* A bit fascist, but the user will probably break the extra
525 * parameters that we add if they try to set any of these.
527 if (strcmp (qemu_param, "-kernel") == 0 ||
528 strcmp (qemu_param, "-initrd") == 0 ||
529 strcmp (qemu_param, "-nographic") == 0 ||
530 strcmp (qemu_param, "-serial") == 0 ||
531 strcmp (qemu_param, "-vnc") == 0 ||
532 strcmp (qemu_param, "-full-screen") == 0 ||
533 strcmp (qemu_param, "-std-vga") == 0 ||
534 strcmp (qemu_param, "-vnc") == 0) {
535 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
539 if (add_cmdline (g, qemu_param) != 0) return -1;
541 if (qemu_value != NULL) {
542 if (add_cmdline (g, qemu_value) != 0) return -1;
549 guestfs_add_drive (guestfs_h *g, const char *filename)
551 int len = strlen (filename) + 64;
554 if (strchr (filename, ',') != NULL) {
555 error (g, "filename cannot contain ',' (comma) character");
559 if (access (filename, F_OK) == -1) {
560 perrorf (g, "%s", filename);
564 snprintf (buf, len, "file=%s", filename);
566 return guestfs_config (g, "-drive", buf);
570 guestfs_add_cdrom (guestfs_h *g, const char *filename)
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 return guestfs_config (g, "-cdrom", filename);
586 guestfs_launch (guestfs_h *g)
588 static const char *dir_template = "/tmp/libguestfsXXXXXX";
589 int r, i, len, pmore;
592 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
593 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
594 char *path, *pelem, *pend;
595 char *kernel = NULL, *initrd = NULL;
597 struct sockaddr_un addr;
601 error (g, "you must call guestfs_add_drive before guestfs_launch");
605 if (g->state != CONFIG) {
606 error (g, "qemu has already been launched");
610 /* Search g->path for the kernel and initrd. */
611 pelem = path = safe_strdup (g, g->path);
613 pend = strchrnul (pelem, ':');
614 pmore = *pend == ':';
618 /* Empty element or "." means cwd. */
619 if (len == 0 || (len == 1 && *pelem == '.')) {
622 "looking for kernel and initrd in current directory\n");
623 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
624 kernel = safe_strdup (g, kernel_name);
625 initrd = safe_strdup (g, initrd_name);
629 /* Look at <path>/kernel etc. */
631 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
632 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
633 sprintf (kernel, "%s/%s", pelem, kernel_name);
634 sprintf (initrd, "%s/%s", pelem, initrd_name);
637 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
639 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
643 kernel = initrd = NULL;
651 if (kernel == NULL || initrd == NULL) {
652 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
653 kernel_name, initrd_name, g->path);
657 /* Make the temporary directory containing the socket. */
659 g->tmpdir = safe_strdup (g, dir_template);
660 if (mkdtemp (g->tmpdir) == NULL) {
661 perrorf (g, "%s: cannot create temporary directory", dir_template);
666 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
669 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
684 if (r == 0) { /* Child (qemu). */
688 /* Set up the full command line. Do this in the subprocess so we
689 * don't need to worry about cleaning up.
691 g->cmdline[0] = (char *) QEMU;
693 /* Construct the -net channel parameter for qemu. */
694 snprintf (vmchannel, sizeof vmchannel,
695 "channel,%d:unix:%s,server,nowait",
696 VMCHANNEL_PORT, unixsock);
698 /* Linux kernel command line. */
699 snprintf (append, sizeof append,
700 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
702 add_cmdline (g, "-m");
703 add_cmdline (g, "384"); /* XXX Choose best size. */
704 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
705 add_cmdline (g, "-kernel");
706 add_cmdline (g, (char *) kernel);
707 add_cmdline (g, "-initrd");
708 add_cmdline (g, (char *) initrd);
709 add_cmdline (g, "-append");
710 add_cmdline (g, append);
711 add_cmdline (g, "-nographic");
712 add_cmdline (g, "-serial");
713 add_cmdline (g, "stdio");
714 add_cmdline (g, "-net");
715 add_cmdline (g, vmchannel);
716 add_cmdline (g, "-net");
717 add_cmdline (g, "user,vlan=0");
718 add_cmdline (g, "-net");
719 add_cmdline (g, "nic,vlan=0");
720 incr_cmdline_size (g);
721 g->cmdline[g->cmdline_size-1] = NULL;
724 fprintf (stderr, "%s", QEMU);
725 for (i = 0; g->cmdline[i]; ++i)
726 fprintf (stderr, " %s", g->cmdline[i]);
727 fprintf (stderr, "\n");
730 /* Set up stdin, stdout. */
741 /* Set up a new process group, so we can signal this process
742 * and all subprocesses (eg. if qemu is really a shell script).
747 execv (QEMU, g->cmdline); /* Run qemu. */
752 /* Parent (library). */
755 /* Start the clock ... */
758 /* Close the other ends of the pipe. */
762 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
763 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
764 perrorf (g, "fcntl");
768 g->fd[0] = wfd[1]; /* stdin of child */
769 g->fd[1] = rfd[0]; /* stdout of child */
771 /* Open the Unix socket. The vmchannel implementation that got
772 * merged with qemu sucks in a number of ways. Both ends do
773 * connect(2), which means that no one knows what, if anything, is
774 * connected to the other end, or if it becomes disconnected. Even
775 * worse, we have to wait some indeterminate time for qemu to create
776 * the socket and connect to it (which happens very early in qemu's
777 * start-up), so any code that uses vmchannel is inherently racy.
778 * Hence this silly loop.
780 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
782 perrorf (g, "socket");
786 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
787 perrorf (g, "fcntl");
791 addr.sun_family = AF_UNIX;
792 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
793 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
797 /* Always sleep at least once to give qemu a small chance to start up. */
800 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
801 if ((r == -1 && errno == EINPROGRESS) || r == 0)
805 perrorf (g, "connect");
809 error (g, "failed to connect to vmchannel socket");
813 /* Watch the file descriptors. */
816 g->msg_in_size = g->msg_in_allocated = 0;
824 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
825 GUESTFS_HANDLE_READABLE,
827 if (g->stdout_watch == -1) {
828 error (g, "could not watch qemu stdout");
832 if (guestfs__switch_to_receiving (g) == -1)
835 g->state = LAUNCHING;
839 if (g->stdout_watch >= 0)
840 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
841 if (g->sock_watch >= 0)
842 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
851 waitpid (g->pid, NULL, 0);
857 g->stdout_watch = -1;
867 finish_wait_ready (guestfs_h *g, void *vp)
870 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
873 g->main_loop->main_loop_quit (g->main_loop, g);
877 guestfs_wait_ready (guestfs_h *g)
881 if (g->state == READY) return 0;
883 if (g->state == BUSY) {
884 error (g, "qemu has finished launching already");
888 if (g->state != LAUNCHING) {
889 error (g, "qemu has not been launched yet");
893 g->launch_done_cb = finish_wait_ready;
894 g->launch_done_cb_data = &finished;
895 r = g->main_loop->main_loop_run (g->main_loop, g);
896 g->launch_done_cb = NULL;
897 g->launch_done_cb_data = NULL;
899 if (r == -1) return -1;
902 error (g, "guestfs_wait_ready failed, see earlier error messages");
906 /* This is possible in some really strange situations, such as
907 * guestfsd starts up OK but then qemu immediately exits. Check for
908 * it because the caller is probably expecting to be able to send
909 * commands after this function returns.
911 if (g->state != READY) {
912 error (g, "qemu launched and contacted daemon, but state != READY");
920 guestfs_kill_subprocess (guestfs_h *g)
922 if (g->state == CONFIG) {
923 error (g, "no subprocess to kill");
928 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
930 kill (g->pid, SIGTERM);
935 /* Access current state. */
937 guestfs_is_config (guestfs_h *g)
939 return g->state == CONFIG;
943 guestfs_is_launching (guestfs_h *g)
945 return g->state == LAUNCHING;
949 guestfs_is_ready (guestfs_h *g)
951 return g->state == READY;
955 guestfs_is_busy (guestfs_h *g)
957 return g->state == BUSY;
961 guestfs_get_state (guestfs_h *g)
966 /* Structure-freeing functions. These rely on the fact that the
967 * structure format is identical to the XDR format. See note in
971 guestfs_free_int_bool (struct guestfs_int_bool *x)
977 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
979 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
984 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
986 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
991 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
993 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
997 /* This function is called whenever qemu prints something on stdout.
998 * Qemu's stdout is also connected to the guest's serial console, so
999 * we see kernel messages here too.
1002 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1003 int watch, int fd, int events)
1011 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1012 g, g->state, fd, events);
1015 if (g->fd[1] != fd) {
1016 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1020 n = read (fd, buf, sizeof buf);
1022 /* Hopefully this indicates the qemu child process has died. */
1024 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1025 /*kill (g->pid, SIGTERM);*/
1026 waitpid (g->pid, NULL, 0);
1027 if (g->stdout_watch >= 0)
1028 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1029 if (g->sock_watch >= 0)
1030 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1039 g->stdout_watch = -1;
1042 if (g->subprocess_quit_cb)
1043 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1048 if (errno != EAGAIN)
1049 perrorf (g, "read");
1053 /* In verbose mode, copy all log messages to stderr. */
1057 /* It's an actual log message, send it upwards if anyone is listening. */
1058 if (g->log_message_cb)
1059 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1062 /* The function is called whenever we can read something on the
1063 * guestfsd (daemon inside the guest) communication socket.
1066 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1067 int watch, int fd, int events)
1075 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1076 g, g->state, fd, events);
1078 if (g->sock != fd) {
1079 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1083 if (g->msg_in_size <= g->msg_in_allocated) {
1084 g->msg_in_allocated += 4096;
1085 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1087 n = read (g->sock, g->msg_in + g->msg_in_size,
1088 g->msg_in_allocated - g->msg_in_size);
1090 /* Disconnected? Ignore it because stdout_watch will get called
1091 * and will do the cleanup.
1096 if (errno != EAGAIN)
1097 perrorf (g, "read");
1101 g->msg_in_size += n;
1103 /* Have we got enough of a message to be able to process it yet? */
1104 if (g->msg_in_size < 4) return;
1106 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1107 if (!xdr_uint32_t (&xdr, &len)) {
1108 error (g, "can't decode length word");
1112 /* Length is normally the length of the message, but when guestfsd
1113 * starts up it sends a "magic" value (longer than any possible
1114 * message). Check for this.
1116 if (len == 0xf5f55ff5) {
1117 if (g->state != LAUNCHING)
1118 error (g, "received magic signature from guestfsd, but in state %d",
1120 else if (g->msg_in_size != 4)
1121 error (g, "received magic signature from guestfsd, but msg size is %d",
1125 if (g->launch_done_cb)
1126 g->launch_done_cb (g, g->launch_done_cb_data);
1132 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1133 if (len > GUESTFS_MESSAGE_MAX) {
1134 error (g, "message length (%u) > maximum possible size (%d)",
1135 len, GUESTFS_MESSAGE_MAX);
1139 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1141 /* This should not happen, and if it does it probably means we've
1142 * lost all hope of synchronization.
1144 if (g->msg_in_size-4 > len) {
1145 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1149 /* Got the full message, begin processing it. */
1153 for (i = 0; i < g->msg_in_size; i += 16) {
1154 printf ("%04x: ", i);
1155 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1156 printf ("%02x ", (unsigned char) g->msg_in[j]);
1157 for (; j < i+16; ++j)
1160 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1161 if (isprint (g->msg_in[j]))
1162 printf ("%c", g->msg_in[j]);
1165 for (; j < i+16; ++j)
1171 /* Not in the expected state. */
1172 if (g->state != BUSY)
1173 error (g, "state %d != BUSY", g->state);
1175 /* Push the message up to the higher layer. */
1178 g->reply_cb (g, g->reply_cb_data, &xdr);
1181 /* Free the message buffer if it's grown excessively large. */
1182 if (g->msg_in_allocated > 65536) {
1185 g->msg_in_size = g->msg_in_allocated = 0;
1192 /* The function is called whenever we can write something on the
1193 * guestfsd (daemon inside the guest) communication socket.
1196 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1197 int watch, int fd, int events)
1203 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1204 g, g->state, fd, events);
1206 if (g->sock != fd) {
1207 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1211 if (g->state != BUSY) {
1212 error (g, "sock_write_event: state %d != BUSY", g->state);
1217 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1218 g->msg_out_size - g->msg_out_pos);
1220 n = write (g->sock, g->msg_out + g->msg_out_pos,
1221 g->msg_out_size - g->msg_out_pos);
1223 if (errno != EAGAIN)
1224 perrorf (g, "write");
1229 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1231 g->msg_out_pos += n;
1233 /* More to write? */
1234 if (g->msg_out_pos < g->msg_out_size)
1238 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1242 g->msg_out_pos = g->msg_out_size = 0;
1244 /* Done writing, call the higher layer. */
1246 g->send_cb (g, g->send_cb_data);
1250 guestfs_set_send_callback (guestfs_h *g,
1251 guestfs_send_cb cb, void *opaque)
1254 g->send_cb_data = opaque;
1258 guestfs_set_reply_callback (guestfs_h *g,
1259 guestfs_reply_cb cb, void *opaque)
1262 g->reply_cb_data = opaque;
1266 guestfs_set_log_message_callback (guestfs_h *g,
1267 guestfs_log_message_cb cb, void *opaque)
1269 g->log_message_cb = cb;
1270 g->log_message_cb_data = opaque;
1274 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1275 guestfs_subprocess_quit_cb cb, void *opaque)
1277 g->subprocess_quit_cb = cb;
1278 g->subprocess_quit_cb_data = opaque;
1282 guestfs_set_launch_done_callback (guestfs_h *g,
1283 guestfs_launch_done_cb cb, void *opaque)
1285 g->launch_done_cb = cb;
1286 g->launch_done_cb_data = opaque;
1289 /* Access to the handle's main loop and the default main loop. */
1291 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1293 g->main_loop = main_loop;
1297 guestfs_get_main_loop (guestfs_h *g)
1299 return g->main_loop;
1303 guestfs_get_default_main_loop (void)
1305 return (guestfs_main_loop *) &default_main_loop;
1308 /* Dispatch a call (len + header + args) to the remote daemon. This
1309 * function just queues the call in msg_out, to be sent when we next
1310 * enter the main loop. Returns -1 for error, or the message serial
1314 guestfs__send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1316 char buffer[GUESTFS_MESSAGE_MAX];
1317 struct guestfs_message_header hdr;
1320 int serial = g->msg_next_serial++;
1322 if (g->state != READY) {
1323 error (g, "dispatch: state %d != READY", g->state);
1327 /* Serialize the header. */
1328 hdr.prog = GUESTFS_PROGRAM;
1329 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1331 hdr.direction = GUESTFS_DIRECTION_CALL;
1332 hdr.serial = serial;
1333 hdr.status = GUESTFS_STATUS_OK;
1335 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1336 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1337 error (g, "xdr_guestfs_message_header failed");
1341 /* Serialize the args. If any, because some message types
1342 * have no parameters.
1345 if (!(*xdrp) (&xdr, args)) {
1346 error (g, "dispatch failed to marshal args");
1351 len = xdr_getpos (&xdr);
1354 /* Allocate the outgoing message buffer. */
1355 g->msg_out = safe_malloc (g, len + 4);
1357 g->msg_out_size = len + 4;
1361 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1362 if (!xdr_uint32_t (&xdr, &len)) {
1363 error (g, "xdr_uint32_t failed in dispatch");
1367 memcpy (g->msg_out + 4, buffer, len);
1369 if (guestfs__switch_to_sending (g) == -1)
1377 g->msg_out_size = 0;
1382 /* Change the daemon socket handler so that we are now writing.
1383 * This sets the handle to sock_write_event.
1386 guestfs__switch_to_sending (guestfs_h *g)
1388 if (g->sock_watch >= 0) {
1389 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1390 error (g, "remove_handle failed");
1397 g->main_loop->add_handle (g->main_loop, g, g->sock,
1398 GUESTFS_HANDLE_WRITABLE,
1399 sock_write_event, NULL);
1400 if (g->sock_watch == -1) {
1401 error (g, "add_handle failed");
1409 guestfs__switch_to_receiving (guestfs_h *g)
1411 if (g->sock_watch >= 0) {
1412 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1413 error (g, "remove_handle failed");
1420 g->main_loop->add_handle (g->main_loop, g, g->sock,
1421 GUESTFS_HANDLE_READABLE,
1422 sock_read_event, NULL);
1423 if (g->sock_watch == -1) {
1424 error (g, "add_handle failed");
1432 guestfs__send_file_sync (guestfs_main_loop *ml, guestfs_h *g,
1433 const char *filename)
1439 guestfs__receive_file_sync (guestfs_main_loop *ml, guestfs_h *g,
1440 const char *filename)
1446 static int cancel = 0; /* XXX Implement file cancellation. */
1449 guestfs__send_file (guestfs_h *g, const char *filename)
1451 char buf[GUESTFS_MAX_CHUNK_SIZE];
1454 fd = open (filename, O_RDONLY);
1456 perrorf (g, "open: %s", filename);
1457 send_file_cancellation (g);
1458 /* Daemon sees cancellation and won't reply, so caller can
1464 /* Send file in chunked encoding. */
1465 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1466 if (send_file_data (g, buf, r) == -1)
1471 send_file_cancellation (g);
1476 perrorf (g, "read: %s", filename);
1477 send_file_cancellation (g);
1481 /* End of file, but before we send that, we need to close
1482 * the file and check for errors.
1484 if (close (fd) == -1) {
1485 perrorf (g, "close: %s", filename);
1486 send_file_cancellation (g);
1490 return send_file_complete (g);
1493 /* Send a chunk, cancellation or end of file, wait for it to go. */
1495 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len)
1498 guestfs_chunk chunk;
1501 if (g->state != BUSY) {
1502 error (g, "send_file_chunk: state %d != READY", g->state);
1506 /* Serialize the chunk. */
1507 chunk.cancel = cancel;
1508 chunk.data.data_len = len;
1509 chunk.data.data_val = (char *) buf;
1511 data = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 48);
1512 xdrmem_create (&xdr, data, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1513 if (xdr_guestfs_chunk (&xdr, &chunk)) {
1514 error (g, "xdr_guestfs_chunk failed");
1519 chunkdatalen = xdr_getpos (&xdr);
1522 len = xdr_getpos (&xdr);
1525 data = safe_realloc (g, data, len);
1527 g->msg_out_size = len;
1530 if (guestfs__switch_to_sending (g) == -1)
1538 g->msg_out_size = 0;
1543 /* Send a chunk of file data. */
1545 send_file_data (guestfs_h *g, const char *buf, size_t len)
1547 return send_file_chunk (g, 0, buf, len);
1550 /* Send a cancellation message. */
1552 send_file_cancellation (guestfs_h *g)
1555 return send_file_chunk (g, 1, buf, 0);
1558 /* Send a file complete chunk. */
1560 send_file_complete (guestfs_h *g)
1563 return send_file_chunk (g, 0, buf, 0);
1567 /* This is the default main loop implementation, using select(2). */
1570 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1571 guestfs_handle_event_cb cb, void *data)
1573 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1575 if (fd < 0 || fd >= FD_SETSIZE) {
1576 error (g, "fd %d is out of range", fd);
1580 if ((events & ~(GUESTFS_HANDLE_READABLE |
1581 GUESTFS_HANDLE_WRITABLE |
1582 GUESTFS_HANDLE_HANGUP |
1583 GUESTFS_HANDLE_ERROR)) != 0) {
1584 error (g, "set of events (0x%x) contains unknown events", events);
1589 error (g, "set of events is empty");
1593 if (FD_ISSET (fd, &ml->rset) ||
1594 FD_ISSET (fd, &ml->wset) ||
1595 FD_ISSET (fd, &ml->xset)) {
1596 error (g, "fd %d is already registered", fd);
1601 error (g, "callback is NULL");
1605 if ((events & GUESTFS_HANDLE_READABLE))
1606 FD_SET (fd, &ml->rset);
1607 if ((events & GUESTFS_HANDLE_WRITABLE))
1608 FD_SET (fd, &ml->wset);
1609 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1610 FD_SET (fd, &ml->xset);
1612 if (fd > ml->max_fd) {
1614 ml->handle_cb_data =
1615 safe_realloc (g, ml->handle_cb_data,
1616 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1618 ml->handle_cb_data[fd].cb = cb;
1619 ml->handle_cb_data[fd].g = g;
1620 ml->handle_cb_data[fd].data = data;
1624 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1629 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1631 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1633 if (fd < 0 || fd >= FD_SETSIZE) {
1634 error (g, "fd %d is out of range", fd);
1638 if (!FD_ISSET (fd, &ml->rset) &&
1639 !FD_ISSET (fd, &ml->wset) &&
1640 !FD_ISSET (fd, &ml->xset)) {
1641 error (g, "fd %d was not registered", fd);
1645 FD_CLR (fd, &ml->rset);
1646 FD_CLR (fd, &ml->wset);
1647 FD_CLR (fd, &ml->xset);
1649 if (fd == ml->max_fd) {
1651 ml->handle_cb_data =
1652 safe_realloc (g, ml->handle_cb_data,
1653 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1662 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1663 guestfs_handle_timeout_cb cb, void *data)
1665 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1667 abort (); /* XXX not implemented yet */
1671 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1673 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1675 abort (); /* XXX not implemented yet */
1678 /* The 'g' parameter is just used for error reporting. Events
1679 * for multiple handles can be dispatched by running the main
1683 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1685 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1687 fd_set rset2, wset2, xset2;
1689 if (ml->is_running) {
1690 error (g, "select_main_loop_run: this cannot be called recursively");
1696 while (ml->is_running) {
1697 if (ml->nr_fds == 0)
1703 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1705 perrorf (g, "select");
1710 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1712 if (FD_ISSET (fd, &rset2))
1713 events |= GUESTFS_HANDLE_READABLE;
1714 if (FD_ISSET (fd, &wset2))
1715 events |= GUESTFS_HANDLE_WRITABLE;
1716 if (FD_ISSET (fd, &xset2))
1717 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1720 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1721 ml->handle_cb_data[fd].g,
1722 ml->handle_cb_data[fd].data,
1733 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1735 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1737 if (!ml->is_running) {
1738 error (g, "cannot quit, we are not running in a main loop");