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 (void *data, int watch, int fd, int events);
68 static void sock_read_event (void *data, int watch, int fd, int events);
69 static void sock_write_event (void *data, int watch, int fd, int events);
71 static void close_handles (void);
73 static int select_add_handle (guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
74 static int select_remove_handle (guestfs_h *g, int watch);
75 static int select_add_timeout (guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
76 static int select_remove_timeout (guestfs_h *g, int timer);
77 static void select_main_loop_run (guestfs_h *g);
78 static void select_main_loop_quit (guestfs_h *g);
80 #define UNIX_PATH_MAX 108
82 /* Also in guestfsd.c */
83 #define VMCHANNEL_PORT 6666
84 #define VMCHANNEL_ADDR "10.0.2.4"
86 /* Current main loop. */
87 static guestfs_main_loop main_loop = {
88 .add_handle = select_add_handle,
89 .remove_handle = select_remove_handle,
90 .add_timeout = select_add_timeout,
91 .remove_timeout = select_remove_timeout,
92 .main_loop_run = select_main_loop_run,
93 .main_loop_quit = select_main_loop_quit,
96 /* GuestFS handle and connection. */
97 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
101 struct guestfs_h *next; /* Linked list of open handles. */
103 /* State: see the state machine diagram in the man page guestfs(3). */
106 int fd[2]; /* Stdin/stdout of qemu. */
107 int sock; /* Daemon communications socket. */
108 int pid; /* Qemu PID. */
109 time_t start_t; /* The time when we started qemu. */
111 int stdout_watch; /* Watches qemu stdout for log messages. */
112 int sock_watch; /* Watches daemon comm socket. */
114 char *tmpdir; /* Temporary directory containing socket. */
116 char **cmdline; /* Qemu command line. */
125 guestfs_abort_cb abort_cb;
126 guestfs_error_handler_cb error_cb;
127 void * error_cb_data;
128 guestfs_reply_cb reply_cb;
129 void * reply_cb_data;
130 guestfs_log_message_cb log_message_cb;
131 void * log_message_cb_data;
132 guestfs_subprocess_quit_cb subprocess_quit_cb;
133 void * subprocess_quit_cb_data;
134 guestfs_launch_done_cb launch_done_cb;
135 void * launch_done_cb_data;
137 /* These callbacks are called before reply_cb and launch_done_cb,
138 * and are used to implement the high-level API without needing to
139 * interfere with callbacks that the user might have set.
141 guestfs_reply_cb reply_cb_internal;
142 void * reply_cb_internal_data;
143 guestfs_launch_done_cb launch_done_cb_internal;
144 void * launch_done_cb_internal_data;
146 /* Messages sent and received from the daemon. */
148 int msg_in_size, msg_in_allocated;
150 int msg_out_size, msg_out_pos;
155 static guestfs_h *handles = NULL;
156 static int atexit_handler_set = 0;
159 guestfs_create (void)
164 g = malloc (sizeof (*g));
167 memset (g, 0, sizeof (*g));
174 g->stdout_watch = -1;
178 g->error_cb = default_error_cb;
179 g->error_cb_data = NULL;
181 str = getenv ("LIBGUESTFS_DEBUG");
182 g->verbose = str != NULL && strcmp (str, "1") == 0;
184 str = getenv ("LIBGUESTFS_PATH");
185 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
186 /* XXX We should probably make QEMU configurable as well. */
188 /* Start with large serial numbers so they are easy to spot
189 * inside the protocol.
191 g->msg_next_serial = 0x00123400;
193 /* Link the handles onto a global list. This is the one area
194 * where the library needs to be made thread-safe. (XXX)
196 /* acquire mutex (XXX) */
199 if (!atexit_handler_set) {
200 atexit (close_handles);
201 atexit_handler_set = 1;
203 /* release mutex (XXX) */
206 fprintf (stderr, "new guestfs handle %p\n", g);
212 guestfs_close (guestfs_h *g)
218 if (g->state == NO_HANDLE) {
219 /* Not safe to call 'error' here, so ... */
220 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
225 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
227 /* Try to sync if autosync flag is set. */
228 if (g->autosync && g->state == READY)
231 /* Remove any handlers that might be called back before we kill the
234 g->log_message_cb = NULL;
236 if (g->state != CONFIG)
237 guestfs_kill_subprocess (g);
240 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
249 for (i = 0; i < g->cmdline_size; ++i)
250 free (g->cmdline[i]);
254 /* Mark the handle as dead before freeing it. */
255 g->state = NO_HANDLE;
257 /* acquire mutex (XXX) */
261 for (gg = handles; gg->next != g; gg = gg->next)
265 /* release mutex (XXX) */
270 /* Close all open handles (called from atexit(3)). */
274 while (handles) guestfs_close (handles);
278 default_error_cb (guestfs_h *g, void *data, const char *msg)
280 fprintf (stderr, "libguestfs: error: %s\n", msg);
284 error (guestfs_h *g, const char *fs, ...)
289 if (!g->error_cb) return;
292 vasprintf (&msg, fs, args);
295 g->error_cb (g, g->error_cb_data, msg);
301 perrorf (guestfs_h *g, const char *fs, ...)
307 if (!g->error_cb) return;
310 vasprintf (&msg, fs, args);
315 strerror_r (err, buf, sizeof buf);
319 buf = strerror_r (err, _buf, sizeof _buf);
322 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
326 g->error_cb (g, g->error_cb_data, msg);
332 safe_malloc (guestfs_h *g, size_t nbytes)
334 void *ptr = malloc (nbytes);
335 if (!ptr) g->abort_cb ();
340 safe_realloc (guestfs_h *g, void *ptr, int nbytes)
342 void *p = realloc (ptr, nbytes);
343 if (!p) g->abort_cb ();
348 safe_strdup (guestfs_h *g, const char *str)
350 char *s = strdup (str);
351 if (!s) g->abort_cb ();
356 safe_memdup (guestfs_h *g, void *ptr, size_t size)
358 void *p = malloc (size);
359 if (!p) g->abort_cb ();
360 memcpy (p, ptr, size);
365 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
371 guestfs_get_out_of_memory_handler (guestfs_h *g)
377 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
380 g->error_cb_data = data;
383 guestfs_error_handler_cb
384 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
386 if (data_rtn) *data_rtn = g->error_cb_data;
391 guestfs_set_verbose (guestfs_h *g, int v)
398 guestfs_get_verbose (guestfs_h *g)
404 guestfs_set_autosync (guestfs_h *g, int a)
411 guestfs_get_autosync (guestfs_h *g)
417 guestfs_set_path (guestfs_h *g, const char *path)
420 g->path = GUESTFS_DEFAULT_PATH;
427 guestfs_get_path (guestfs_h *g)
432 /* Add a string to the current command line. */
434 incr_cmdline_size (guestfs_h *g)
436 if (g->cmdline == NULL) {
437 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
439 g->cmdline = safe_malloc (g, sizeof (char *));
440 g->cmdline[0] = NULL;
444 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
448 add_cmdline (guestfs_h *g, const char *str)
450 if (g->state != CONFIG) {
451 error (g, "command line cannot be altered after qemu subprocess launched");
455 incr_cmdline_size (g);
456 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
461 guestfs_config (guestfs_h *g,
462 const char *qemu_param, const char *qemu_value)
464 if (qemu_param[0] != '-') {
465 error (g, "guestfs_config: parameter must begin with '-' character");
469 /* A bit fascist, but the user will probably break the extra
470 * parameters that we add if they try to set any of these.
472 if (strcmp (qemu_param, "-kernel") == 0 ||
473 strcmp (qemu_param, "-initrd") == 0 ||
474 strcmp (qemu_param, "-nographic") == 0 ||
475 strcmp (qemu_param, "-serial") == 0 ||
476 strcmp (qemu_param, "-vnc") == 0 ||
477 strcmp (qemu_param, "-full-screen") == 0 ||
478 strcmp (qemu_param, "-std-vga") == 0 ||
479 strcmp (qemu_param, "-vnc") == 0) {
480 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
484 if (add_cmdline (g, qemu_param) != 0) return -1;
486 if (qemu_value != NULL) {
487 if (add_cmdline (g, qemu_value) != 0) return -1;
494 guestfs_add_drive (guestfs_h *g, const char *filename)
496 int len = strlen (filename) + 64;
499 if (strchr (filename, ',') != NULL) {
500 error (g, "filename cannot contain ',' (comma) character");
504 if (access (filename, F_OK) == -1) {
505 perrorf (g, "%s", filename);
509 snprintf (buf, len, "file=%s", filename);
511 return guestfs_config (g, "-drive", buf);
515 guestfs_add_cdrom (guestfs_h *g, const char *filename)
517 if (strchr (filename, ',') != NULL) {
518 error (g, "filename cannot contain ',' (comma) character");
522 if (access (filename, F_OK) == -1) {
523 perrorf (g, "%s", filename);
527 return guestfs_config (g, "-cdrom", filename);
531 guestfs_launch (guestfs_h *g)
533 static const char *dir_template = "/tmp/libguestfsXXXXXX";
534 int r, i, len, pmore;
537 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
538 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
539 char *path, *pelem, *pend;
540 char *kernel = NULL, *initrd = NULL;
542 struct sockaddr_un addr;
546 error (g, "you must call guestfs_add_drive before guestfs_launch");
550 if (g->state != CONFIG) {
551 error (g, "qemu has already been launched");
555 /* Search g->path for the kernel and initrd. */
556 pelem = path = safe_strdup (g, g->path);
558 pend = strchrnul (pelem, ':');
559 pmore = *pend == ':';
563 /* Empty element or "." means cwd. */
564 if (len == 0 || (len == 1 && *pelem == '.')) {
567 "looking for kernel and initrd in current directory\n");
568 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
569 kernel = safe_strdup (g, kernel_name);
570 initrd = safe_strdup (g, initrd_name);
574 /* Look at <path>/kernel etc. */
576 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
577 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
578 sprintf (kernel, "%s/%s", pelem, kernel_name);
579 sprintf (initrd, "%s/%s", pelem, initrd_name);
582 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
584 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
588 kernel = initrd = NULL;
596 if (kernel == NULL || initrd == NULL) {
597 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
598 kernel_name, initrd_name, g->path);
602 /* Make the temporary directory containing the socket. */
604 g->tmpdir = safe_strdup (g, dir_template);
605 if (mkdtemp (g->tmpdir) == NULL) {
606 perrorf (g, "%s: cannot create temporary directory", dir_template);
611 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
614 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
629 if (r == 0) { /* Child (qemu). */
633 /* Set up the full command line. Do this in the subprocess so we
634 * don't need to worry about cleaning up.
636 g->cmdline[0] = (char *) QEMU;
638 /* Construct the -net channel parameter for qemu. */
639 snprintf (vmchannel, sizeof vmchannel,
640 "channel,%d:unix:%s,server,nowait",
641 VMCHANNEL_PORT, unixsock);
643 /* Linux kernel command line. */
644 snprintf (append, sizeof append,
645 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
647 add_cmdline (g, "-m");
648 add_cmdline (g, "384"); /* XXX Choose best size. */
649 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
650 add_cmdline (g, "-kernel");
651 add_cmdline (g, (char *) kernel);
652 add_cmdline (g, "-initrd");
653 add_cmdline (g, (char *) initrd);
654 add_cmdline (g, "-append");
655 add_cmdline (g, append);
656 add_cmdline (g, "-nographic");
657 add_cmdline (g, "-serial");
658 add_cmdline (g, "stdio");
659 add_cmdline (g, "-net");
660 add_cmdline (g, vmchannel);
661 add_cmdline (g, "-net");
662 add_cmdline (g, "user,vlan=0");
663 add_cmdline (g, "-net");
664 add_cmdline (g, "nic,vlan=0");
665 incr_cmdline_size (g);
666 g->cmdline[g->cmdline_size-1] = NULL;
669 fprintf (stderr, "%s", QEMU);
670 for (i = 0; g->cmdline[i]; ++i)
671 fprintf (stderr, " %s", g->cmdline[i]);
672 fprintf (stderr, "\n");
675 /* Set up stdin, stdout. */
686 /* Set up a new process group, so we can signal this process
687 * and all subprocesses (eg. if qemu is really a shell script).
692 execv (QEMU, g->cmdline); /* Run qemu. */
697 /* Parent (library). */
700 /* Start the clock ... */
703 /* Close the other ends of the pipe. */
707 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
708 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
709 perrorf (g, "fcntl");
713 g->fd[0] = wfd[1]; /* stdin of child */
714 g->fd[1] = rfd[0]; /* stdout of child */
716 /* Open the Unix socket. The vmchannel implementation that got
717 * merged with qemu sucks in a number of ways. Both ends do
718 * connect(2), which means that no one knows what, if anything, is
719 * connected to the other end, or if it becomes disconnected. Even
720 * worse, we have to wait some indeterminate time for qemu to create
721 * the socket and connect to it (which happens very early in qemu's
722 * start-up), so any code that uses vmchannel is inherently racy.
723 * Hence this silly loop.
725 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
727 perrorf (g, "socket");
731 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
732 perrorf (g, "fcntl");
736 addr.sun_family = AF_UNIX;
737 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
738 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
742 /* Always sleep at least once to give qemu a small chance to start up. */
745 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
746 if ((r == -1 && errno == EINPROGRESS) || r == 0)
750 perrorf (g, "connect");
754 error (g, "failed to connect to vmchannel socket");
758 /* Watch the file descriptors. */
761 g->msg_in_size = g->msg_in_allocated = 0;
769 main_loop.add_handle (g, g->fd[1],
770 GUESTFS_HANDLE_READABLE,
772 if (g->stdout_watch == -1) {
773 error (g, "could not watch qemu stdout");
778 main_loop.add_handle (g, g->sock,
779 GUESTFS_HANDLE_READABLE,
781 if (g->sock_watch == -1) {
782 error (g, "could not watch daemon communications socket");
786 g->state = LAUNCHING;
790 if (g->stdout_watch >= 0)
791 main_loop.remove_handle (g, g->stdout_watch);
792 if (g->sock_watch >= 0)
793 main_loop.remove_handle (g, g->sock_watch);
802 waitpid (g->pid, NULL, 0);
808 g->stdout_watch = -1;
818 finish_wait_ready (guestfs_h *g, void *vp)
821 main_loop.main_loop_quit (g);
825 guestfs_wait_ready (guestfs_h *g)
829 if (g->state == READY) return 0;
831 if (g->state == BUSY) {
832 error (g, "qemu has finished launching already");
836 if (g->state != LAUNCHING) {
837 error (g, "qemu has not been launched yet");
841 g->launch_done_cb_internal = finish_wait_ready;
842 g->launch_done_cb_internal_data = &r;
843 main_loop.main_loop_run (g);
844 g->launch_done_cb_internal = NULL;
845 g->launch_done_cb_internal_data = NULL;
848 error (g, "guestfs_wait_ready failed, see earlier error messages");
852 /* This is possible in some really strange situations, such as
853 * guestfsd starts up OK but then qemu immediately exits. Check for
854 * it because the caller is probably expecting to be able to send
855 * commands after this function returns.
857 if (g->state != READY) {
858 error (g, "qemu launched and contacted daemon, but state != READY");
866 guestfs_kill_subprocess (guestfs_h *g)
868 if (g->state == CONFIG) {
869 error (g, "no subprocess to kill");
874 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
876 kill (g->pid, SIGTERM);
881 /* This function is called whenever qemu prints something on stdout.
882 * Qemu's stdout is also connected to the guest's serial console, so
883 * we see kernel messages here too.
886 stdout_event (void *data, int watch, int fd, int events)
888 guestfs_h *g = (guestfs_h *) data;
895 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
896 g, g->state, fd, events);
899 if (g->fd[1] != fd) {
900 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
904 n = read (fd, buf, sizeof buf);
906 /* Hopefully this indicates the qemu child process has died. */
908 fprintf (stderr, "stdout_event: %p: child process died\n", g);
909 /*kill (g->pid, SIGTERM);*/
910 waitpid (g->pid, NULL, 0);
911 if (g->stdout_watch >= 0)
912 main_loop.remove_handle (g, g->stdout_watch);
913 if (g->sock_watch >= 0)
914 main_loop.remove_handle (g, g->sock_watch);
923 g->stdout_watch = -1;
926 if (g->subprocess_quit_cb)
927 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
937 /* In verbose mode, copy all log messages to stderr. */
941 /* It's an actual log message, send it upwards if anyone is listening. */
942 if (g->log_message_cb)
943 g->log_message_cb (g, g->log_message_cb_data, buf, n);
946 /* The function is called whenever we can read something on the
947 * guestfsd (daemon inside the guest) communication socket.
950 sock_read_event (void *data, int watch, int fd, int events)
952 guestfs_h *g = (guestfs_h *) data;
959 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
960 g, g->state, fd, events);
963 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
967 if (g->msg_in_size <= g->msg_in_allocated) {
968 g->msg_in_allocated += 4096;
969 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
971 n = read (g->sock, g->msg_in + g->msg_in_size,
972 g->msg_in_allocated - g->msg_in_size);
974 /* Disconnected? Ignore it because stdout_watch will get called
975 * and will do the cleanup.
987 /* Have we got enough of a message to be able to process it yet? */
988 if (g->msg_in_size < 4) return;
990 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
991 if (!xdr_uint32_t (&xdr, &len)) {
992 error (g, "can't decode length word");
996 /* Length is normally the length of the message, but when guestfsd
997 * starts up it sends a "magic" value (longer than any possible
998 * message). Check for this.
1000 if (len == 0xf5f55ff5) {
1001 if (g->state != LAUNCHING)
1002 error (g, "received magic signature from guestfsd, but in state %d",
1004 else if (g->msg_in_size != 4)
1005 error (g, "received magic signature from guestfsd, but msg size is %d",
1009 if (g->launch_done_cb_internal)
1010 g->launch_done_cb_internal (g, g->launch_done_cb_internal_data);
1011 if (g->launch_done_cb)
1012 g->launch_done_cb (g, g->launch_done_cb_data);
1018 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1019 if (len > GUESTFS_MESSAGE_MAX) {
1020 error (g, "message length (%u) > maximum possible size (%d)",
1021 len, GUESTFS_MESSAGE_MAX);
1025 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1027 /* This should not happen, and if it does it probably means we've
1028 * lost all hope of synchronization.
1030 if (g->msg_in_size-4 > len) {
1031 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1035 /* Got the full message, begin processing it. */
1039 for (i = 0; i < g->msg_in_size; i += 16) {
1040 printf ("%04x: ", i);
1041 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1042 printf ("%02x ", (unsigned char) g->msg_in[j]);
1043 for (; j < i+16; ++j)
1046 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1047 if (isprint (g->msg_in[j]))
1048 printf ("%c", g->msg_in[j]);
1051 for (; j < i+16; ++j)
1057 /* Not in the expected state. */
1058 if (g->state != BUSY)
1059 error (g, "state %d != BUSY", g->state);
1061 /* Push the message up to the higher layer. Note that unlike
1062 * launch_done_cb / launch_done_cb_internal, we only call at
1063 * most one of the callback functions here.
1066 if (g->reply_cb_internal)
1067 g->reply_cb_internal (g, g->reply_cb_internal_data, &xdr);
1068 else if (g->reply_cb)
1069 g->reply_cb (g, g->reply_cb, &xdr);
1072 /* Free the message buffer if it's grown excessively large. */
1073 if (g->msg_in_allocated > 65536) {
1076 g->msg_in_size = g->msg_in_allocated = 0;
1083 /* The function is called whenever we can write something on the
1084 * guestfsd (daemon inside the guest) communication socket.
1087 sock_write_event (void *data, int watch, int fd, int events)
1089 guestfs_h *g = (guestfs_h *) data;
1094 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1095 g, g->state, fd, events);
1097 if (g->sock != fd) {
1098 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1102 if (g->state != BUSY) {
1103 error (g, "sock_write_event: state %d != BUSY", g->state);
1108 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1109 g->msg_out_size - g->msg_out_pos);
1111 n = write (g->sock, g->msg_out + g->msg_out_pos,
1112 g->msg_out_size - g->msg_out_pos);
1114 if (errno != EAGAIN)
1115 perrorf (g, "write");
1120 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1122 g->msg_out_pos += n;
1124 /* More to write? */
1125 if (g->msg_out_pos < g->msg_out_size)
1129 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1132 g->msg_out_pos = g->msg_out_size = 0;
1134 if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1135 error (g, "remove_handle failed in sock_write_event");
1139 main_loop.add_handle (g, g->sock,
1140 GUESTFS_HANDLE_READABLE,
1141 sock_read_event, g);
1142 if (g->sock_watch == -1) {
1143 error (g, "add_handle failed in sock_write_event");
1148 /* Dispatch a call to the remote daemon. This function just queues
1149 * the call in msg_out, to be sent when we next enter the main loop.
1150 * Returns -1 for error, or the message serial number.
1153 dispatch (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1155 char buffer[GUESTFS_MESSAGE_MAX];
1156 struct guestfs_message_header hdr;
1159 int serial = g->msg_next_serial++;
1161 if (g->state != READY) {
1162 error (g, "dispatch: state %d != READY", g->state);
1166 /* Serialize the header. */
1167 hdr.prog = GUESTFS_PROGRAM;
1168 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1170 hdr.direction = GUESTFS_DIRECTION_CALL;
1171 hdr.serial = serial;
1172 hdr.status = GUESTFS_STATUS_OK;
1174 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1175 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1176 error (g, "xdr_guestfs_message_header failed");
1180 /* Serialize the args. If any, because some message types
1181 * have no parameters.
1184 if (!(*xdrp) (&xdr, args)) {
1185 error (g, "dispatch failed to marshal args");
1190 len = xdr_getpos (&xdr);
1193 /* Allocate the outgoing message buffer. */
1194 g->msg_out = safe_malloc (g, len + 4);
1196 g->msg_out_size = len + 4;
1200 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1201 if (!xdr_uint32_t (&xdr, &len)) {
1202 error (g, "xdr_uint32_t failed in dispatch");
1206 memcpy (g->msg_out + 4, buffer, len);
1208 /* Change the handle to sock_write_event. */
1209 if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1210 error (g, "remove_handle failed in dispatch");
1214 main_loop.add_handle (g, g->sock,
1215 GUESTFS_HANDLE_WRITABLE,
1216 sock_write_event, g);
1217 if (g->sock_watch == -1) {
1218 error (g, "add_handle failed in dispatch");
1227 g->msg_out_size = 0;
1232 /* Check the return message from a call for validity. */
1234 check_reply_header (guestfs_h *g,
1235 const struct guestfs_message_header *hdr,
1236 int proc_nr, int serial)
1238 if (hdr->prog != GUESTFS_PROGRAM) {
1239 error (g, "wrong program (%d/%d)", hdr->prog, GUESTFS_PROGRAM);
1242 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
1243 error (g, "wrong protocol version (%d/%d)",
1244 hdr->vers, GUESTFS_PROTOCOL_VERSION);
1247 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
1248 error (g, "unexpected message direction (%d/%d)",
1249 hdr->direction, GUESTFS_DIRECTION_REPLY);
1252 if (hdr->proc != proc_nr) {
1253 error (g, "unexpected procedure number (%d/%d)", hdr->proc, proc_nr);
1256 if (hdr->serial != serial) {
1257 error (g, "unexpected serial (%d/%d)", hdr->serial, serial);
1264 /* The high-level actions are autogenerated by generator.ml. Include
1267 #include "guestfs-actions.c"
1269 /* Structure-freeing functions. These rely on the fact that the
1270 * structure format is identical to the XDR format. See note in
1274 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1276 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1281 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1283 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1288 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1290 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1294 /* This is the default main loop implementation, using select(2). */
1296 struct handle_cb_data {
1297 guestfs_handle_event_cb cb;
1304 static int select_init_done = 0;
1305 static int max_fd = -1;
1306 static int nr_fds = 0;
1307 static struct handle_cb_data *handle_cb_data = NULL;
1312 if (!select_init_done) {
1317 select_init_done = 1;
1322 select_add_handle (guestfs_h *g, int fd, int events,
1323 guestfs_handle_event_cb cb, void *data)
1327 if (fd < 0 || fd >= FD_SETSIZE) {
1328 error (g, "fd %d is out of range", fd);
1332 if ((events & ~(GUESTFS_HANDLE_READABLE |
1333 GUESTFS_HANDLE_WRITABLE |
1334 GUESTFS_HANDLE_HANGUP |
1335 GUESTFS_HANDLE_ERROR)) != 0) {
1336 error (g, "set of events (0x%x) contains unknown events", events);
1341 error (g, "set of events is empty");
1345 if (FD_ISSET (fd, &rset) || FD_ISSET (fd, &wset) || FD_ISSET (fd, &xset)) {
1346 error (g, "fd %d is already registered", fd);
1351 error (g, "callback is NULL");
1355 if ((events & GUESTFS_HANDLE_READABLE))
1357 if ((events & GUESTFS_HANDLE_WRITABLE))
1359 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1364 handle_cb_data = safe_realloc (g, handle_cb_data,
1365 sizeof (struct handle_cb_data) * (max_fd+1));
1367 handle_cb_data[fd].cb = cb;
1368 handle_cb_data[fd].data = data;
1372 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1377 select_remove_handle (guestfs_h *g, int fd)
1381 if (fd < 0 || fd >= FD_SETSIZE) {
1382 error (g, "fd %d is out of range", fd);
1386 if (!FD_ISSET (fd, &rset) && !FD_ISSET (fd, &wset) && !FD_ISSET (fd, &xset)) {
1387 error (g, "fd %d was not registered", fd);
1397 handle_cb_data = safe_realloc (g, handle_cb_data,
1398 sizeof (struct handle_cb_data) * (max_fd+1));
1407 select_add_timeout (guestfs_h *g, int interval,
1408 guestfs_handle_timeout_cb cb, void *data)
1412 abort (); /* XXX not implemented yet */
1416 select_remove_timeout (guestfs_h *g, int timer)
1420 abort (); /* XXX not implemented yet */
1423 /* Note that main loops can be nested. */
1424 static int level = 0;
1427 select_main_loop_run (guestfs_h *g)
1429 int old_level, fd, r, events;
1430 fd_set rset2, wset2, xset2;
1434 old_level = level++;
1435 while (level > old_level) {
1444 r = select (max_fd+1, &rset2, &wset2, &xset2, NULL);
1446 perrorf (g, "select");
1451 for (fd = 0; r > 0 && fd <= max_fd; ++fd) {
1453 if (FD_ISSET (fd, &rset2))
1454 events |= GUESTFS_HANDLE_READABLE;
1455 if (FD_ISSET (fd, &wset2))
1456 events |= GUESTFS_HANDLE_WRITABLE;
1457 if (FD_ISSET (fd, &xset2))
1458 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1461 handle_cb_data[fd].cb (handle_cb_data[fd].data,
1469 select_main_loop_quit (guestfs_h *g)
1474 error (g, "cannot quit, we are not in a main loop");