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)
397 guestfs_get_verbose (guestfs_h *g)
403 guestfs_set_autosync (guestfs_h *g, int a)
409 guestfs_get_autosync (guestfs_h *g)
415 guestfs_set_path (guestfs_h *g, const char *path)
418 g->path = GUESTFS_DEFAULT_PATH;
424 guestfs_get_path (guestfs_h *g)
429 /* Add a string to the current command line. */
431 incr_cmdline_size (guestfs_h *g)
433 if (g->cmdline == NULL) {
434 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
436 g->cmdline = safe_malloc (g, sizeof (char *));
437 g->cmdline[0] = NULL;
441 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
445 add_cmdline (guestfs_h *g, const char *str)
447 if (g->state != CONFIG) {
448 error (g, "command line cannot be altered after qemu subprocess launched");
452 incr_cmdline_size (g);
453 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
458 guestfs_config (guestfs_h *g,
459 const char *qemu_param, const char *qemu_value)
461 if (qemu_param[0] != '-') {
462 error (g, "guestfs_config: parameter must begin with '-' character");
466 /* A bit fascist, but the user will probably break the extra
467 * parameters that we add if they try to set any of these.
469 if (strcmp (qemu_param, "-kernel") == 0 ||
470 strcmp (qemu_param, "-initrd") == 0 ||
471 strcmp (qemu_param, "-nographic") == 0 ||
472 strcmp (qemu_param, "-serial") == 0 ||
473 strcmp (qemu_param, "-vnc") == 0 ||
474 strcmp (qemu_param, "-full-screen") == 0 ||
475 strcmp (qemu_param, "-std-vga") == 0 ||
476 strcmp (qemu_param, "-vnc") == 0) {
477 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
481 if (add_cmdline (g, qemu_param) != 0) return -1;
483 if (qemu_value != NULL) {
484 if (add_cmdline (g, qemu_value) != 0) return -1;
491 guestfs_add_drive (guestfs_h *g, const char *filename)
493 int len = strlen (filename) + 64;
496 if (strchr (filename, ',') != NULL) {
497 error (g, "filename cannot contain ',' (comma) character");
501 if (access (filename, F_OK) == -1) {
502 perrorf (g, "%s", filename);
506 snprintf (buf, len, "file=%s", filename);
508 return guestfs_config (g, "-drive", buf);
512 guestfs_add_cdrom (guestfs_h *g, const char *filename)
514 if (strchr (filename, ',') != NULL) {
515 error (g, "filename cannot contain ',' (comma) character");
519 if (access (filename, F_OK) == -1) {
520 perrorf (g, "%s", filename);
524 return guestfs_config (g, "-cdrom", filename);
528 guestfs_launch (guestfs_h *g)
530 static const char *dir_template = "/tmp/libguestfsXXXXXX";
531 int r, i, len, pmore;
534 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
535 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
536 char *path, *pelem, *pend;
537 char *kernel = NULL, *initrd = NULL;
539 struct sockaddr_un addr;
543 error (g, "you must call guestfs_add_drive before guestfs_launch");
547 if (g->state != CONFIG) {
548 error (g, "qemu has already been launched");
552 /* Search g->path for the kernel and initrd. */
553 pelem = path = safe_strdup (g, g->path);
555 pend = strchrnul (pelem, ':');
556 pmore = *pend == ':';
560 /* Empty element or "." means cwd. */
561 if (len == 0 || (len == 1 && *pelem == '.')) {
564 "looking for kernel and initrd in current directory\n");
565 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
566 kernel = safe_strdup (g, kernel_name);
567 initrd = safe_strdup (g, initrd_name);
571 /* Look at <path>/kernel etc. */
573 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
574 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
575 sprintf (kernel, "%s/%s", pelem, kernel_name);
576 sprintf (initrd, "%s/%s", pelem, initrd_name);
579 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
581 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
585 kernel = initrd = NULL;
593 if (kernel == NULL || initrd == NULL) {
594 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
595 kernel_name, initrd_name, g->path);
599 /* Make the temporary directory containing the socket. */
601 g->tmpdir = safe_strdup (g, dir_template);
602 if (mkdtemp (g->tmpdir) == NULL) {
603 perrorf (g, "%s: cannot create temporary directory", dir_template);
608 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
611 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
626 if (r == 0) { /* Child (qemu). */
630 /* Set up the full command line. Do this in the subprocess so we
631 * don't need to worry about cleaning up.
633 g->cmdline[0] = (char *) QEMU;
635 /* Construct the -net channel parameter for qemu. */
636 snprintf (vmchannel, sizeof vmchannel,
637 "channel,%d:unix:%s,server,nowait",
638 VMCHANNEL_PORT, unixsock);
640 /* Linux kernel command line. */
641 snprintf (append, sizeof append,
642 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
644 add_cmdline (g, "-m");
645 add_cmdline (g, "384"); /* XXX Choose best size. */
646 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
647 add_cmdline (g, "-kernel");
648 add_cmdline (g, (char *) kernel);
649 add_cmdline (g, "-initrd");
650 add_cmdline (g, (char *) initrd);
651 add_cmdline (g, "-append");
652 add_cmdline (g, append);
653 add_cmdline (g, "-nographic");
654 add_cmdline (g, "-serial");
655 add_cmdline (g, "stdio");
656 add_cmdline (g, "-net");
657 add_cmdline (g, vmchannel);
658 add_cmdline (g, "-net");
659 add_cmdline (g, "user,vlan=0");
660 add_cmdline (g, "-net");
661 add_cmdline (g, "nic,vlan=0");
662 incr_cmdline_size (g);
663 g->cmdline[g->cmdline_size-1] = NULL;
666 fprintf (stderr, "%s", QEMU);
667 for (i = 0; g->cmdline[i]; ++i)
668 fprintf (stderr, " %s", g->cmdline[i]);
669 fprintf (stderr, "\n");
672 /* Set up stdin, stdout. */
683 /* Set up a new process group, so we can signal this process
684 * and all subprocesses (eg. if qemu is really a shell script).
689 execv (QEMU, g->cmdline); /* Run qemu. */
694 /* Parent (library). */
697 /* Start the clock ... */
700 /* Close the other ends of the pipe. */
704 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
705 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
706 perrorf (g, "fcntl");
710 g->fd[0] = wfd[1]; /* stdin of child */
711 g->fd[1] = rfd[0]; /* stdout of child */
713 /* Open the Unix socket. The vmchannel implementation that got
714 * merged with qemu sucks in a number of ways. Both ends do
715 * connect(2), which means that no one knows what, if anything, is
716 * connected to the other end, or if it becomes disconnected. Even
717 * worse, we have to wait some indeterminate time for qemu to create
718 * the socket and connect to it (which happens very early in qemu's
719 * start-up), so any code that uses vmchannel is inherently racy.
720 * Hence this silly loop.
722 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
724 perrorf (g, "socket");
728 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
729 perrorf (g, "fcntl");
733 addr.sun_family = AF_UNIX;
734 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
735 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
739 /* Always sleep at least once to give qemu a small chance to start up. */
742 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
743 if ((r == -1 && errno == EINPROGRESS) || r == 0)
747 perrorf (g, "connect");
751 error (g, "failed to connect to vmchannel socket");
755 /* Watch the file descriptors. */
758 g->msg_in_size = g->msg_in_allocated = 0;
766 main_loop.add_handle (g, g->fd[1],
767 GUESTFS_HANDLE_READABLE,
769 if (g->stdout_watch == -1) {
770 error (g, "could not watch qemu stdout");
775 main_loop.add_handle (g, g->sock,
776 GUESTFS_HANDLE_READABLE,
778 if (g->sock_watch == -1) {
779 error (g, "could not watch daemon communications socket");
783 g->state = LAUNCHING;
787 if (g->stdout_watch >= 0)
788 main_loop.remove_handle (g, g->stdout_watch);
789 if (g->sock_watch >= 0)
790 main_loop.remove_handle (g, g->sock_watch);
799 waitpid (g->pid, NULL, 0);
805 g->stdout_watch = -1;
815 finish_wait_ready (guestfs_h *g, void *vp)
818 main_loop.main_loop_quit (g);
822 guestfs_wait_ready (guestfs_h *g)
826 if (g->state == READY) return 0;
828 if (g->state == BUSY) {
829 error (g, "qemu has finished launching already");
833 if (g->state != LAUNCHING) {
834 error (g, "qemu has not been launched yet");
838 g->launch_done_cb_internal = finish_wait_ready;
839 g->launch_done_cb_internal_data = &r;
840 main_loop.main_loop_run (g);
841 g->launch_done_cb_internal = NULL;
842 g->launch_done_cb_internal_data = NULL;
845 error (g, "guestfs_wait_ready failed, see earlier error messages");
849 /* This is possible in some really strange situations, such as
850 * guestfsd starts up OK but then qemu immediately exits. Check for
851 * it because the caller is probably expecting to be able to send
852 * commands after this function returns.
854 if (g->state != READY) {
855 error (g, "qemu launched and contacted daemon, but state != READY");
863 guestfs_kill_subprocess (guestfs_h *g)
865 if (g->state == CONFIG) {
866 error (g, "no subprocess to kill");
871 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
873 kill (g->pid, SIGTERM);
878 /* This function is called whenever qemu prints something on stdout.
879 * Qemu's stdout is also connected to the guest's serial console, so
880 * we see kernel messages here too.
883 stdout_event (void *data, int watch, int fd, int events)
885 guestfs_h *g = (guestfs_h *) data;
892 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
893 g, g->state, fd, events);
896 if (g->fd[1] != fd) {
897 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
901 n = read (fd, buf, sizeof buf);
903 /* Hopefully this indicates the qemu child process has died. */
905 fprintf (stderr, "stdout_event: %p: child process died\n", g);
906 /*kill (g->pid, SIGTERM);*/
907 waitpid (g->pid, NULL, 0);
908 if (g->stdout_watch >= 0)
909 main_loop.remove_handle (g, g->stdout_watch);
910 if (g->sock_watch >= 0)
911 main_loop.remove_handle (g, g->sock_watch);
920 g->stdout_watch = -1;
923 if (g->subprocess_quit_cb)
924 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
934 /* In verbose mode, copy all log messages to stderr. */
938 /* It's an actual log message, send it upwards if anyone is listening. */
939 if (g->log_message_cb)
940 g->log_message_cb (g, g->log_message_cb_data, buf, n);
943 /* The function is called whenever we can read something on the
944 * guestfsd (daemon inside the guest) communication socket.
947 sock_read_event (void *data, int watch, int fd, int events)
949 guestfs_h *g = (guestfs_h *) data;
956 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
957 g, g->state, fd, events);
960 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
964 if (g->msg_in_size <= g->msg_in_allocated) {
965 g->msg_in_allocated += 4096;
966 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
968 n = read (g->sock, g->msg_in + g->msg_in_size,
969 g->msg_in_allocated - g->msg_in_size);
971 /* Disconnected? Ignore it because stdout_watch will get called
972 * and will do the cleanup.
984 /* Have we got enough of a message to be able to process it yet? */
985 if (g->msg_in_size < 4) return;
987 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
988 if (!xdr_uint32_t (&xdr, &len)) {
989 error (g, "can't decode length word");
993 /* Length is normally the length of the message, but when guestfsd
994 * starts up it sends a "magic" value (longer than any possible
995 * message). Check for this.
997 if (len == 0xf5f55ff5) {
998 if (g->state != LAUNCHING)
999 error (g, "received magic signature from guestfsd, but in state %d",
1001 else if (g->msg_in_size != 4)
1002 error (g, "received magic signature from guestfsd, but msg size is %d",
1006 if (g->launch_done_cb_internal)
1007 g->launch_done_cb_internal (g, g->launch_done_cb_internal_data);
1008 if (g->launch_done_cb)
1009 g->launch_done_cb (g, g->launch_done_cb_data);
1015 /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1016 if (len > GUESTFS_MESSAGE_MAX) {
1017 error (g, "message length (%u) > maximum possible size (%d)",
1018 len, GUESTFS_MESSAGE_MAX);
1022 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1024 /* This should not happen, and if it does it probably means we've
1025 * lost all hope of synchronization.
1027 if (g->msg_in_size-4 > len) {
1028 error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1032 /* Got the full message, begin processing it. */
1036 for (i = 0; i < g->msg_in_size; i += 16) {
1037 printf ("%04x: ", i);
1038 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1039 printf ("%02x ", (unsigned char) g->msg_in[j]);
1040 for (; j < i+16; ++j)
1043 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1044 if (isprint (g->msg_in[j]))
1045 printf ("%c", g->msg_in[j]);
1048 for (; j < i+16; ++j)
1054 /* Not in the expected state. */
1055 if (g->state != BUSY)
1056 error (g, "state %d != BUSY", g->state);
1058 /* Push the message up to the higher layer. Note that unlike
1059 * launch_done_cb / launch_done_cb_internal, we only call at
1060 * most one of the callback functions here.
1063 if (g->reply_cb_internal)
1064 g->reply_cb_internal (g, g->reply_cb_internal_data, &xdr);
1065 else if (g->reply_cb)
1066 g->reply_cb (g, g->reply_cb, &xdr);
1069 /* Free the message buffer if it's grown excessively large. */
1070 if (g->msg_in_allocated > 65536) {
1073 g->msg_in_size = g->msg_in_allocated = 0;
1080 /* The function is called whenever we can write something on the
1081 * guestfsd (daemon inside the guest) communication socket.
1084 sock_write_event (void *data, int watch, int fd, int events)
1086 guestfs_h *g = (guestfs_h *) data;
1091 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1092 g, g->state, fd, events);
1094 if (g->sock != fd) {
1095 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1099 if (g->state != BUSY) {
1100 error (g, "sock_write_event: state %d != BUSY", g->state);
1105 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1106 g->msg_out_size - g->msg_out_pos);
1108 n = write (g->sock, g->msg_out + g->msg_out_pos,
1109 g->msg_out_size - g->msg_out_pos);
1111 if (errno != EAGAIN)
1112 perrorf (g, "write");
1117 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1119 g->msg_out_pos += n;
1121 /* More to write? */
1122 if (g->msg_out_pos < g->msg_out_size)
1126 fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1129 g->msg_out_pos = g->msg_out_size = 0;
1131 if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1132 error (g, "remove_handle failed in sock_write_event");
1136 main_loop.add_handle (g, g->sock,
1137 GUESTFS_HANDLE_READABLE,
1138 sock_read_event, g);
1139 if (g->sock_watch == -1) {
1140 error (g, "add_handle failed in sock_write_event");
1145 /* Dispatch a call to the remote daemon. This function just queues
1146 * the call in msg_out, to be sent when we next enter the main loop.
1147 * Returns -1 for error, or the message serial number.
1150 dispatch (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1152 char buffer[GUESTFS_MESSAGE_MAX];
1153 struct guestfs_message_header hdr;
1156 int serial = g->msg_next_serial++;
1158 if (g->state != READY) {
1159 error (g, "dispatch: state %d != READY", g->state);
1163 /* Serialize the header. */
1164 hdr.prog = GUESTFS_PROGRAM;
1165 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1167 hdr.direction = GUESTFS_DIRECTION_CALL;
1168 hdr.serial = serial;
1169 hdr.status = GUESTFS_STATUS_OK;
1171 xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1172 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1173 error (g, "xdr_guestfs_message_header failed");
1177 /* Serialize the args. If any, because some message types
1178 * have no parameters.
1181 if (!(*xdrp) (&xdr, args)) {
1182 error (g, "dispatch failed to marshal args");
1187 len = xdr_getpos (&xdr);
1190 /* Allocate the outgoing message buffer. */
1191 g->msg_out = safe_malloc (g, len + 4);
1193 g->msg_out_size = len + 4;
1197 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1198 if (!xdr_uint32_t (&xdr, &len)) {
1199 error (g, "xdr_uint32_t failed in dispatch");
1203 memcpy (g->msg_out + 4, buffer, len);
1205 /* Change the handle to sock_write_event. */
1206 if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1207 error (g, "remove_handle failed in dispatch");
1211 main_loop.add_handle (g, g->sock,
1212 GUESTFS_HANDLE_WRITABLE,
1213 sock_write_event, g);
1214 if (g->sock_watch == -1) {
1215 error (g, "add_handle failed in dispatch");
1224 g->msg_out_size = 0;
1229 /* Check the return message from a call for validity. */
1231 check_reply_header (guestfs_h *g,
1232 const struct guestfs_message_header *hdr,
1233 int proc_nr, int serial)
1235 if (hdr->prog != GUESTFS_PROGRAM) {
1236 error (g, "wrong program (%d/%d)", hdr->prog, GUESTFS_PROGRAM);
1239 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
1240 error (g, "wrong protocol version (%d/%d)",
1241 hdr->vers, GUESTFS_PROTOCOL_VERSION);
1244 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
1245 error (g, "unexpected message direction (%d/%d)",
1246 hdr->direction, GUESTFS_DIRECTION_REPLY);
1249 if (hdr->proc != proc_nr) {
1250 error (g, "unexpected procedure number (%d/%d)", hdr->proc, proc_nr);
1253 if (hdr->serial != serial) {
1254 error (g, "unexpected serial (%d/%d)", hdr->serial, serial);
1261 /* The high-level actions are autogenerated by generator.ml. Include
1264 #include "guestfs-actions.c"
1266 /* Structure-freeing functions. These rely on the fact that the
1267 * structure format is identical to the XDR format. See note in
1271 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1273 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1278 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1280 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1285 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1287 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1291 /* This is the default main loop implementation, using select(2). */
1293 struct handle_cb_data {
1294 guestfs_handle_event_cb cb;
1301 static int select_init_done = 0;
1302 static int max_fd = -1;
1303 static int nr_fds = 0;
1304 static struct handle_cb_data *handle_cb_data = NULL;
1309 if (!select_init_done) {
1314 select_init_done = 1;
1319 select_add_handle (guestfs_h *g, int fd, int events,
1320 guestfs_handle_event_cb cb, void *data)
1324 if (fd < 0 || fd >= FD_SETSIZE) {
1325 error (g, "fd %d is out of range", fd);
1329 if ((events & ~(GUESTFS_HANDLE_READABLE |
1330 GUESTFS_HANDLE_WRITABLE |
1331 GUESTFS_HANDLE_HANGUP |
1332 GUESTFS_HANDLE_ERROR)) != 0) {
1333 error (g, "set of events (0x%x) contains unknown events", events);
1338 error (g, "set of events is empty");
1342 if (FD_ISSET (fd, &rset) || FD_ISSET (fd, &wset) || FD_ISSET (fd, &xset)) {
1343 error (g, "fd %d is already registered", fd);
1348 error (g, "callback is NULL");
1352 if ((events & GUESTFS_HANDLE_READABLE))
1354 if ((events & GUESTFS_HANDLE_WRITABLE))
1356 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1361 handle_cb_data = safe_realloc (g, handle_cb_data,
1362 sizeof (struct handle_cb_data) * (max_fd+1));
1364 handle_cb_data[fd].cb = cb;
1365 handle_cb_data[fd].data = data;
1369 /* Any integer >= 0 can be the handle, and this is as good as any ... */
1374 select_remove_handle (guestfs_h *g, int fd)
1378 if (fd < 0 || fd >= FD_SETSIZE) {
1379 error (g, "fd %d is out of range", fd);
1383 if (!FD_ISSET (fd, &rset) && !FD_ISSET (fd, &wset) && !FD_ISSET (fd, &xset)) {
1384 error (g, "fd %d was not registered", fd);
1394 handle_cb_data = safe_realloc (g, handle_cb_data,
1395 sizeof (struct handle_cb_data) * (max_fd+1));
1404 select_add_timeout (guestfs_h *g, int interval,
1405 guestfs_handle_timeout_cb cb, void *data)
1409 abort (); /* XXX not implemented yet */
1413 select_remove_timeout (guestfs_h *g, int timer)
1417 abort (); /* XXX not implemented yet */
1420 /* Note that main loops can be nested. */
1421 static int level = 0;
1424 select_main_loop_run (guestfs_h *g)
1426 int old_level, fd, r, events;
1427 fd_set rset2, wset2, xset2;
1431 old_level = level++;
1432 while (level > old_level) {
1441 r = select (max_fd+1, &rset2, &wset2, &xset2, NULL);
1443 perrorf (g, "select");
1448 for (fd = 0; r > 0 && fd <= max_fd; ++fd) {
1450 if (FD_ISSET (fd, &rset2))
1451 events |= GUESTFS_HANDLE_READABLE;
1452 if (FD_ISSET (fd, &wset2))
1453 events |= GUESTFS_HANDLE_WRITABLE;
1454 if (FD_ISSET (fd, &xset2))
1455 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1458 handle_cb_data[fd].cb (handle_cb_data[fd].data,
1466 select_main_loop_quit (guestfs_h *g)
1471 error (g, "cannot quit, we are not in a main loop");