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, int nbytes);
62 static void *safe_realloc (guestfs_h *g, void *ptr, int nbytes);
63 static char *safe_strdup (guestfs_h *g, const char *str);
65 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
66 static void stdout_event (void *data, int watch, int fd, int events);
67 static void sock_read_event (void *data, int watch, int fd, int events);
68 static void sock_write_event (void *data, int watch, int fd, int events);
70 static void close_handles (void);
72 static int select_add_handle (guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
73 static int select_remove_handle (guestfs_h *g, int watch);
74 static int select_add_timeout (guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
75 static int select_remove_timeout (guestfs_h *g, int timer);
76 static void select_main_loop_run (guestfs_h *g);
77 static void select_main_loop_quit (guestfs_h *g);
79 #define UNIX_PATH_MAX 108
81 /* Also in guestfsd.c */
82 #define VMCHANNEL_PORT 6666
83 #define VMCHANNEL_ADDR "10.0.2.4"
85 /* Current main loop. */
86 static guestfs_main_loop main_loop = {
87 .add_handle = select_add_handle,
88 .remove_handle = select_remove_handle,
89 .add_timeout = select_add_timeout,
90 .remove_timeout = select_remove_timeout,
91 .main_loop_run = select_main_loop_run,
92 .main_loop_quit = select_main_loop_quit,
95 /* GuestFS handle and connection. */
96 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
100 struct guestfs_h *next; /* Linked list of open handles. */
102 /* State: see the state machine diagram in the man page guestfs(3). */
105 int fd[2]; /* Stdin/stdout of qemu. */
106 int sock; /* Daemon communications socket. */
107 int pid; /* Qemu PID. */
108 time_t start_t; /* The time when we started qemu. */
110 int stdout_watch; /* Watches qemu stdout for log messages. */
111 int sock_watch; /* Watches daemon comm socket. */
113 char *tmpdir; /* Temporary directory containing socket. */
115 char **cmdline; /* Qemu command line. */
124 guestfs_abort_cb abort_cb;
125 guestfs_error_handler_cb error_cb;
126 void * error_cb_data;
127 guestfs_reply_cb reply_cb;
128 void * reply_cb_data;
129 guestfs_log_message_cb log_message_cb;
130 void * log_message_cb_data;
131 guestfs_subprocess_quit_cb subprocess_quit_cb;
132 void * subprocess_quit_cb_data;
133 guestfs_launch_done_cb launch_done_cb;
134 void * launch_done_cb_data;
136 /* These callbacks are called before reply_cb and launch_done_cb,
137 * and are used to implement the high-level API without needing to
138 * interfere with callbacks that the user might have set.
140 guestfs_reply_cb reply_cb_internal;
141 void * reply_cb_internal_data;
142 guestfs_launch_done_cb launch_done_cb_internal;
143 void * launch_done_cb_internal_data;
145 /* Messages sent and received from the daemon. */
147 int msg_in_size, msg_in_allocated;
149 int msg_out_size, msg_out_pos;
154 static guestfs_h *handles = NULL;
155 static int atexit_handler_set = 0;
158 guestfs_create (void)
163 g = malloc (sizeof (*g));
166 memset (g, 0, sizeof (*g));
173 g->stdout_watch = -1;
177 g->error_cb = default_error_cb;
178 g->error_cb_data = NULL;
180 str = getenv ("LIBGUESTFS_DEBUG");
181 g->verbose = str != NULL && strcmp (str, "1") == 0;
183 str = getenv ("LIBGUESTFS_PATH");
184 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
185 /* XXX We should probably make QEMU configurable as well. */
187 /* Start with large serial numbers so they are easy to spot
188 * inside the protocol.
190 g->msg_next_serial = 0x00123400;
192 /* Link the handles onto a global list. This is the one area
193 * where the library needs to be made thread-safe. (XXX)
195 /* acquire mutex (XXX) */
198 if (!atexit_handler_set) {
199 atexit (close_handles);
200 atexit_handler_set = 1;
202 /* release mutex (XXX) */
205 fprintf (stderr, "new guestfs handle %p\n", g);
211 guestfs_close (guestfs_h *g)
217 if (g->state == NO_HANDLE) {
218 /* Not safe to call 'error' here, so ... */
219 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
224 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
226 /* Try to sync if autosync flag is set. */
227 if (g->autosync && g->state == READY)
230 /* Remove any handlers that might be called back before we kill the
233 g->log_message_cb = NULL;
235 if (g->state != CONFIG)
236 guestfs_kill_subprocess (g);
239 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
248 for (i = 0; i < g->cmdline_size; ++i)
249 free (g->cmdline[i]);
253 /* Mark the handle as dead before freeing it. */
254 g->state = NO_HANDLE;
256 /* acquire mutex (XXX) */
260 for (gg = handles; gg->next != g; gg = gg->next)
264 /* release mutex (XXX) */
269 /* Close all open handles (called from atexit(3)). */
273 while (handles) guestfs_close (handles);
277 default_error_cb (guestfs_h *g, void *data, const char *msg)
279 fprintf (stderr, "libguestfs: error: %s\n", msg);
283 error (guestfs_h *g, const char *fs, ...)
288 if (!g->error_cb) return;
291 vasprintf (&msg, fs, args);
294 g->error_cb (g, g->error_cb_data, msg);
300 perrorf (guestfs_h *g, const char *fs, ...)
306 if (!g->error_cb) return;
309 vasprintf (&msg, fs, args);
314 strerror_r (err, buf, sizeof buf);
318 buf = strerror_r (err, _buf, sizeof _buf);
321 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
325 g->error_cb (g, g->error_cb_data, msg);
331 safe_malloc (guestfs_h *g, int nbytes)
333 void *ptr = malloc (nbytes);
334 if (!ptr) g->abort_cb ();
339 safe_realloc (guestfs_h *g, void *ptr, int nbytes)
341 void *p = realloc (ptr, nbytes);
342 if (!p) g->abort_cb ();
347 safe_strdup (guestfs_h *g, const char *str)
349 char *s = strdup (str);
350 if (!s) g->abort_cb ();
355 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
361 guestfs_get_out_of_memory_handler (guestfs_h *g)
367 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
370 g->error_cb_data = data;
373 guestfs_error_handler_cb
374 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
376 if (data_rtn) *data_rtn = g->error_cb_data;
381 guestfs_set_verbose (guestfs_h *g, int v)
387 guestfs_get_verbose (guestfs_h *g)
393 guestfs_set_autosync (guestfs_h *g, int a)
399 guestfs_get_autosync (guestfs_h *g)
405 guestfs_set_path (guestfs_h *g, const char *path)
408 g->path = GUESTFS_DEFAULT_PATH;
414 guestfs_get_path (guestfs_h *g)
419 /* Add a string to the current command line. */
421 incr_cmdline_size (guestfs_h *g)
423 if (g->cmdline == NULL) {
424 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
426 g->cmdline = safe_malloc (g, sizeof (char *));
427 g->cmdline[0] = NULL;
431 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
435 add_cmdline (guestfs_h *g, const char *str)
437 if (g->state != CONFIG) {
438 error (g, "command line cannot be altered after qemu subprocess launched");
442 incr_cmdline_size (g);
443 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
448 guestfs_config (guestfs_h *g,
449 const char *qemu_param, const char *qemu_value)
451 if (qemu_param[0] != '-') {
452 error (g, "guestfs_config: parameter must begin with '-' character");
456 /* A bit fascist, but the user will probably break the extra
457 * parameters that we add if they try to set any of these.
459 if (strcmp (qemu_param, "-kernel") == 0 ||
460 strcmp (qemu_param, "-initrd") == 0 ||
461 strcmp (qemu_param, "-nographic") == 0 ||
462 strcmp (qemu_param, "-serial") == 0 ||
463 strcmp (qemu_param, "-vnc") == 0 ||
464 strcmp (qemu_param, "-full-screen") == 0 ||
465 strcmp (qemu_param, "-std-vga") == 0 ||
466 strcmp (qemu_param, "-vnc") == 0) {
467 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
471 if (add_cmdline (g, qemu_param) != 0) return -1;
473 if (qemu_value != NULL) {
474 if (add_cmdline (g, qemu_value) != 0) return -1;
481 guestfs_add_drive (guestfs_h *g, const char *filename)
483 int len = strlen (filename) + 64;
486 if (strchr (filename, ',') != NULL) {
487 error (g, "filename cannot contain ',' (comma) character");
491 snprintf (buf, len, "file=%s", filename);
493 return guestfs_config (g, "-drive", buf);
497 guestfs_add_cdrom (guestfs_h *g, const char *filename)
499 if (strchr (filename, ',') != NULL) {
500 error (g, "filename cannot contain ',' (comma) character");
504 return guestfs_config (g, "-cdrom", filename);
508 guestfs_launch (guestfs_h *g)
510 static const char *dir_template = "/tmp/libguestfsXXXXXX";
511 int r, i, len, pmore;
514 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
515 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
516 char *path, *pelem, *pend;
517 char *kernel = NULL, *initrd = NULL;
519 struct sockaddr_un addr;
523 error (g, "you must call guestfs_add_drive before guestfs_launch");
527 if (g->state != CONFIG) {
528 error (g, "qemu has already been launched");
532 /* Search g->path for the kernel and initrd. */
533 pelem = path = safe_strdup (g, g->path);
535 pend = strchrnul (pelem, ':');
536 pmore = *pend == ':';
540 /* Empty element or "." means cwd. */
541 if (len == 0 || (len == 1 && *pelem == '.')) {
544 "looking for kernel and initrd in current directory\n");
545 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
546 kernel = safe_strdup (g, kernel_name);
547 initrd = safe_strdup (g, initrd_name);
551 /* Look at <path>/kernel etc. */
553 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
554 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
555 sprintf (kernel, "%s/%s", pelem, kernel_name);
556 sprintf (initrd, "%s/%s", pelem, initrd_name);
559 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
561 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
565 kernel = initrd = NULL;
573 if (kernel == NULL || initrd == NULL) {
574 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
575 kernel_name, initrd_name, g->path);
579 /* Make the temporary directory containing the socket. */
581 g->tmpdir = safe_strdup (g, dir_template);
582 if (mkdtemp (g->tmpdir) == NULL) {
583 perrorf (g, "%s: cannot create temporary directory", dir_template);
588 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
591 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
606 if (r == 0) { /* Child (qemu). */
610 /* Set up the full command line. Do this in the subprocess so we
611 * don't need to worry about cleaning up.
613 g->cmdline[0] = (char *) QEMU;
615 /* Construct the -net channel parameter for qemu. */
616 snprintf (vmchannel, sizeof vmchannel,
617 "channel,%d:unix:%s,server,nowait",
618 VMCHANNEL_PORT, unixsock);
620 /* Linux kernel command line. */
621 snprintf (append, sizeof append,
622 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
624 add_cmdline (g, "-m");
625 add_cmdline (g, "384"); /* XXX Choose best size. */
626 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
627 add_cmdline (g, "-kernel");
628 add_cmdline (g, (char *) kernel);
629 add_cmdline (g, "-initrd");
630 add_cmdline (g, (char *) initrd);
631 add_cmdline (g, "-append");
632 add_cmdline (g, append);
633 add_cmdline (g, "-nographic");
634 add_cmdline (g, "-serial");
635 add_cmdline (g, "stdio");
636 add_cmdline (g, "-net");
637 add_cmdline (g, vmchannel);
638 add_cmdline (g, "-net");
639 add_cmdline (g, "user,vlan=0");
640 add_cmdline (g, "-net");
641 add_cmdline (g, "nic,vlan=0");
642 incr_cmdline_size (g);
643 g->cmdline[g->cmdline_size-1] = NULL;
646 fprintf (stderr, "%s", QEMU);
647 for (i = 0; g->cmdline[i]; ++i)
648 fprintf (stderr, " %s", g->cmdline[i]);
649 fprintf (stderr, "\n");
652 /* Set up stdin, stdout. */
663 /* Set up a new process group, so we can signal this process
664 * and all subprocesses (eg. if qemu is really a shell script).
669 execv (QEMU, g->cmdline); /* Run qemu. */
674 /* Parent (library). */
677 /* Start the clock ... */
680 /* Close the other ends of the pipe. */
684 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
685 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
686 perrorf (g, "fcntl");
690 g->fd[0] = wfd[1]; /* stdin of child */
691 g->fd[1] = rfd[0]; /* stdout of child */
693 /* Open the Unix socket. The vmchannel implementation that got
694 * merged with qemu sucks in a number of ways. Both ends do
695 * connect(2), which means that no one knows what, if anything, is
696 * connected to the other end, or if it becomes disconnected. Even
697 * worse, we have to wait some indeterminate time for qemu to create
698 * the socket and connect to it (which happens very early in qemu's
699 * start-up), so any code that uses vmchannel is inherently racy.
700 * Hence this silly loop.
702 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
704 perrorf (g, "socket");
708 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
709 perrorf (g, "fcntl");
713 addr.sun_family = AF_UNIX;
714 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
715 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
719 /* Always sleep at least once to give qemu a small chance to start up. */
722 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
723 if ((r == -1 && errno == EINPROGRESS) || r == 0)
727 perrorf (g, "connect");
731 error (g, "failed to connect to vmchannel socket");
735 /* Watch the file descriptors. */
738 g->msg_in_size = g->msg_in_allocated = 0;
746 main_loop.add_handle (g, g->fd[1],
747 GUESTFS_HANDLE_READABLE,
749 if (g->stdout_watch == -1) {
750 error (g, "could not watch qemu stdout");
755 main_loop.add_handle (g, g->sock,
756 GUESTFS_HANDLE_READABLE,
758 if (g->sock_watch == -1) {
759 error (g, "could not watch daemon communications socket");
763 g->state = LAUNCHING;
767 if (g->stdout_watch >= 0)
768 main_loop.remove_handle (g, g->stdout_watch);
769 if (g->sock_watch >= 0)
770 main_loop.remove_handle (g, g->sock_watch);
779 waitpid (g->pid, NULL, 0);
785 g->stdout_watch = -1;
795 finish_wait_ready (guestfs_h *g, void *vp)
798 main_loop.main_loop_quit (g);
802 guestfs_wait_ready (guestfs_h *g)
806 if (g->state == READY) return 0;
808 if (g->state == BUSY) {
809 error (g, "qemu has finished launching already");
813 if (g->state != LAUNCHING) {
814 error (g, "qemu has not been launched yet");
818 g->launch_done_cb_internal = finish_wait_ready;
819 g->launch_done_cb_internal_data = &r;
820 main_loop.main_loop_run (g);
821 g->launch_done_cb_internal = NULL;
822 g->launch_done_cb_internal_data = NULL;
825 error (g, "guestfs_wait_ready failed, see earlier error messages");
829 /* This is possible in some really strange situations, such as
830 * guestfsd starts up OK but then qemu immediately exits. Check for
831 * it because the caller is probably expecting to be able to send
832 * commands after this function returns.
834 if (g->state != READY) {
835 error (g, "qemu launched and contacted daemon, but state != READY");
843 guestfs_kill_subprocess (guestfs_h *g)
845 if (g->state == CONFIG) {
846 error (g, "no subprocess to kill");
851 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
853 kill (g->pid, SIGTERM);
858 /* This function is called whenever qemu prints something on stdout.
859 * Qemu's stdout is also connected to the guest's serial console, so
860 * we see kernel messages here too.
863 stdout_event (void *data, int watch, int fd, int events)
865 guestfs_h *g = (guestfs_h *) data;
872 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
873 g, g->state, fd, events);
876 if (g->fd[1] != fd) {
877 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
881 n = read (fd, buf, sizeof buf);
883 /* Hopefully this indicates the qemu child process has died. */
885 fprintf (stderr, "stdout_event: %p: child process died\n", g);
886 /*kill (g->pid, SIGTERM);*/
887 waitpid (g->pid, NULL, 0);
888 if (g->stdout_watch >= 0)
889 main_loop.remove_handle (g, g->stdout_watch);
890 if (g->sock_watch >= 0)
891 main_loop.remove_handle (g, g->sock_watch);
900 g->stdout_watch = -1;
903 if (g->subprocess_quit_cb)
904 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
914 /* In verbose mode, copy all log messages to stderr. */
918 /* It's an actual log message, send it upwards if anyone is listening. */
919 if (g->log_message_cb)
920 g->log_message_cb (g, g->log_message_cb_data, buf, n);
923 /* The function is called whenever we can read something on the
924 * guestfsd (daemon inside the guest) communication socket.
927 sock_read_event (void *data, int watch, int fd, int events)
929 guestfs_h *g = (guestfs_h *) data;
936 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
937 g, g->state, fd, events);
940 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
944 if (g->msg_in_size <= g->msg_in_allocated) {
945 g->msg_in_allocated += 4096;
946 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
948 n = read (g->sock, g->msg_in + g->msg_in_size,
949 g->msg_in_allocated - g->msg_in_size);
951 /* Disconnected? Ignore it because stdout_watch will get called
952 * and will do the cleanup.
964 /* Have we got enough of a message to be able to process it yet? */
965 if (g->msg_in_size < 4) return;
967 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
968 if (!xdr_uint32_t (&xdr, &len)) {
969 error (g, "can't decode length word");
973 /* Length is normally the length of the message, but when guestfsd
974 * starts up it sends a "magic" value (longer than any possible
975 * message). Check for this.
977 if (len == 0xf5f55ff5) {
978 if (g->state != LAUNCHING)
979 error (g, "received magic signature from guestfsd, but in state %d",
981 else if (g->msg_in_size != 4)
982 error (g, "received magic signature from guestfsd, but msg size is %d",
986 if (g->launch_done_cb_internal)
987 g->launch_done_cb_internal (g, g->launch_done_cb_internal_data);
988 if (g->launch_done_cb)
989 g->launch_done_cb (g, g->launch_done_cb_data);
995 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
996 if (len > GUESTFS_MESSAGE_MAX) {
997 error (g, "message length (%u) > maximum possible size (%d)",
998 len, GUESTFS_MESSAGE_MAX);
1002 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1004 /* This should not happen, and if it does it probably means we've
1005 * lost all hope of synchronization.
1007 if (g->msg_in_size-4 > len) {
1008 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1012 /* Not in the expected state. */
1013 if (g->state != BUSY)
1014 error (g, "state %d != BUSY", g->state);
1016 /* Push the message up to the higher layer. Note that unlike
1017 * launch_done_cb / launch_done_cb_internal, we only call at
1018 * most one of the callback functions here.
1021 if (g->reply_cb_internal)
1022 g->reply_cb_internal (g, g->reply_cb_internal_data, &xdr);
1023 else if (g->reply_cb)
1024 g->reply_cb (g, g->reply_cb, &xdr);
1027 /* Free the message buffer if it's grown excessively large. */
1028 if (g->msg_in_allocated > 65536) {
1031 g->msg_in_size = g->msg_in_allocated = 0;
1038 /* The function is called whenever we can write something on the
1039 * guestfsd (daemon inside the guest) communication socket.
1042 sock_write_event (void *data, int watch, int fd, int events)
1044 guestfs_h *g = (guestfs_h *) data;
1049 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1050 g, g->state, fd, events);
1052 if (g->sock != fd) {
1053 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1057 if (g->state != BUSY) {
1058 error (g, "sock_write_event: state %d != BUSY", g->state);
1063 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1064 g->msg_out_size - g->msg_out_pos);
1066 n = write (g->sock, g->msg_out + g->msg_out_pos,
1067 g->msg_out_size - g->msg_out_pos);
1069 if (errno != EAGAIN)
1070 perrorf (g, "write");
1075 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1077 g->msg_out_pos += n;
1079 /* More to write? */
1080 if (g->msg_out_pos < g->msg_out_size)
1084 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1087 g->msg_out_pos = g->msg_out_size = 0;
1089 if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1090 error (g, "remove_handle failed in sock_write_event");
1094 main_loop.add_handle (g, g->sock,
1095 GUESTFS_HANDLE_READABLE,
1096 sock_read_event, g);
1097 if (g->sock_watch == -1) {
1098 error (g, "add_handle failed in sock_write_event");
1103 /* Dispatch a call to the remote daemon. This function just queues
1104 * the call in msg_out, to be sent when we next enter the main loop.
1105 * Returns -1 for error, or the message serial number.
1108 dispatch (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1110 char buffer[GUESTFS_MESSAGE_MAX];
1111 struct guestfs_message_header hdr;
1114 int serial = g->msg_next_serial++;
1116 if (g->state != READY) {
1117 error (g, "dispatch: state %d != READY", g->state);
1121 /* Serialize the header. */
1122 hdr.prog = GUESTFS_PROGRAM;
1123 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1125 hdr.direction = GUESTFS_DIRECTION_CALL;
1126 hdr.serial = serial;
1127 hdr.status = GUESTFS_STATUS_OK;
1129 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1130 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1131 error (g, "xdr_guestfs_message_header failed");
1135 /* Serialize the args. If any, because some message types
1136 * have no parameters.
1139 if (!(*xdrp) (&xdr, args)) {
1140 error (g, "dispatch failed to marshal args");
1145 len = xdr_getpos (&xdr);
1148 /* Allocate the outgoing message buffer. */
1149 g->msg_out = safe_malloc (g, len + 4);
1151 g->msg_out_size = len + 4;
1155 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1156 if (!xdr_uint32_t (&xdr, &len)) {
1157 error (g, "xdr_uint32_t failed in dispatch");
1161 memcpy (g->msg_out + 4, buffer, len);
1163 /* Change the handle to sock_write_event. */
1164 if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1165 error (g, "remove_handle failed in dispatch");
1169 main_loop.add_handle (g, g->sock,
1170 GUESTFS_HANDLE_WRITABLE,
1171 sock_write_event, g);
1172 if (g->sock_watch == -1) {
1173 error (g, "add_handle failed in dispatch");
1182 g->msg_out_size = 0;
1187 /* Check the return message from a call for validity. */
1189 check_reply_header (guestfs_h *g,
1190 const struct guestfs_message_header *hdr,
1191 int proc_nr, int serial)
1193 if (hdr->prog != GUESTFS_PROGRAM) {
1194 error (g, "wrong program (%d/%d)", hdr->prog, GUESTFS_PROGRAM);
1197 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
1198 error (g, "wrong protocol version (%d/%d)",
1199 hdr->vers, GUESTFS_PROTOCOL_VERSION);
1202 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
1203 error (g, "unexpected message direction (%d/%d)",
1204 hdr->direction, GUESTFS_DIRECTION_REPLY);
1207 if (hdr->proc != proc_nr) {
1208 error (g, "unexpected procedure number (%d/%d)", hdr->proc, proc_nr);
1211 if (hdr->serial != serial) {
1212 error (g, "unexpected serial (%d/%d)", hdr->serial, serial);
1219 /* The high-level actions are autogenerated by generator.ml. Include
1222 #include "guestfs-actions.c"
1224 /* This is the default main loop implementation, using select(2). */
1226 struct handle_cb_data {
1227 guestfs_handle_event_cb cb;
1234 static int select_init_done = 0;
1235 static int max_fd = -1;
1236 static int nr_fds = 0;
1237 static struct handle_cb_data *handle_cb_data = NULL;
1242 if (!select_init_done) {
1247 select_init_done = 1;
1252 select_add_handle (guestfs_h *g, int fd, int events,
1253 guestfs_handle_event_cb cb, void *data)
1257 if (fd < 0 || fd >= FD_SETSIZE) {
1258 error (g, "fd %d is out of range", fd);
1262 if ((events & ~(GUESTFS_HANDLE_READABLE |
1263 GUESTFS_HANDLE_WRITABLE |
1264 GUESTFS_HANDLE_HANGUP |
1265 GUESTFS_HANDLE_ERROR)) != 0) {
1266 error (g, "set of events (0x%x) contains unknown events", events);
1271 error (g, "set of events is empty");
1275 if (FD_ISSET (fd, &rset) || FD_ISSET (fd, &wset) || FD_ISSET (fd, &xset)) {
1276 error (g, "fd %d is already registered", fd);
1281 error (g, "callback is NULL");
1285 if ((events & GUESTFS_HANDLE_READABLE))
1287 if ((events & GUESTFS_HANDLE_WRITABLE))
1289 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1294 handle_cb_data = safe_realloc (g, handle_cb_data,
1295 sizeof (struct handle_cb_data) * (max_fd+1));
1297 handle_cb_data[fd].cb = cb;
1298 handle_cb_data[fd].data = data;
1302 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1307 select_remove_handle (guestfs_h *g, int fd)
1311 if (fd < 0 || fd >= FD_SETSIZE) {
1312 error (g, "fd %d is out of range", fd);
1316 if (!FD_ISSET (fd, &rset) && !FD_ISSET (fd, &wset) && !FD_ISSET (fd, &xset)) {
1317 error (g, "fd %d was not registered", fd);
1327 handle_cb_data = safe_realloc (g, handle_cb_data,
1328 sizeof (struct handle_cb_data) * (max_fd+1));
1337 select_add_timeout (guestfs_h *g, int interval,
1338 guestfs_handle_timeout_cb cb, void *data)
1342 abort (); /* XXX not implemented yet */
1346 select_remove_timeout (guestfs_h *g, int timer)
1350 abort (); /* XXX not implemented yet */
1353 /* Note that main loops can be nested. */
1354 static int level = 0;
1357 select_main_loop_run (guestfs_h *g)
1359 int old_level, fd, r, events;
1360 fd_set rset2, wset2, xset2;
1364 old_level = level++;
1365 while (level > old_level) {
1374 r = select (max_fd+1, &rset2, &wset2, &xset2, NULL);
1376 perrorf (g, "select");
1381 for (fd = 0; r > 0 && fd <= max_fd; ++fd) {
1383 if (FD_ISSET (fd, &rset2))
1384 events |= GUESTFS_HANDLE_READABLE;
1385 if (FD_ISSET (fd, &wset2))
1386 events |= GUESTFS_HANDLE_WRITABLE;
1387 if (FD_ISSET (fd, &xset2))
1388 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1391 handle_cb_data[fd].cb (handle_cb_data[fd].data,
1399 select_main_loop_quit (guestfs_h *g)
1404 error (g, "cannot quit, we are not in a main loop");