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");
833 g->main_loop->add_handle (g->main_loop, g, g->sock,
834 GUESTFS_HANDLE_READABLE,
835 sock_read_event, NULL);
836 if (g->sock_watch == -1) {
837 error (g, "could not watch daemon communications socket");
841 g->state = LAUNCHING;
845 if (g->stdout_watch >= 0)
846 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
847 if (g->sock_watch >= 0)
848 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
857 waitpid (g->pid, NULL, 0);
863 g->stdout_watch = -1;
873 finish_wait_ready (guestfs_h *g, void *vp)
876 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
879 g->main_loop->main_loop_quit (g->main_loop, g);
883 guestfs_wait_ready (guestfs_h *g)
887 if (g->state == READY) return 0;
889 if (g->state == BUSY) {
890 error (g, "qemu has finished launching already");
894 if (g->state != LAUNCHING) {
895 error (g, "qemu has not been launched yet");
899 g->launch_done_cb = finish_wait_ready;
900 g->launch_done_cb_data = &finished;
901 r = g->main_loop->main_loop_run (g->main_loop, g);
902 g->launch_done_cb = NULL;
903 g->launch_done_cb_data = NULL;
905 if (r == -1) return -1;
908 error (g, "guestfs_wait_ready failed, see earlier error messages");
912 /* This is possible in some really strange situations, such as
913 * guestfsd starts up OK but then qemu immediately exits. Check for
914 * it because the caller is probably expecting to be able to send
915 * commands after this function returns.
917 if (g->state != READY) {
918 error (g, "qemu launched and contacted daemon, but state != READY");
926 guestfs_kill_subprocess (guestfs_h *g)
928 if (g->state == CONFIG) {
929 error (g, "no subprocess to kill");
934 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
936 kill (g->pid, SIGTERM);
941 /* Access current state. */
943 guestfs_is_config (guestfs_h *g)
945 return g->state == CONFIG;
949 guestfs_is_launching (guestfs_h *g)
951 return g->state == LAUNCHING;
955 guestfs_is_ready (guestfs_h *g)
957 return g->state == READY;
961 guestfs_is_busy (guestfs_h *g)
963 return g->state == BUSY;
967 guestfs_get_state (guestfs_h *g)
972 /* Structure-freeing functions. These rely on the fact that the
973 * structure format is identical to the XDR format. See note in
977 guestfs_free_int_bool (struct guestfs_int_bool *x)
983 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
985 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
990 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
992 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
997 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
999 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1003 /* This function is called whenever qemu prints something on stdout.
1004 * Qemu's stdout is also connected to the guest's serial console, so
1005 * we see kernel messages here too.
1008 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1009 int watch, int fd, int events)
1017 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1018 g, g->state, fd, events);
1021 if (g->fd[1] != fd) {
1022 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1026 n = read (fd, buf, sizeof buf);
1028 /* Hopefully this indicates the qemu child process has died. */
1030 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1031 /*kill (g->pid, SIGTERM);*/
1032 waitpid (g->pid, NULL, 0);
1033 if (g->stdout_watch >= 0)
1034 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1035 if (g->sock_watch >= 0)
1036 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1045 g->stdout_watch = -1;
1048 if (g->subprocess_quit_cb)
1049 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1054 if (errno != EAGAIN)
1055 perrorf (g, "read");
1059 /* In verbose mode, copy all log messages to stderr. */
1063 /* It's an actual log message, send it upwards if anyone is listening. */
1064 if (g->log_message_cb)
1065 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1068 /* The function is called whenever we can read something on the
1069 * guestfsd (daemon inside the guest) communication socket.
1072 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1073 int watch, int fd, int events)
1081 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1082 g, g->state, fd, events);
1084 if (g->sock != fd) {
1085 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1089 if (g->msg_in_size <= g->msg_in_allocated) {
1090 g->msg_in_allocated += 4096;
1091 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1093 n = read (g->sock, g->msg_in + g->msg_in_size,
1094 g->msg_in_allocated - g->msg_in_size);
1096 /* Disconnected? Ignore it because stdout_watch will get called
1097 * and will do the cleanup.
1102 if (errno != EAGAIN)
1103 perrorf (g, "read");
1107 g->msg_in_size += n;
1109 /* Have we got enough of a message to be able to process it yet? */
1110 if (g->msg_in_size < 4) return;
1112 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1113 if (!xdr_uint32_t (&xdr, &len)) {
1114 error (g, "can't decode length word");
1118 /* Length is normally the length of the message, but when guestfsd
1119 * starts up it sends a "magic" value (longer than any possible
1120 * message). Check for this.
1122 if (len == 0xf5f55ff5) {
1123 if (g->state != LAUNCHING)
1124 error (g, "received magic signature from guestfsd, but in state %d",
1126 else if (g->msg_in_size != 4)
1127 error (g, "received magic signature from guestfsd, but msg size is %d",
1131 if (g->launch_done_cb)
1132 g->launch_done_cb (g, g->launch_done_cb_data);
1138 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1139 if (len > GUESTFS_MESSAGE_MAX) {
1140 error (g, "message length (%u) > maximum possible size (%d)",
1141 len, GUESTFS_MESSAGE_MAX);
1145 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1147 /* This should not happen, and if it does it probably means we've
1148 * lost all hope of synchronization.
1150 if (g->msg_in_size-4 > len) {
1151 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1155 /* Got the full message, begin processing it. */
1159 for (i = 0; i < g->msg_in_size; i += 16) {
1160 printf ("%04x: ", i);
1161 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1162 printf ("%02x ", (unsigned char) g->msg_in[j]);
1163 for (; j < i+16; ++j)
1166 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1167 if (isprint (g->msg_in[j]))
1168 printf ("%c", g->msg_in[j]);
1171 for (; j < i+16; ++j)
1177 /* Not in the expected state. */
1178 if (g->state != BUSY)
1179 error (g, "state %d != BUSY", g->state);
1181 /* Push the message up to the higher layer. */
1184 g->reply_cb (g, g->reply_cb_data, &xdr);
1187 /* Free the message buffer if it's grown excessively large. */
1188 if (g->msg_in_allocated > 65536) {
1191 g->msg_in_size = g->msg_in_allocated = 0;
1198 /* The function is called whenever we can write something on the
1199 * guestfsd (daemon inside the guest) communication socket.
1202 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1203 int watch, int fd, int events)
1209 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1210 g, g->state, fd, events);
1212 if (g->sock != fd) {
1213 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1217 if (g->state != BUSY) {
1218 error (g, "sock_write_event: state %d != BUSY", g->state);
1223 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1224 g->msg_out_size - g->msg_out_pos);
1226 n = write (g->sock, g->msg_out + g->msg_out_pos,
1227 g->msg_out_size - g->msg_out_pos);
1229 if (errno != EAGAIN)
1230 perrorf (g, "write");
1235 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1237 g->msg_out_pos += n;
1239 /* More to write? */
1240 if (g->msg_out_pos < g->msg_out_size)
1244 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1247 g->msg_out_pos = g->msg_out_size = 0;
1249 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1250 error (g, "remove_handle failed in sock_write_event");
1254 g->main_loop->add_handle (g->main_loop, g, g->sock,
1255 GUESTFS_HANDLE_READABLE,
1256 sock_read_event, NULL);
1257 if (g->sock_watch == -1) {
1258 error (g, "add_handle failed in sock_write_event");
1264 guestfs_set_send_callback (guestfs_h *g,
1265 guestfs_send_cb cb, void *opaque)
1268 g->send_cb_data = opaque;
1272 guestfs_set_reply_callback (guestfs_h *g,
1273 guestfs_reply_cb cb, void *opaque)
1276 g->reply_cb_data = opaque;
1280 guestfs_set_log_message_callback (guestfs_h *g,
1281 guestfs_log_message_cb cb, void *opaque)
1283 g->log_message_cb = cb;
1284 g->log_message_cb_data = opaque;
1288 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1289 guestfs_subprocess_quit_cb cb, void *opaque)
1291 g->subprocess_quit_cb = cb;
1292 g->subprocess_quit_cb_data = opaque;
1296 guestfs_set_launch_done_callback (guestfs_h *g,
1297 guestfs_launch_done_cb cb, void *opaque)
1299 g->launch_done_cb = cb;
1300 g->launch_done_cb_data = opaque;
1303 /* Access to the handle's main loop and the default main loop. */
1305 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1307 g->main_loop = main_loop;
1311 guestfs_get_main_loop (guestfs_h *g)
1313 return g->main_loop;
1317 guestfs_get_default_main_loop (void)
1319 return (guestfs_main_loop *) &default_main_loop;
1322 /* Dispatch a call (len + header + args) to the remote daemon. This
1323 * function just queues the call in msg_out, to be sent when we next
1324 * enter the main loop. Returns -1 for error, or the message serial
1328 guestfs__send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1330 char buffer[GUESTFS_MESSAGE_MAX];
1331 struct guestfs_message_header hdr;
1334 int serial = g->msg_next_serial++;
1336 if (g->state != READY) {
1337 error (g, "dispatch: state %d != READY", g->state);
1341 /* Serialize the header. */
1342 hdr.prog = GUESTFS_PROGRAM;
1343 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1345 hdr.direction = GUESTFS_DIRECTION_CALL;
1346 hdr.serial = serial;
1347 hdr.status = GUESTFS_STATUS_OK;
1349 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1350 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1351 error (g, "xdr_guestfs_message_header failed");
1355 /* Serialize the args. If any, because some message types
1356 * have no parameters.
1359 if (!(*xdrp) (&xdr, args)) {
1360 error (g, "dispatch failed to marshal args");
1365 len = xdr_getpos (&xdr);
1368 /* Allocate the outgoing message buffer. */
1369 g->msg_out = safe_malloc (g, len + 4);
1371 g->msg_out_size = len + 4;
1375 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1376 if (!xdr_uint32_t (&xdr, &len)) {
1377 error (g, "xdr_uint32_t failed in dispatch");
1381 memcpy (g->msg_out + 4, buffer, len);
1383 /* Change the handle to sock_write_event. */
1384 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1385 error (g, "remove_handle failed in dispatch");
1389 g->main_loop->add_handle (g->main_loop, g, g->sock,
1390 GUESTFS_HANDLE_WRITABLE,
1391 sock_write_event, NULL);
1392 if (g->sock_watch == -1) {
1393 error (g, "add_handle failed in dispatch");
1402 g->msg_out_size = 0;
1408 static int cancel = 0; /* XXX Implement file cancellation. */
1411 send_file (guestfs_h *g, const char *filename)
1413 char buf[GUESTFS_MAX_CHUNK_SIZE];
1416 fd = open (filename, O_RDONLY);
1418 perrorf (g, "open: %s", filename);
1419 send_file_cancellation (g);
1420 /* Daemon sees cancellation and won't reply, so caller can
1426 /* Send file in chunked encoding. */
1427 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1428 if (send_file_data (g, buf, r) == -1)
1433 send_file_cancellation (g);
1438 perrorf (g, "read: %s", filename);
1439 send_file_cancellation (g);
1443 /* End of file, but before we send that, we need to close
1444 * the file and check for errors.
1446 if (close (fd) == -1) {
1447 perrorf (g, "close: %s", filename);
1448 send_file_cancellation (g);
1452 return send_file_complete (g);
1455 /* Send a chunk, cancellation or end of file, wait for it to go. */
1457 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len)
1460 guestfs_chunk chunk;
1463 if (g->state != BUSY) {
1464 error (g, "send_file_chunk: state %d != READY", g->state);
1468 /* Serialize the chunk. */
1469 chunk.cancel = cancel;
1470 chunk.data.data_len = len;
1471 chunk.data.data_val = (char *) buf;
1473 data = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 48);
1474 xdrmem_create (&xdr, data, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1475 if (xdr_guestfs_chunk (&xdr, &chunk)) {
1476 error (g, "xdr_guestfs_chunk failed");
1481 chunkdatalen = xdr_getpos (&xdr);
1484 len = xdr_getpos (&xdr);
1487 data = safe_realloc (g, data, len);
1489 g->msg_out_size = len;
1492 /* Change the handle to sock_write_event. */
1493 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1494 error (g, "remove_handle failed in dispatch");
1498 g->main_loop->add_handle (g->main_loop, g, g->sock,
1499 GUESTFS_HANDLE_WRITABLE,
1500 sock_write_event, NULL);
1501 if (g->sock_watch == -1) {
1502 error (g, "add_handle failed in dispatch");
1511 g->msg_out_size = 0;
1516 /* Send a chunk of file data. */
1518 send_file_data (guestfs_h *g, const char *buf, size_t len)
1520 return send_file_chunk (g, 0, buf, len);
1523 /* Send a cancellation message. */
1525 send_file_cancellation (guestfs_h *g)
1528 return send_file_chunk (g, 1, buf, 0);
1531 /* Send a file complete chunk. */
1533 send_file_complete (guestfs_h *g)
1536 return send_file_chunk (g, 0, buf, 0);
1540 /* This is the default main loop implementation, using select(2). */
1543 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1544 guestfs_handle_event_cb cb, void *data)
1546 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1548 if (fd < 0 || fd >= FD_SETSIZE) {
1549 error (g, "fd %d is out of range", fd);
1553 if ((events & ~(GUESTFS_HANDLE_READABLE |
1554 GUESTFS_HANDLE_WRITABLE |
1555 GUESTFS_HANDLE_HANGUP |
1556 GUESTFS_HANDLE_ERROR)) != 0) {
1557 error (g, "set of events (0x%x) contains unknown events", events);
1562 error (g, "set of events is empty");
1566 if (FD_ISSET (fd, &ml->rset) ||
1567 FD_ISSET (fd, &ml->wset) ||
1568 FD_ISSET (fd, &ml->xset)) {
1569 error (g, "fd %d is already registered", fd);
1574 error (g, "callback is NULL");
1578 if ((events & GUESTFS_HANDLE_READABLE))
1579 FD_SET (fd, &ml->rset);
1580 if ((events & GUESTFS_HANDLE_WRITABLE))
1581 FD_SET (fd, &ml->wset);
1582 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1583 FD_SET (fd, &ml->xset);
1585 if (fd > ml->max_fd) {
1587 ml->handle_cb_data =
1588 safe_realloc (g, ml->handle_cb_data,
1589 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1591 ml->handle_cb_data[fd].cb = cb;
1592 ml->handle_cb_data[fd].g = g;
1593 ml->handle_cb_data[fd].data = data;
1597 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1602 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1604 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1606 if (fd < 0 || fd >= FD_SETSIZE) {
1607 error (g, "fd %d is out of range", fd);
1611 if (!FD_ISSET (fd, &ml->rset) &&
1612 !FD_ISSET (fd, &ml->wset) &&
1613 !FD_ISSET (fd, &ml->xset)) {
1614 error (g, "fd %d was not registered", fd);
1618 FD_CLR (fd, &ml->rset);
1619 FD_CLR (fd, &ml->wset);
1620 FD_CLR (fd, &ml->xset);
1622 if (fd == ml->max_fd) {
1624 ml->handle_cb_data =
1625 safe_realloc (g, ml->handle_cb_data,
1626 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1635 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1636 guestfs_handle_timeout_cb cb, void *data)
1638 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1640 abort (); /* XXX not implemented yet */
1644 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1646 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1648 abort (); /* XXX not implemented yet */
1651 /* The 'g' parameter is just used for error reporting. Events
1652 * for multiple handles can be dispatched by running the main
1656 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1658 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1660 fd_set rset2, wset2, xset2;
1662 if (ml->is_running) {
1663 error (g, "select_main_loop_run: this cannot be called recursively");
1669 while (ml->is_running) {
1670 if (ml->nr_fds == 0)
1676 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1678 perrorf (g, "select");
1683 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1685 if (FD_ISSET (fd, &rset2))
1686 events |= GUESTFS_HANDLE_READABLE;
1687 if (FD_ISSET (fd, &wset2))
1688 events |= GUESTFS_HANDLE_WRITABLE;
1689 if (FD_ISSET (fd, &xset2))
1690 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1693 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1694 ml->handle_cb_data[fd].g,
1695 ml->handle_cb_data[fd].data,
1706 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1708 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1710 if (!ml->is_running) {
1711 error (g, "cannot quit, we are not running in a main loop");