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 static void error (guestfs_h *g, const char *fs, ...);
60 static void perrorf (guestfs_h *g, const char *fs, ...);
61 static void *safe_malloc (guestfs_h *g, size_t nbytes);
62 static void *safe_realloc (guestfs_h *g, void *ptr, int nbytes);
63 static char *safe_strdup (guestfs_h *g, const char *str);
64 static void *safe_memdup (guestfs_h *g, void *ptr, size_t size);
66 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
67 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
68 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
69 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
71 static void close_handles (void);
73 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
74 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
75 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
76 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
77 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
78 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
80 /* Default select-based main loop. */
81 struct select_handle_cb_data {
82 guestfs_handle_event_cb cb;
87 struct select_main_loop {
88 /* NB. These fields must be the same as in struct guestfs_main_loop: */
89 guestfs_add_handle_cb add_handle;
90 guestfs_remove_handle_cb remove_handle;
91 guestfs_add_timeout_cb add_timeout;
92 guestfs_remove_timeout_cb remove_timeout;
93 guestfs_main_loop_run_cb main_loop_run;
94 guestfs_main_loop_quit_cb main_loop_quit;
96 /* Additional private data: */
105 struct select_handle_cb_data *handle_cb_data;
108 /* Default main loop. */
109 static struct select_main_loop default_main_loop = {
110 .add_handle = select_add_handle,
111 .remove_handle = select_remove_handle,
112 .add_timeout = select_add_timeout,
113 .remove_timeout = select_remove_timeout,
114 .main_loop_run = select_main_loop_run,
115 .main_loop_quit = select_main_loop_quit,
117 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
118 * set by the normal action of everything being initialized to zero.
123 .handle_cb_data = NULL,
126 #define UNIX_PATH_MAX 108
128 /* Also in guestfsd.c */
129 #define VMCHANNEL_PORT 6666
130 #define VMCHANNEL_ADDR "10.0.2.4"
132 /* GuestFS handle and connection. */
133 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
137 struct guestfs_h *next; /* Linked list of open handles. */
139 /* State: see the state machine diagram in the man page guestfs(3). */
142 int fd[2]; /* Stdin/stdout of qemu. */
143 int sock; /* Daemon communications socket. */
144 int pid; /* Qemu PID. */
145 time_t start_t; /* The time when we started qemu. */
147 int stdout_watch; /* Watches qemu stdout for log messages. */
148 int sock_watch; /* Watches daemon comm socket. */
150 char *tmpdir; /* Temporary directory containing socket. */
152 char **cmdline; /* Qemu command line. */
163 guestfs_abort_cb abort_cb;
164 guestfs_error_handler_cb error_cb;
165 void * error_cb_data;
166 guestfs_send_cb send_cb;
168 guestfs_reply_cb reply_cb;
169 void * reply_cb_data;
170 guestfs_log_message_cb log_message_cb;
171 void * log_message_cb_data;
172 guestfs_subprocess_quit_cb subprocess_quit_cb;
173 void * subprocess_quit_cb_data;
174 guestfs_launch_done_cb launch_done_cb;
175 void * launch_done_cb_data;
177 /* These callbacks are called before send_cb, reply_cb and
178 * launch_done_cb, and are used to implement the high-level
179 * API without needing to interfere with callbacks that the
180 * user might have set.
182 guestfs_send_cb send_cb_internal;
183 void * send_cb_internal_data;
184 guestfs_reply_cb reply_cb_internal;
185 void * reply_cb_internal_data;
186 guestfs_launch_done_cb launch_done_cb_internal;
187 void * launch_done_cb_internal_data;
189 /* Main loop used by this handle. */
190 guestfs_main_loop *main_loop;
192 /* Messages sent and received from the daemon. */
194 int msg_in_size, msg_in_allocated;
196 int msg_out_size, msg_out_pos;
201 static guestfs_h *handles = NULL;
202 static int atexit_handler_set = 0;
205 guestfs_create (void)
210 g = malloc (sizeof (*g));
213 memset (g, 0, sizeof (*g));
220 g->stdout_watch = -1;
224 g->error_cb = default_error_cb;
225 g->error_cb_data = NULL;
227 str = getenv ("LIBGUESTFS_DEBUG");
228 g->verbose = str != NULL && strcmp (str, "1") == 0;
230 str = getenv ("LIBGUESTFS_PATH");
231 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
232 /* XXX We should probably make QEMU configurable as well. */
234 g->main_loop = (guestfs_main_loop *) &default_main_loop;
236 /* Start with large serial numbers so they are easy to spot
237 * inside the protocol.
239 g->msg_next_serial = 0x00123400;
241 /* Link the handles onto a global list. This is the one area
242 * where the library needs to be made thread-safe. (XXX)
244 /* acquire mutex (XXX) */
247 if (!atexit_handler_set) {
248 atexit (close_handles);
249 atexit_handler_set = 1;
251 /* release mutex (XXX) */
254 fprintf (stderr, "new guestfs handle %p\n", g);
260 guestfs_close (guestfs_h *g)
266 if (g->state == NO_HANDLE) {
267 /* Not safe to call 'error' here, so ... */
268 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
273 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
275 /* Try to sync if autosync flag is set. */
276 if (g->autosync && g->state == READY)
279 /* Remove any handlers that might be called back before we kill the
282 g->log_message_cb = NULL;
284 if (g->state != CONFIG)
285 guestfs_kill_subprocess (g);
288 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
297 for (i = 0; i < g->cmdline_size; ++i)
298 free (g->cmdline[i]);
302 /* Mark the handle as dead before freeing it. */
303 g->state = NO_HANDLE;
305 /* acquire mutex (XXX) */
309 for (gg = handles; gg->next != g; gg = gg->next)
313 /* release mutex (XXX) */
315 free (g->last_error);
319 /* Close all open handles (called from atexit(3)). */
323 while (handles) guestfs_close (handles);
327 guestfs_last_error (guestfs_h *g)
329 return g->last_error;
333 set_last_error (guestfs_h *g, const char *msg)
335 free (g->last_error);
336 g->last_error = strdup (msg);
340 default_error_cb (guestfs_h *g, void *data, const char *msg)
342 fprintf (stderr, "libguestfs: error: %s\n", msg);
346 error (guestfs_h *g, const char *fs, ...)
352 vasprintf (&msg, fs, args);
355 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
356 set_last_error (g, msg);
362 perrorf (guestfs_h *g, const char *fs, ...)
369 vasprintf (&msg, fs, args);
374 strerror_r (err, buf, sizeof buf);
378 buf = strerror_r (err, _buf, sizeof _buf);
381 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
385 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
386 set_last_error (g, msg);
392 safe_malloc (guestfs_h *g, size_t nbytes)
394 void *ptr = malloc (nbytes);
395 if (!ptr) g->abort_cb ();
400 safe_realloc (guestfs_h *g, void *ptr, int nbytes)
402 void *p = realloc (ptr, nbytes);
403 if (!p) g->abort_cb ();
408 safe_strdup (guestfs_h *g, const char *str)
410 char *s = strdup (str);
411 if (!s) g->abort_cb ();
416 safe_memdup (guestfs_h *g, void *ptr, size_t size)
418 void *p = malloc (size);
419 if (!p) g->abort_cb ();
420 memcpy (p, ptr, size);
425 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
431 guestfs_get_out_of_memory_handler (guestfs_h *g)
437 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
440 g->error_cb_data = data;
443 guestfs_error_handler_cb
444 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
446 if (data_rtn) *data_rtn = g->error_cb_data;
451 guestfs_set_verbose (guestfs_h *g, int v)
458 guestfs_get_verbose (guestfs_h *g)
464 guestfs_set_autosync (guestfs_h *g, int a)
471 guestfs_get_autosync (guestfs_h *g)
477 guestfs_set_path (guestfs_h *g, const char *path)
480 g->path = GUESTFS_DEFAULT_PATH;
487 guestfs_get_path (guestfs_h *g)
492 /* Add a string to the current command line. */
494 incr_cmdline_size (guestfs_h *g)
496 if (g->cmdline == NULL) {
497 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
499 g->cmdline = safe_malloc (g, sizeof (char *));
500 g->cmdline[0] = NULL;
504 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
508 add_cmdline (guestfs_h *g, const char *str)
510 if (g->state != CONFIG) {
511 error (g, "command line cannot be altered after qemu subprocess launched");
515 incr_cmdline_size (g);
516 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
521 guestfs_config (guestfs_h *g,
522 const char *qemu_param, const char *qemu_value)
524 if (qemu_param[0] != '-') {
525 error (g, "guestfs_config: parameter must begin with '-' character");
529 /* A bit fascist, but the user will probably break the extra
530 * parameters that we add if they try to set any of these.
532 if (strcmp (qemu_param, "-kernel") == 0 ||
533 strcmp (qemu_param, "-initrd") == 0 ||
534 strcmp (qemu_param, "-nographic") == 0 ||
535 strcmp (qemu_param, "-serial") == 0 ||
536 strcmp (qemu_param, "-vnc") == 0 ||
537 strcmp (qemu_param, "-full-screen") == 0 ||
538 strcmp (qemu_param, "-std-vga") == 0 ||
539 strcmp (qemu_param, "-vnc") == 0) {
540 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
544 if (add_cmdline (g, qemu_param) != 0) return -1;
546 if (qemu_value != NULL) {
547 if (add_cmdline (g, qemu_value) != 0) return -1;
554 guestfs_add_drive (guestfs_h *g, const char *filename)
556 int len = strlen (filename) + 64;
559 if (strchr (filename, ',') != NULL) {
560 error (g, "filename cannot contain ',' (comma) character");
564 if (access (filename, F_OK) == -1) {
565 perrorf (g, "%s", filename);
569 snprintf (buf, len, "file=%s", filename);
571 return guestfs_config (g, "-drive", buf);
575 guestfs_add_cdrom (guestfs_h *g, const char *filename)
577 if (strchr (filename, ',') != NULL) {
578 error (g, "filename cannot contain ',' (comma) character");
582 if (access (filename, F_OK) == -1) {
583 perrorf (g, "%s", filename);
587 return guestfs_config (g, "-cdrom", filename);
591 guestfs_launch (guestfs_h *g)
593 static const char *dir_template = "/tmp/libguestfsXXXXXX";
594 int r, i, len, pmore;
597 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
598 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
599 char *path, *pelem, *pend;
600 char *kernel = NULL, *initrd = NULL;
602 struct sockaddr_un addr;
606 error (g, "you must call guestfs_add_drive before guestfs_launch");
610 if (g->state != CONFIG) {
611 error (g, "qemu has already been launched");
615 /* Search g->path for the kernel and initrd. */
616 pelem = path = safe_strdup (g, g->path);
618 pend = strchrnul (pelem, ':');
619 pmore = *pend == ':';
623 /* Empty element or "." means cwd. */
624 if (len == 0 || (len == 1 && *pelem == '.')) {
627 "looking for kernel and initrd in current directory\n");
628 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
629 kernel = safe_strdup (g, kernel_name);
630 initrd = safe_strdup (g, initrd_name);
634 /* Look at <path>/kernel etc. */
636 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
637 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
638 sprintf (kernel, "%s/%s", pelem, kernel_name);
639 sprintf (initrd, "%s/%s", pelem, initrd_name);
642 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
644 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
648 kernel = initrd = NULL;
656 if (kernel == NULL || initrd == NULL) {
657 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
658 kernel_name, initrd_name, g->path);
662 /* Make the temporary directory containing the socket. */
664 g->tmpdir = safe_strdup (g, dir_template);
665 if (mkdtemp (g->tmpdir) == NULL) {
666 perrorf (g, "%s: cannot create temporary directory", dir_template);
671 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
674 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
689 if (r == 0) { /* Child (qemu). */
693 /* Set up the full command line. Do this in the subprocess so we
694 * don't need to worry about cleaning up.
696 g->cmdline[0] = (char *) QEMU;
698 /* Construct the -net channel parameter for qemu. */
699 snprintf (vmchannel, sizeof vmchannel,
700 "channel,%d:unix:%s,server,nowait",
701 VMCHANNEL_PORT, unixsock);
703 /* Linux kernel command line. */
704 snprintf (append, sizeof append,
705 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
707 add_cmdline (g, "-m");
708 add_cmdline (g, "384"); /* XXX Choose best size. */
709 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
710 add_cmdline (g, "-kernel");
711 add_cmdline (g, (char *) kernel);
712 add_cmdline (g, "-initrd");
713 add_cmdline (g, (char *) initrd);
714 add_cmdline (g, "-append");
715 add_cmdline (g, append);
716 add_cmdline (g, "-nographic");
717 add_cmdline (g, "-serial");
718 add_cmdline (g, "stdio");
719 add_cmdline (g, "-net");
720 add_cmdline (g, vmchannel);
721 add_cmdline (g, "-net");
722 add_cmdline (g, "user,vlan=0");
723 add_cmdline (g, "-net");
724 add_cmdline (g, "nic,vlan=0");
725 incr_cmdline_size (g);
726 g->cmdline[g->cmdline_size-1] = NULL;
729 fprintf (stderr, "%s", QEMU);
730 for (i = 0; g->cmdline[i]; ++i)
731 fprintf (stderr, " %s", g->cmdline[i]);
732 fprintf (stderr, "\n");
735 /* Set up stdin, stdout. */
746 /* Set up a new process group, so we can signal this process
747 * and all subprocesses (eg. if qemu is really a shell script).
752 execv (QEMU, g->cmdline); /* Run qemu. */
757 /* Parent (library). */
760 /* Start the clock ... */
763 /* Close the other ends of the pipe. */
767 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
768 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
769 perrorf (g, "fcntl");
773 g->fd[0] = wfd[1]; /* stdin of child */
774 g->fd[1] = rfd[0]; /* stdout of child */
776 /* Open the Unix socket. The vmchannel implementation that got
777 * merged with qemu sucks in a number of ways. Both ends do
778 * connect(2), which means that no one knows what, if anything, is
779 * connected to the other end, or if it becomes disconnected. Even
780 * worse, we have to wait some indeterminate time for qemu to create
781 * the socket and connect to it (which happens very early in qemu's
782 * start-up), so any code that uses vmchannel is inherently racy.
783 * Hence this silly loop.
785 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
787 perrorf (g, "socket");
791 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
792 perrorf (g, "fcntl");
796 addr.sun_family = AF_UNIX;
797 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
798 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
802 /* Always sleep at least once to give qemu a small chance to start up. */
805 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
806 if ((r == -1 && errno == EINPROGRESS) || r == 0)
810 perrorf (g, "connect");
814 error (g, "failed to connect to vmchannel socket");
818 /* Watch the file descriptors. */
821 g->msg_in_size = g->msg_in_allocated = 0;
829 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
830 GUESTFS_HANDLE_READABLE,
832 if (g->stdout_watch == -1) {
833 error (g, "could not watch qemu stdout");
838 g->main_loop->add_handle (g->main_loop, g, g->sock,
839 GUESTFS_HANDLE_READABLE,
840 sock_read_event, NULL);
841 if (g->sock_watch == -1) {
842 error (g, "could not watch daemon communications socket");
846 g->state = LAUNCHING;
850 if (g->stdout_watch >= 0)
851 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
852 if (g->sock_watch >= 0)
853 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
862 waitpid (g->pid, NULL, 0);
868 g->stdout_watch = -1;
878 finish_wait_ready (guestfs_h *g, void *vp)
881 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
884 g->main_loop->main_loop_quit (g->main_loop, g);
888 guestfs_wait_ready (guestfs_h *g)
892 if (g->state == READY) return 0;
894 if (g->state == BUSY) {
895 error (g, "qemu has finished launching already");
899 if (g->state != LAUNCHING) {
900 error (g, "qemu has not been launched yet");
904 g->launch_done_cb_internal = finish_wait_ready;
905 g->launch_done_cb_internal_data = &finished;
906 r = g->main_loop->main_loop_run (g->main_loop, g);
907 g->launch_done_cb_internal = NULL;
908 g->launch_done_cb_internal_data = NULL;
910 if (r == -1) return -1;
913 error (g, "guestfs_wait_ready failed, see earlier error messages");
917 /* This is possible in some really strange situations, such as
918 * guestfsd starts up OK but then qemu immediately exits. Check for
919 * it because the caller is probably expecting to be able to send
920 * commands after this function returns.
922 if (g->state != READY) {
923 error (g, "qemu launched and contacted daemon, but state != READY");
931 guestfs_kill_subprocess (guestfs_h *g)
933 if (g->state == CONFIG) {
934 error (g, "no subprocess to kill");
939 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
941 kill (g->pid, SIGTERM);
946 /* This function is called whenever qemu prints something on stdout.
947 * Qemu's stdout is also connected to the guest's serial console, so
948 * we see kernel messages here too.
951 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
952 int watch, int fd, int events)
960 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
961 g, g->state, fd, events);
964 if (g->fd[1] != fd) {
965 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
969 n = read (fd, buf, sizeof buf);
971 /* Hopefully this indicates the qemu child process has died. */
973 fprintf (stderr, "stdout_event: %p: child process died\n", g);
974 /*kill (g->pid, SIGTERM);*/
975 waitpid (g->pid, NULL, 0);
976 if (g->stdout_watch >= 0)
977 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
978 if (g->sock_watch >= 0)
979 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
988 g->stdout_watch = -1;
991 if (g->subprocess_quit_cb)
992 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1002 /* In verbose mode, copy all log messages to stderr. */
1006 /* It's an actual log message, send it upwards if anyone is listening. */
1007 if (g->log_message_cb)
1008 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1011 /* The function is called whenever we can read something on the
1012 * guestfsd (daemon inside the guest) communication socket.
1015 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1016 int watch, int fd, int events)
1024 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1025 g, g->state, fd, events);
1027 if (g->sock != fd) {
1028 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1032 if (g->msg_in_size <= g->msg_in_allocated) {
1033 g->msg_in_allocated += 4096;
1034 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1036 n = read (g->sock, g->msg_in + g->msg_in_size,
1037 g->msg_in_allocated - g->msg_in_size);
1039 /* Disconnected? Ignore it because stdout_watch will get called
1040 * and will do the cleanup.
1045 if (errno != EAGAIN)
1046 perrorf (g, "read");
1050 g->msg_in_size += n;
1052 /* Have we got enough of a message to be able to process it yet? */
1053 if (g->msg_in_size < 4) return;
1055 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1056 if (!xdr_uint32_t (&xdr, &len)) {
1057 error (g, "can't decode length word");
1061 /* Length is normally the length of the message, but when guestfsd
1062 * starts up it sends a "magic" value (longer than any possible
1063 * message). Check for this.
1065 if (len == 0xf5f55ff5) {
1066 if (g->state != LAUNCHING)
1067 error (g, "received magic signature from guestfsd, but in state %d",
1069 else if (g->msg_in_size != 4)
1070 error (g, "received magic signature from guestfsd, but msg size is %d",
1074 if (g->launch_done_cb_internal)
1075 g->launch_done_cb_internal (g, g->launch_done_cb_internal_data);
1076 if (g->launch_done_cb)
1077 g->launch_done_cb (g, g->launch_done_cb_data);
1083 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1084 if (len > GUESTFS_MESSAGE_MAX) {
1085 error (g, "message length (%u) > maximum possible size (%d)",
1086 len, GUESTFS_MESSAGE_MAX);
1090 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1092 /* This should not happen, and if it does it probably means we've
1093 * lost all hope of synchronization.
1095 if (g->msg_in_size-4 > len) {
1096 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1100 /* Got the full message, begin processing it. */
1104 for (i = 0; i < g->msg_in_size; i += 16) {
1105 printf ("%04x: ", i);
1106 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1107 printf ("%02x ", (unsigned char) g->msg_in[j]);
1108 for (; j < i+16; ++j)
1111 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1112 if (isprint (g->msg_in[j]))
1113 printf ("%c", g->msg_in[j]);
1116 for (; j < i+16; ++j)
1122 /* Not in the expected state. */
1123 if (g->state != BUSY)
1124 error (g, "state %d != BUSY", g->state);
1126 /* Push the message up to the higher layer. Note that unlike
1127 * launch_done_cb / launch_done_cb_internal, we only call at
1128 * most one of the callback functions here.
1131 if (g->reply_cb_internal)
1132 g->reply_cb_internal (g, g->reply_cb_internal_data, &xdr);
1133 else if (g->reply_cb)
1134 g->reply_cb (g, g->reply_cb, &xdr);
1137 /* Free the message buffer if it's grown excessively large. */
1138 if (g->msg_in_allocated > 65536) {
1141 g->msg_in_size = g->msg_in_allocated = 0;
1148 /* The function is called whenever we can write something on the
1149 * guestfsd (daemon inside the guest) communication socket.
1152 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1153 int watch, int fd, int events)
1159 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1160 g, g->state, fd, events);
1162 if (g->sock != fd) {
1163 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1167 if (g->state != BUSY) {
1168 error (g, "sock_write_event: state %d != BUSY", g->state);
1173 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1174 g->msg_out_size - g->msg_out_pos);
1176 n = write (g->sock, g->msg_out + g->msg_out_pos,
1177 g->msg_out_size - g->msg_out_pos);
1179 if (errno != EAGAIN)
1180 perrorf (g, "write");
1185 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1187 g->msg_out_pos += n;
1189 /* More to write? */
1190 if (g->msg_out_pos < g->msg_out_size)
1194 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1197 g->msg_out_pos = g->msg_out_size = 0;
1199 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1200 error (g, "remove_handle failed in sock_write_event");
1204 g->main_loop->add_handle (g->main_loop, g, g->sock,
1205 GUESTFS_HANDLE_READABLE,
1206 sock_read_event, NULL);
1207 if (g->sock_watch == -1) {
1208 error (g, "add_handle failed in sock_write_event");
1213 /* Dispatch a call to the remote daemon. This function just queues
1214 * the call in msg_out, to be sent when we next enter the main loop.
1215 * Returns -1 for error, or the message serial number.
1218 dispatch (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1220 char buffer[GUESTFS_MESSAGE_MAX];
1221 struct guestfs_message_header hdr;
1224 int serial = g->msg_next_serial++;
1226 if (g->state != READY) {
1227 error (g, "dispatch: state %d != READY", g->state);
1231 /* Serialize the header. */
1232 hdr.prog = GUESTFS_PROGRAM;
1233 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1235 hdr.direction = GUESTFS_DIRECTION_CALL;
1236 hdr.serial = serial;
1237 hdr.status = GUESTFS_STATUS_OK;
1239 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1240 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1241 error (g, "xdr_guestfs_message_header failed");
1245 /* Serialize the args. If any, because some message types
1246 * have no parameters.
1249 if (!(*xdrp) (&xdr, args)) {
1250 error (g, "dispatch failed to marshal args");
1255 len = xdr_getpos (&xdr);
1258 /* Allocate the outgoing message buffer. */
1259 g->msg_out = safe_malloc (g, len + 4);
1261 g->msg_out_size = len + 4;
1265 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1266 if (!xdr_uint32_t (&xdr, &len)) {
1267 error (g, "xdr_uint32_t failed in dispatch");
1271 memcpy (g->msg_out + 4, buffer, len);
1273 /* Change the handle to sock_write_event. */
1274 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1275 error (g, "remove_handle failed in dispatch");
1279 g->main_loop->add_handle (g->main_loop, g, g->sock,
1280 GUESTFS_HANDLE_WRITABLE,
1281 sock_write_event, NULL);
1282 if (g->sock_watch == -1) {
1283 error (g, "add_handle failed in dispatch");
1292 g->msg_out_size = 0;
1298 static int cancel = 0; /* XXX Implement file cancellation. */
1301 send_file (guestfs_h *g, const char *filename)
1303 char buf[GUESTFS_MAX_CHUNK_SIZE];
1306 fd = open (filename, O_RDONLY);
1308 perrorf (g, "open: %s", filename);
1309 send_file_cancellation (g);
1310 /* Daemon sees cancellation and won't reply, so caller can
1316 /* Send file in chunked encoding. */
1317 while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1318 if (send_file_data (g, buf, r) == -1)
1323 send_file_cancellation (g);
1328 perrorf (g, "read: %s", filename);
1329 send_file_cancellation (g);
1333 /* End of file, but before we send that, we need to close
1334 * the file and check for errors.
1336 if (close (fd) == -1) {
1337 perrorf (g, "close: %s", filename);
1338 send_file_cancellation (g);
1342 return send_file_complete (g);
1345 /* Send a chunk, cancellation or end of file, wait for it to go. */
1347 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len)
1350 guestfs_chunk chunk;
1353 if (g->state != BUSY) {
1354 error (g, "send_file_chunk: state %d != READY", g->state);
1358 /* Serialize the chunk. */
1359 chunk.cancel = cancel;
1360 chunk.data.data_len = len;
1361 chunk.data.data_val = (char *) buf;
1363 data = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 48);
1364 xdrmem_create (&xdr, data, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1365 if (xdr_guestfs_chunk (&xdr, &chunk)) {
1366 error (g, "xdr_guestfs_chunk failed");
1371 chunkdatalen = xdr_getpos (&xdr);
1374 len = xdr_getpos (&xdr);
1377 data = safe_realloc (g, data, len);
1379 g->msg_out_size = len;
1382 /* Change the handle to sock_write_event. */
1383 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1384 error (g, "remove_handle failed in dispatch");
1388 g->main_loop->add_handle (g->main_loop, g, g->sock,
1389 GUESTFS_HANDLE_WRITABLE,
1390 sock_write_event, NULL);
1391 if (g->sock_watch == -1) {
1392 error (g, "add_handle failed in dispatch");
1401 g->msg_out_size = 0;
1406 /* Send a chunk of file data. */
1408 send_file_data (guestfs_h *g, const char *buf, size_t len)
1410 return send_file_chunk (g, 0, buf, len);
1413 /* Send a cancellation message. */
1415 send_file_cancellation (guestfs_h *g)
1418 return send_file_chunk (g, 1, buf, 0);
1421 /* Send a file complete chunk. */
1423 send_file_complete (guestfs_h *g)
1426 return send_file_chunk (g, 0, buf, 0);
1430 /* Check the return message from a call for validity. */
1432 check_reply_header (guestfs_h *g,
1433 const struct guestfs_message_header *hdr,
1434 int proc_nr, int serial)
1436 if (hdr->prog != GUESTFS_PROGRAM) {
1437 error (g, "wrong program (%d/%d)", hdr->prog, GUESTFS_PROGRAM);
1440 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
1441 error (g, "wrong protocol version (%d/%d)",
1442 hdr->vers, GUESTFS_PROTOCOL_VERSION);
1445 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
1446 error (g, "unexpected message direction (%d/%d)",
1447 hdr->direction, GUESTFS_DIRECTION_REPLY);
1450 if (hdr->proc != proc_nr) {
1451 error (g, "unexpected procedure number (%d/%d)", hdr->proc, proc_nr);
1454 if (hdr->serial != serial) {
1455 error (g, "unexpected serial (%d/%d)", hdr->serial, serial);
1462 /* The high-level actions are autogenerated by generator.ml. Include
1465 #include "guestfs-actions.c"
1467 /* Structure-freeing functions. These rely on the fact that the
1468 * structure format is identical to the XDR format. See note in
1472 guestfs_free_int_bool (struct guestfs_int_bool *x)
1478 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1480 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1485 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1487 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1492 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1494 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1498 /* This is the default main loop implementation, using select(2). */
1501 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1502 guestfs_handle_event_cb cb, void *data)
1504 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1506 if (fd < 0 || fd >= FD_SETSIZE) {
1507 error (g, "fd %d is out of range", fd);
1511 if ((events & ~(GUESTFS_HANDLE_READABLE |
1512 GUESTFS_HANDLE_WRITABLE |
1513 GUESTFS_HANDLE_HANGUP |
1514 GUESTFS_HANDLE_ERROR)) != 0) {
1515 error (g, "set of events (0x%x) contains unknown events", events);
1520 error (g, "set of events is empty");
1524 if (FD_ISSET (fd, &ml->rset) ||
1525 FD_ISSET (fd, &ml->wset) ||
1526 FD_ISSET (fd, &ml->xset)) {
1527 error (g, "fd %d is already registered", fd);
1532 error (g, "callback is NULL");
1536 if ((events & GUESTFS_HANDLE_READABLE))
1537 FD_SET (fd, &ml->rset);
1538 if ((events & GUESTFS_HANDLE_WRITABLE))
1539 FD_SET (fd, &ml->wset);
1540 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1541 FD_SET (fd, &ml->xset);
1543 if (fd > ml->max_fd) {
1545 ml->handle_cb_data =
1546 safe_realloc (g, ml->handle_cb_data,
1547 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1549 ml->handle_cb_data[fd].cb = cb;
1550 ml->handle_cb_data[fd].g = g;
1551 ml->handle_cb_data[fd].data = data;
1555 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1560 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1562 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1564 if (fd < 0 || fd >= FD_SETSIZE) {
1565 error (g, "fd %d is out of range", fd);
1569 if (!FD_ISSET (fd, &ml->rset) &&
1570 !FD_ISSET (fd, &ml->wset) &&
1571 !FD_ISSET (fd, &ml->xset)) {
1572 error (g, "fd %d was not registered", fd);
1576 FD_CLR (fd, &ml->rset);
1577 FD_CLR (fd, &ml->wset);
1578 FD_CLR (fd, &ml->xset);
1580 if (fd == ml->max_fd) {
1582 ml->handle_cb_data =
1583 safe_realloc (g, ml->handle_cb_data,
1584 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1593 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1594 guestfs_handle_timeout_cb cb, void *data)
1596 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1598 abort (); /* XXX not implemented yet */
1602 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1604 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1606 abort (); /* XXX not implemented yet */
1609 /* The 'g' parameter is just used for error reporting. Events
1610 * for multiple handles can be dispatched by running the main
1614 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1616 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1618 fd_set rset2, wset2, xset2;
1620 if (ml->is_running) {
1621 error (g, "select_main_loop_run: this cannot be called recursively");
1627 while (ml->is_running) {
1628 if (ml->nr_fds == 0)
1634 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1636 perrorf (g, "select");
1641 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1643 if (FD_ISSET (fd, &rset2))
1644 events |= GUESTFS_HANDLE_READABLE;
1645 if (FD_ISSET (fd, &wset2))
1646 events |= GUESTFS_HANDLE_WRITABLE;
1647 if (FD_ISSET (fd, &xset2))
1648 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1651 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1652 ml->handle_cb_data[fd].g,
1653 ml->handle_cb_data[fd].data,
1664 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1666 struct select_main_loop *ml = (struct select_main_loop *) mlv;
1668 if (!ml->is_running) {
1669 error (g, "cannot quit, we are not running in a main loop");