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 */
33 #include <sys/select.h>
35 #include <rpc/types.h>
42 #ifdef HAVE_SYS_TYPES_H
43 #include <sys/types.h>
46 #ifdef HAVE_SYS_WAIT_H
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
59 #include "guestfs_protocol.h"
61 #define error guestfs_error
62 #define perrorf guestfs_perrorf
63 #define safe_malloc guestfs_safe_malloc
64 #define safe_realloc guestfs_safe_realloc
65 #define safe_strdup guestfs_safe_strdup
66 #define safe_memdup guestfs_safe_memdup
68 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
69 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
70 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
71 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
73 static void close_handles (void);
75 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
76 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
77 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
78 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
79 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
80 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
82 /* Default select-based main loop. */
83 struct select_handle_cb_data {
84 guestfs_handle_event_cb cb;
89 struct select_main_loop {
90 /* NB. These fields must be the same as in struct guestfs_main_loop: */
91 guestfs_add_handle_cb add_handle;
92 guestfs_remove_handle_cb remove_handle;
93 guestfs_add_timeout_cb add_timeout;
94 guestfs_remove_timeout_cb remove_timeout;
95 guestfs_main_loop_run_cb main_loop_run;
96 guestfs_main_loop_quit_cb main_loop_quit;
98 /* Additional private data: */
107 struct select_handle_cb_data *handle_cb_data;
110 /* Default main loop. */
111 static struct select_main_loop default_main_loop = {
112 .add_handle = select_add_handle,
113 .remove_handle = select_remove_handle,
114 .add_timeout = select_add_timeout,
115 .remove_timeout = select_remove_timeout,
116 .main_loop_run = select_main_loop_run,
117 .main_loop_quit = select_main_loop_quit,
119 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
120 * set by the normal action of everything being initialized to zero.
125 .handle_cb_data = NULL,
128 #define UNIX_PATH_MAX 108
130 /* Also in guestfsd.c */
131 #define VMCHANNEL_PORT 6666
132 #define VMCHANNEL_ADDR "10.0.2.4"
134 /* GuestFS handle and connection. */
135 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
139 struct guestfs_h *next; /* Linked list of open handles. */
141 /* State: see the state machine diagram in the man page guestfs(3). */
144 int fd[2]; /* Stdin/stdout of qemu. */
145 int sock; /* Daemon communications socket. */
146 pid_t pid; /* Qemu PID. */
147 pid_t recoverypid; /* Recovery process PID. */
148 time_t start_t; /* The time when we started qemu. */
150 int stdout_watch; /* Watches qemu stdout for log messages. */
151 int sock_watch; /* Watches daemon comm socket. */
153 char *tmpdir; /* Temporary directory containing socket. */
155 char **cmdline; /* Qemu command line. */
164 const char *append; /* Append to kernel command line. */
169 guestfs_abort_cb abort_cb;
170 guestfs_error_handler_cb error_cb;
171 void * error_cb_data;
172 guestfs_send_cb send_cb;
174 guestfs_reply_cb reply_cb;
175 void * reply_cb_data;
176 guestfs_log_message_cb log_message_cb;
177 void * log_message_cb_data;
178 guestfs_subprocess_quit_cb subprocess_quit_cb;
179 void * subprocess_quit_cb_data;
180 guestfs_launch_done_cb launch_done_cb;
181 void * launch_done_cb_data;
183 /* Main loop used by this handle. */
184 guestfs_main_loop *main_loop;
186 /* Messages sent and received from the daemon. */
188 int msg_in_size, msg_in_allocated;
190 int msg_out_size, msg_out_pos;
195 static guestfs_h *handles = NULL;
196 static int atexit_handler_set = 0;
199 guestfs_create (void)
204 g = malloc (sizeof (*g));
207 memset (g, 0, sizeof (*g));
214 g->stdout_watch = -1;
218 g->error_cb = default_error_cb;
219 g->error_cb_data = NULL;
221 str = getenv ("LIBGUESTFS_DEBUG");
222 g->verbose = str != NULL && strcmp (str, "1") == 0;
224 str = getenv ("LIBGUESTFS_PATH");
225 g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
227 str = getenv ("LIBGUESTFS_QEMU");
228 g->qemu = str != NULL ? str : QEMU;
230 str = getenv ("LIBGUESTFS_APPEND");
233 g->main_loop = guestfs_get_default_main_loop ();
235 /* Start with large serial numbers so they are easy to spot
236 * inside the protocol.
238 g->msg_next_serial = 0x00123400;
240 /* Link the handles onto a global list. This is the one area
241 * where the library needs to be made thread-safe. (XXX)
243 /* acquire mutex (XXX) */
246 if (!atexit_handler_set) {
247 atexit (close_handles);
248 atexit_handler_set = 1;
250 /* release mutex (XXX) */
253 fprintf (stderr, "new guestfs handle %p\n", g);
259 guestfs_close (guestfs_h *g)
265 if (g->state == NO_HANDLE) {
266 /* Not safe to call 'error' here, so ... */
267 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
272 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
274 /* Try to sync if autosync flag is set. */
275 if (g->autosync && g->state == READY) {
276 guestfs_umount_all (g);
280 /* Remove any handlers that might be called back before we kill the
283 g->log_message_cb = NULL;
285 if (g->state != CONFIG)
286 guestfs_kill_subprocess (g);
289 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
298 for (i = 0; i < g->cmdline_size; ++i)
299 free (g->cmdline[i]);
303 /* Mark the handle as dead before freeing it. */
304 g->state = NO_HANDLE;
306 /* acquire mutex (XXX) */
310 for (gg = handles; gg->next != g; gg = gg->next)
314 /* release mutex (XXX) */
318 free (g->last_error);
322 /* Close all open handles (called from atexit(3)). */
326 while (handles) guestfs_close (handles);
330 guestfs_last_error (guestfs_h *g)
332 return g->last_error;
336 set_last_error (guestfs_h *g, const char *msg)
338 free (g->last_error);
339 g->last_error = strdup (msg);
343 default_error_cb (guestfs_h *g, void *data, const char *msg)
345 fprintf (stderr, "libguestfs: error: %s\n", msg);
349 guestfs_error (guestfs_h *g, const char *fs, ...)
355 vasprintf (&msg, fs, args);
358 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
359 set_last_error (g, msg);
365 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
372 vasprintf (&msg, fs, args);
377 strerror_r (err, buf, sizeof buf);
381 buf = strerror_r (err, _buf, sizeof _buf);
384 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
388 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
389 set_last_error (g, msg);
395 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
397 void *ptr = malloc (nbytes);
398 if (!ptr) g->abort_cb ();
403 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
405 void *p = realloc (ptr, nbytes);
406 if (!p) g->abort_cb ();
411 guestfs_safe_strdup (guestfs_h *g, const char *str)
413 char *s = strdup (str);
414 if (!s) g->abort_cb ();
419 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
421 void *p = malloc (size);
422 if (!p) g->abort_cb ();
423 memcpy (p, ptr, size);
428 xwrite (int fd, const void *buf, size_t len)
433 r = write (fd, buf, len);
445 xread (int fd, void *buf, size_t len)
450 r = read (fd, buf, len);
452 if (errno == EINTR || errno == EAGAIN)
465 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
471 guestfs_get_out_of_memory_handler (guestfs_h *g)
477 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
480 g->error_cb_data = data;
483 guestfs_error_handler_cb
484 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
486 if (data_rtn) *data_rtn = g->error_cb_data;
491 guestfs_set_verbose (guestfs_h *g, int v)
498 guestfs_get_verbose (guestfs_h *g)
504 guestfs_set_autosync (guestfs_h *g, int a)
511 guestfs_get_autosync (guestfs_h *g)
517 guestfs_set_path (guestfs_h *g, const char *path)
520 g->path = GUESTFS_DEFAULT_PATH;
527 guestfs_get_path (guestfs_h *g)
533 guestfs_set_qemu (guestfs_h *g, const char *qemu)
543 guestfs_get_qemu (guestfs_h *g)
549 guestfs_set_append (guestfs_h *g, const char *append)
556 guestfs_get_append (guestfs_h *g)
561 /* Add a string to the current command line. */
563 incr_cmdline_size (guestfs_h *g)
565 if (g->cmdline == NULL) {
566 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
568 g->cmdline = safe_malloc (g, sizeof (char *));
569 g->cmdline[0] = NULL;
573 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
577 add_cmdline (guestfs_h *g, const char *str)
579 if (g->state != CONFIG) {
580 error (g, "command line cannot be altered after qemu subprocess launched");
584 incr_cmdline_size (g);
585 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
590 guestfs_config (guestfs_h *g,
591 const char *qemu_param, const char *qemu_value)
593 if (qemu_param[0] != '-') {
594 error (g, "guestfs_config: parameter must begin with '-' character");
598 /* A bit fascist, but the user will probably break the extra
599 * parameters that we add if they try to set any of these.
601 if (strcmp (qemu_param, "-kernel") == 0 ||
602 strcmp (qemu_param, "-initrd") == 0 ||
603 strcmp (qemu_param, "-nographic") == 0 ||
604 strcmp (qemu_param, "-serial") == 0 ||
605 strcmp (qemu_param, "-vnc") == 0 ||
606 strcmp (qemu_param, "-full-screen") == 0 ||
607 strcmp (qemu_param, "-std-vga") == 0 ||
608 strcmp (qemu_param, "-vnc") == 0) {
609 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
613 if (add_cmdline (g, qemu_param) != 0) return -1;
615 if (qemu_value != NULL) {
616 if (add_cmdline (g, qemu_value) != 0) return -1;
623 guestfs_add_drive (guestfs_h *g, const char *filename)
625 size_t len = strlen (filename) + 64;
628 if (strchr (filename, ',') != NULL) {
629 error (g, "filename cannot contain ',' (comma) character");
633 if (access (filename, F_OK) == -1) {
634 perrorf (g, "%s", filename);
638 snprintf (buf, len, "file=%s", filename);
640 return guestfs_config (g, "-drive", buf);
644 guestfs_add_cdrom (guestfs_h *g, const char *filename)
646 if (strchr (filename, ',') != NULL) {
647 error (g, "filename cannot contain ',' (comma) character");
651 if (access (filename, F_OK) == -1) {
652 perrorf (g, "%s", filename);
656 return guestfs_config (g, "-cdrom", filename);
660 guestfs_launch (guestfs_h *g)
662 static const char *dir_template = "/tmp/libguestfsXXXXXX";
663 int r, i, pmore, memsize;
667 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
668 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
669 char *path, *pelem, *pend;
670 char *kernel = NULL, *initrd = NULL;
672 struct sockaddr_un addr;
676 error (g, "you must call guestfs_add_drive before guestfs_launch");
680 if (g->state != CONFIG) {
681 error (g, "qemu has already been launched");
685 /* Search g->path for the kernel and initrd. */
686 pelem = path = safe_strdup (g, g->path);
688 pend = strchrnul (pelem, ':');
689 pmore = *pend == ':';
693 /* Empty element or "." means cwd. */
694 if (len == 0 || (len == 1 && *pelem == '.')) {
697 "looking for kernel and initrd in current directory\n");
698 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
699 kernel = safe_strdup (g, kernel_name);
700 initrd = safe_strdup (g, initrd_name);
704 /* Look at <path>/kernel etc. */
706 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
707 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
708 sprintf (kernel, "%s/%s", pelem, kernel_name);
709 sprintf (initrd, "%s/%s", pelem, initrd_name);
712 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
714 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
718 kernel = initrd = NULL;
726 if (kernel == NULL || initrd == NULL) {
727 error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
728 kernel_name, initrd_name, g->path);
732 /* Choose a suitable memory size. Previously we tried to choose
733 * a minimal memory size, but this isn't really necessary since
734 * recent QEMU and KVM don't do anything nasty like locking
735 * memory into core any more. This we can safely choose a
736 * large, generous amount of memory, and it'll just get swapped
737 * on smaller systems.
741 /* Make the temporary directory containing the socket. */
743 g->tmpdir = safe_strdup (g, dir_template);
744 if (mkdtemp (g->tmpdir) == NULL) {
745 perrorf (g, "%s: cannot create temporary directory", dir_template);
750 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
753 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
768 if (r == 0) { /* Child (qemu). */
771 char memsize_str[256];
773 /* Set up the full command line. Do this in the subprocess so we
774 * don't need to worry about cleaning up.
776 g->cmdline[0] = (char *) g->qemu;
778 /* Construct the -net channel parameter for qemu. */
779 snprintf (vmchannel, sizeof vmchannel,
780 "channel,%d:unix:%s,server,nowait",
781 VMCHANNEL_PORT, unixsock);
783 /* Linux kernel command line. */
784 snprintf (append, sizeof append,
785 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
786 VMCHANNEL_ADDR, VMCHANNEL_PORT,
787 g->verbose ? " guestfs_verbose=1" : "",
788 g->append ? " " : "", g->append ? g->append : "");
790 snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
792 add_cmdline (g, "-m");
793 add_cmdline (g, memsize_str);
795 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
797 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
798 add_cmdline (g, "-kernel");
799 add_cmdline (g, (char *) kernel);
800 add_cmdline (g, "-initrd");
801 add_cmdline (g, (char *) initrd);
802 add_cmdline (g, "-append");
803 add_cmdline (g, append);
804 add_cmdline (g, "-nographic");
805 add_cmdline (g, "-serial");
806 add_cmdline (g, "stdio");
807 add_cmdline (g, "-net");
808 add_cmdline (g, vmchannel);
809 add_cmdline (g, "-net");
810 add_cmdline (g, "user,vlan=0");
811 add_cmdline (g, "-net");
812 add_cmdline (g, "nic,model=virtio,vlan=0");
813 incr_cmdline_size (g);
814 g->cmdline[g->cmdline_size-1] = NULL;
817 fprintf (stderr, "%s", g->qemu);
818 for (i = 0; g->cmdline[i]; ++i)
819 fprintf (stderr, " %s", g->cmdline[i]);
820 fprintf (stderr, "\n");
823 /* Set up stdin, stdout. */
834 /* Set up a new process group, so we can signal this process
835 * and all subprocesses (eg. if qemu is really a shell script).
840 execv (g->qemu, g->cmdline); /* Run qemu. */
845 /* Parent (library). */
853 /* Fork the recovery process off which will kill qemu if the parent
854 * process fails to do so (eg. if the parent segfaults).
858 pid_t qemu_pid = g->pid;
859 pid_t parent_pid = getppid ();
861 /* Writing to argv is hideously complicated and error prone. See:
862 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
865 /* Loop around waiting for one or both of the other processes to
866 * disappear. It's fair to say this is very hairy. The PIDs that
867 * we are looking at might be reused by another process. We are
868 * effectively polling. Is the cure worse than the disease?
871 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
873 if (kill (parent_pid, 0) == -1) {
874 /* Parent's gone away, qemu still around, so kill qemu. */
882 /* Don't worry, if the fork failed, this will be -1. The recovery
883 * process isn't essential.
887 /* Start the clock ... */
890 /* Close the other ends of the pipe. */
894 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
895 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
896 perrorf (g, "fcntl");
900 g->fd[0] = wfd[1]; /* stdin of child */
901 g->fd[1] = rfd[0]; /* stdout of child */
903 /* Open the Unix socket. The vmchannel implementation that got
904 * merged with qemu sucks in a number of ways. Both ends do
905 * connect(2), which means that no one knows what, if anything, is
906 * connected to the other end, or if it becomes disconnected. Even
907 * worse, we have to wait some indeterminate time for qemu to create
908 * the socket and connect to it (which happens very early in qemu's
909 * start-up), so any code that uses vmchannel is inherently racy.
910 * Hence this silly loop.
912 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
914 perrorf (g, "socket");
918 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
919 perrorf (g, "fcntl");
923 addr.sun_family = AF_UNIX;
924 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
925 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
928 /* Always sleep at least once to give qemu a small chance to start up. */
931 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
932 if ((r == -1 && errno == EINPROGRESS) || r == 0)
936 perrorf (g, "connect");
941 error (g, "failed to connect to vmchannel socket");
945 /* Watch the file descriptors. */
948 g->msg_in_size = g->msg_in_allocated = 0;
956 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
957 GUESTFS_HANDLE_READABLE,
959 if (g->stdout_watch == -1) {
960 error (g, "could not watch qemu stdout");
964 if (guestfs__switch_to_receiving (g) == -1)
967 g->state = LAUNCHING;
971 if (g->stdout_watch >= 0)
972 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
973 if (g->sock_watch >= 0)
974 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
983 if (g->recoverypid > 0) kill (g->recoverypid, 9);
984 waitpid (g->pid, NULL, 0);
985 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
992 g->stdout_watch = -1;
1002 finish_wait_ready (guestfs_h *g, void *vp)
1005 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1008 g->main_loop->main_loop_quit (g->main_loop, g);
1012 guestfs_wait_ready (guestfs_h *g)
1014 int finished = 0, r;
1016 if (g->state == READY) return 0;
1018 if (g->state == BUSY) {
1019 error (g, "qemu has finished launching already");
1023 if (g->state != LAUNCHING) {
1024 error (g, "qemu has not been launched yet");
1028 g->launch_done_cb = finish_wait_ready;
1029 g->launch_done_cb_data = &finished;
1030 r = g->main_loop->main_loop_run (g->main_loop, g);
1031 g->launch_done_cb = NULL;
1032 g->launch_done_cb_data = NULL;
1034 if (r == -1) return -1;
1036 if (finished != 1) {
1037 error (g, "guestfs_wait_ready failed, see earlier error messages");
1041 /* This is possible in some really strange situations, such as
1042 * guestfsd starts up OK but then qemu immediately exits. Check for
1043 * it because the caller is probably expecting to be able to send
1044 * commands after this function returns.
1046 if (g->state != READY) {
1047 error (g, "qemu launched and contacted daemon, but state != READY");
1055 guestfs_kill_subprocess (guestfs_h *g)
1057 if (g->state == CONFIG) {
1058 error (g, "no subprocess to kill");
1063 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1065 kill (g->pid, SIGTERM);
1066 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1071 /* Access current state. */
1073 guestfs_is_config (guestfs_h *g)
1075 return g->state == CONFIG;
1079 guestfs_is_launching (guestfs_h *g)
1081 return g->state == LAUNCHING;
1085 guestfs_is_ready (guestfs_h *g)
1087 return g->state == READY;
1091 guestfs_is_busy (guestfs_h *g)
1093 return g->state == BUSY;
1097 guestfs_get_state (guestfs_h *g)
1103 guestfs_set_ready (guestfs_h *g)
1105 if (g->state != BUSY) {
1106 error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1114 guestfs_set_busy (guestfs_h *g)
1116 if (g->state != READY) {
1117 error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1125 guestfs_end_busy (guestfs_h *g)
1137 error (g, "guestfs_end_busy: called when in state %d", g->state);
1143 /* Structure-freeing functions. These rely on the fact that the
1144 * structure format is identical to the XDR format. See note in
1148 guestfs_free_int_bool (struct guestfs_int_bool *x)
1154 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1156 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1161 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1163 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1168 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1170 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1174 /* We don't know if stdout_event or sock_read_event will be the
1175 * first to receive EOF if the qemu process dies. This function
1176 * has the common cleanup code for both.
1179 child_cleanup (guestfs_h *g)
1182 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1183 /*kill (g->pid, SIGTERM);*/
1184 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1185 waitpid (g->pid, NULL, 0);
1186 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1187 if (g->stdout_watch >= 0)
1188 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1189 if (g->sock_watch >= 0)
1190 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1200 g->stdout_watch = -1;
1203 if (g->subprocess_quit_cb)
1204 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1207 /* This function is called whenever qemu prints something on stdout.
1208 * Qemu's stdout is also connected to the guest's serial console, so
1209 * we see kernel messages here too.
1212 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1213 int watch, int fd, int events)
1221 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1222 g, g->state, fd, events);
1225 if (g->fd[1] != fd) {
1226 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1230 n = read (fd, buf, sizeof buf);
1232 /* Hopefully this indicates the qemu child process has died. */
1238 if (errno != EINTR && errno != EAGAIN)
1239 perrorf (g, "read");
1243 /* In verbose mode, copy all log messages to stderr. */
1247 /* It's an actual log message, send it upwards if anyone is listening. */
1248 if (g->log_message_cb)
1249 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1252 /* The function is called whenever we can read something on the
1253 * guestfsd (daemon inside the guest) communication socket.
1256 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1257 int watch, int fd, int events)
1265 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1266 g, g->state, fd, events);
1268 if (g->sock != fd) {
1269 error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1273 if (g->msg_in_size <= g->msg_in_allocated) {
1274 g->msg_in_allocated += 4096;
1275 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1277 n = read (g->sock, g->msg_in + g->msg_in_size,
1278 g->msg_in_allocated - g->msg_in_size);
1286 if (errno != EINTR && errno != EAGAIN)
1287 perrorf (g, "read");
1291 g->msg_in_size += n;
1293 /* Have we got enough of a message to be able to process it yet? */
1295 if (g->msg_in_size < 4) return;
1297 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1298 if (!xdr_uint32_t (&xdr, &len)) {
1299 error (g, "can't decode length word");
1303 /* Length is normally the length of the message, but when guestfsd
1304 * starts up it sends a "magic" value (longer than any possible
1305 * message). Check for this.
1307 if (len == GUESTFS_LAUNCH_FLAG) {
1308 if (g->state != LAUNCHING)
1309 error (g, "received magic signature from guestfsd, but in state %d",
1311 else if (g->msg_in_size != 4)
1312 error (g, "received magic signature from guestfsd, but msg size is %d",
1316 if (g->launch_done_cb)
1317 g->launch_done_cb (g, g->launch_done_cb_data);
1323 /* This can happen if a cancellation happens right at the end
1324 * of us sending a FileIn parameter to the daemon. Discard. The
1325 * daemon should send us an error message next.
1327 if (len == GUESTFS_CANCEL_FLAG) {
1328 g->msg_in_size -= 4;
1329 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1333 /* If this happens, it's pretty bad and we've probably lost
1336 if (len > GUESTFS_MESSAGE_MAX) {
1337 error (g, "message length (%u) > maximum possible size (%d)",
1338 len, GUESTFS_MESSAGE_MAX);
1342 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1344 /* Got the full message, begin processing it. */
1349 for (i = 0; i < g->msg_in_size; i += 16) {
1350 printf ("%04x: ", i);
1351 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1352 printf ("%02x ", (unsigned char) g->msg_in[j]);
1353 for (; j < i+16; ++j)
1356 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1357 if (isprint (g->msg_in[j]))
1358 printf ("%c", g->msg_in[j]);
1361 for (; j < i+16; ++j)
1368 /* Not in the expected state. */
1369 if (g->state != BUSY)
1370 error (g, "state %d != BUSY", g->state);
1372 /* Push the message up to the higher layer. */
1374 g->reply_cb (g, g->reply_cb_data, &xdr);
1376 /* This message (probably) should never be printed. */
1377 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1379 g->msg_in_size -= len + 4;
1380 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1381 if (g->msg_in_size > 0) goto again;
1384 /* Free the message buffer if it's grown excessively large. */
1385 if (g->msg_in_allocated > 65536) {
1388 g->msg_in_size = g->msg_in_allocated = 0;
1395 /* The function is called whenever we can write something on the
1396 * guestfsd (daemon inside the guest) communication socket.
1399 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1400 int watch, int fd, int events)
1406 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1407 g, g->state, fd, events);
1409 if (g->sock != fd) {
1410 error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1414 if (g->state != BUSY) {
1415 error (g, "sock_write_event: state %d != BUSY", g->state);
1420 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1421 g->msg_out_size - g->msg_out_pos);
1423 n = write (g->sock, g->msg_out + g->msg_out_pos,
1424 g->msg_out_size - g->msg_out_pos);
1426 if (errno != EAGAIN)
1427 perrorf (g, "write");
1432 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1434 g->msg_out_pos += n;
1436 /* More to write? */
1437 if (g->msg_out_pos < g->msg_out_size)
1441 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1445 g->msg_out_pos = g->msg_out_size = 0;
1447 /* Done writing, call the higher layer. */
1449 g->send_cb (g, g->send_cb_data);
1453 guestfs_set_send_callback (guestfs_h *g,
1454 guestfs_send_cb cb, void *opaque)
1457 g->send_cb_data = opaque;
1461 guestfs_set_reply_callback (guestfs_h *g,
1462 guestfs_reply_cb cb, void *opaque)
1465 g->reply_cb_data = opaque;
1469 guestfs_set_log_message_callback (guestfs_h *g,
1470 guestfs_log_message_cb cb, void *opaque)
1472 g->log_message_cb = cb;
1473 g->log_message_cb_data = opaque;
1477 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1478 guestfs_subprocess_quit_cb cb, void *opaque)
1480 g->subprocess_quit_cb = cb;
1481 g->subprocess_quit_cb_data = opaque;
1485 guestfs_set_launch_done_callback (guestfs_h *g,
1486 guestfs_launch_done_cb cb, void *opaque)
1488 g->launch_done_cb = cb;
1489 g->launch_done_cb_data = opaque;
1492 /* Access to the handle's main loop and the default main loop. */
1494 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1496 g->main_loop = main_loop;
1500 guestfs_get_main_loop (guestfs_h *g)
1502 return g->main_loop;
1506 guestfs_get_default_main_loop (void)
1508 return (guestfs_main_loop *) &default_main_loop;
1511 /* Change the daemon socket handler so that we are now writing.
1512 * This sets the handle to sock_write_event.
1515 guestfs__switch_to_sending (guestfs_h *g)
1517 if (g->sock_watch >= 0) {
1518 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1519 error (g, "remove_handle failed");
1526 g->main_loop->add_handle (g->main_loop, g, g->sock,
1527 GUESTFS_HANDLE_WRITABLE,
1528 sock_write_event, NULL);
1529 if (g->sock_watch == -1) {
1530 error (g, "add_handle failed");
1538 guestfs__switch_to_receiving (guestfs_h *g)
1540 if (g->sock_watch >= 0) {
1541 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1542 error (g, "remove_handle failed");
1549 g->main_loop->add_handle (g->main_loop, g, g->sock,
1550 GUESTFS_HANDLE_READABLE,
1551 sock_read_event, NULL);
1552 if (g->sock_watch == -1) {
1553 error (g, "add_handle failed");
1560 /* Dispatch a call (len + header + args) to the remote daemon,
1561 * synchronously (ie. using the guest's main loop to wait until
1562 * it has been sent). Returns -1 for error, or the serial
1563 * number of the message.
1566 send_cb (guestfs_h *g, void *data)
1568 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1571 ml->main_loop_quit (ml, g);
1575 guestfs__send_sync (guestfs_h *g, int proc_nr,
1576 xdrproc_t xdrp, char *args)
1578 struct guestfs_message_header hdr;
1581 int serial = g->msg_next_serial++;
1583 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1585 if (g->state != BUSY) {
1586 error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1590 /* This is probably an internal error. Or perhaps we should just
1591 * free the buffer anyway?
1593 if (g->msg_out != NULL) {
1594 error (g, "guestfs__send_sync: msg_out should be NULL");
1598 /* We have to allocate this message buffer on the heap because
1599 * it is quite large (although will be mostly unused). We
1600 * can't allocate it on the stack because in some environments
1601 * we have quite limited stack space available, notably when
1602 * running in the JVM.
1604 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1605 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1607 /* Serialize the header. */
1608 hdr.prog = GUESTFS_PROGRAM;
1609 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1611 hdr.direction = GUESTFS_DIRECTION_CALL;
1612 hdr.serial = serial;
1613 hdr.status = GUESTFS_STATUS_OK;
1615 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1616 error (g, "xdr_guestfs_message_header failed");
1620 /* Serialize the args. If any, because some message types
1621 * have no parameters.
1624 if (!(*xdrp) (&xdr, args)) {
1625 error (g, "dispatch failed to marshal args");
1630 /* Get the actual length of the message, resize the buffer to match
1631 * the actual length, and write the length word at the beginning.
1633 len = xdr_getpos (&xdr);
1636 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1637 g->msg_out_size = len + 4;
1640 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1641 xdr_uint32_t (&xdr, &len);
1643 if (guestfs__switch_to_sending (g) == -1)
1647 guestfs_set_send_callback (g, send_cb, &sent);
1648 if (ml->main_loop_run (ml, g) == -1)
1651 error (g, "send failed, see earlier error messages");
1660 g->msg_out_size = 0;
1664 static int cancel = 0; /* XXX Implement file cancellation. */
1665 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1666 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1667 static int send_file_cancellation_sync (guestfs_h *g);
1668 static int send_file_complete_sync (guestfs_h *g);
1670 /* Synchronously send a file.
1674 * -2 daemon cancelled (we must read the error message)
1677 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1679 char buf[GUESTFS_MAX_CHUNK_SIZE];
1682 fd = open (filename, O_RDONLY);
1684 perrorf (g, "open: %s", filename);
1685 send_file_cancellation_sync (g);
1686 /* Daemon sees cancellation and won't reply, so caller can
1692 /* Send file in chunked encoding. */
1694 r = read (fd, buf, sizeof buf);
1695 if (r == -1 && (errno == EINTR || errno == EAGAIN))
1698 err = send_file_data_sync (g, buf, r);
1700 if (err == -2) /* daemon sent cancellation */
1701 send_file_cancellation_sync (g);
1706 if (cancel) { /* cancel from either end */
1707 send_file_cancellation_sync (g);
1712 perrorf (g, "read: %s", filename);
1713 send_file_cancellation_sync (g);
1717 /* End of file, but before we send that, we need to close
1718 * the file and check for errors.
1720 if (close (fd) == -1) {
1721 perrorf (g, "close: %s", filename);
1722 send_file_cancellation_sync (g);
1726 return send_file_complete_sync (g);
1729 /* Send a chunk of file data. */
1731 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1733 return send_file_chunk_sync (g, 0, buf, len);
1736 /* Send a cancellation message. */
1738 send_file_cancellation_sync (guestfs_h *g)
1740 return send_file_chunk_sync (g, 1, NULL, 0);
1743 /* Send a file complete chunk. */
1745 send_file_complete_sync (guestfs_h *g)
1748 return send_file_chunk_sync (g, 0, buf, 0);
1751 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1754 static int check_for_daemon_cancellation (guestfs_h *g);
1757 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
1761 guestfs_chunk chunk;
1763 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1765 if (g->state != BUSY) {
1766 error (g, "send_file_chunk_sync: state %d != READY", g->state);
1770 /* This is probably an internal error. Or perhaps we should just
1771 * free the buffer anyway?
1773 if (g->msg_out != NULL) {
1774 error (g, "guestfs__send_sync: msg_out should be NULL");
1778 /* Did the daemon send a cancellation message? */
1779 if (check_for_daemon_cancellation (g)) {
1781 fprintf (stderr, "got daemon cancellation\n");
1785 /* Allocate the chunk buffer. Don't use the stack to avoid
1786 * excessive stack usage and unnecessary copies.
1788 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
1789 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1791 /* Serialize the chunk. */
1792 chunk.cancel = cancel;
1793 chunk.data.data_len = buflen;
1794 chunk.data.data_val = (char *) buf;
1796 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1797 error (g, "xdr_guestfs_chunk failed (buf = %p, buflen = %zu)",
1803 len = xdr_getpos (&xdr);
1806 /* Reduce the size of the outgoing message buffer to the real length. */
1807 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1808 g->msg_out_size = len + 4;
1811 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1812 xdr_uint32_t (&xdr, &len);
1814 if (guestfs__switch_to_sending (g) == -1)
1818 guestfs_set_send_callback (g, send_cb, &sent);
1819 if (ml->main_loop_run (ml, g) == -1)
1822 error (g, "send file chunk failed, see earlier error messages");
1831 g->msg_out_size = 0;
1835 /* At this point we are sending FileIn file(s) to the guest, and not
1836 * expecting to read anything, so if we do read anything, it must be
1837 * a cancellation message. This checks for this case without blocking.
1840 check_for_daemon_cancellation (guestfs_h *g)
1850 FD_SET (g->sock, &rset);
1853 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1855 perrorf (g, "select");
1861 /* Read the message from the daemon. */
1862 r = xread (g->sock, buf, sizeof buf);
1864 perrorf (g, "read");
1868 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1869 xdr_uint32_t (&xdr, &flag);
1872 if (flag != GUESTFS_CANCEL_FLAG) {
1873 error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1874 flag, GUESTFS_CANCEL_FLAG);
1881 /* Synchronously receive a file. */
1883 /* Returns -1 = error, 0 = EOF, 1 = more data */
1884 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
1887 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1893 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1895 perrorf (g, "open: %s", filename);
1899 /* Receive the file in chunked encoding. */
1900 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
1901 if (xwrite (fd, buf, len) == -1) {
1902 perrorf (g, "%s: write", filename);
1907 if (r == 0) break; /* End of file. */
1911 error (g, "%s: error in chunked encoding", filename);
1915 if (close (fd) == -1) {
1916 perrorf (g, "close: %s", filename);
1923 /* Send cancellation message to daemon, then wait until it
1924 * cancels (just throwing away data).
1928 uint32_t flag = GUESTFS_CANCEL_FLAG;
1930 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1931 xdr_uint32_t (&xdr, &flag);
1934 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1935 perrorf (g, "write to daemon socket");
1939 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
1940 ; /* just discard it */
1945 /* Note that the reply callback can be called multiple times before
1946 * the main loop quits and we get back to the synchronous code. So
1947 * we have to be prepared to save multiple chunks on a list here.
1949 struct receive_file_ctx {
1950 int count; /* 0 if receive_file_cb not called, or
1951 * else count number of chunks.
1953 guestfs_chunk *chunks; /* Array of chunks. */
1957 free_chunks (struct receive_file_ctx *ctx)
1961 for (i = 0; i < ctx->count; ++i)
1962 free (ctx->chunks[i].data.data_val);
1968 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1970 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1971 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1972 guestfs_chunk chunk;
1974 if (ctx->count == -1) /* Parse error occurred previously. */
1977 ml->main_loop_quit (ml, g);
1979 memset (&chunk, 0, sizeof chunk);
1981 if (!xdr_guestfs_chunk (xdr, &chunk)) {
1982 error (g, "failed to parse file chunk");
1989 /* Copy the chunk to the list. */
1990 ctx->chunks = safe_realloc (g, ctx->chunks,
1991 sizeof (guestfs_chunk) * (ctx->count+1));
1992 ctx->chunks[ctx->count] = chunk;
1996 /* Receive a chunk of file data. */
1997 /* Returns -1 = error, 0 = EOF, 1 = more data */
1999 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2001 struct receive_file_ctx ctx;
2002 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2009 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2010 (void) ml->main_loop_run (ml, g);
2011 guestfs_set_reply_callback (g, NULL, NULL);
2013 if (ctx.count == 0) {
2014 error (g, "receive_file_data_sync: reply callback not called\n");
2018 if (ctx.count == -1) {
2019 error (g, "receive_file_data_sync: parse error in reply callback\n");
2020 /* callback already freed the chunks */
2025 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2027 /* Process each chunk in the list. */
2028 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2031 for (i = 0; i < ctx.count; ++i) {
2032 if (ctx.chunks[i].cancel) {
2033 error (g, "file receive cancelled by daemon");
2035 if (buf) free (*buf);
2036 if (len_r) *len_r = 0;
2040 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2042 if (len_r) *len_r = len;
2047 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2048 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2049 ctx.chunks[i].data.data_len);
2051 len += ctx.chunks[i].data.data_len;
2054 if (len_r) *len_r = len;
2059 /* This is the default main loop implementation, using select(2). */
2062 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2063 guestfs_handle_event_cb cb, void *data)
2065 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2067 if (fd < 0 || fd >= FD_SETSIZE) {
2068 error (g, "fd %d is out of range", fd);
2072 if ((events & ~(GUESTFS_HANDLE_READABLE |
2073 GUESTFS_HANDLE_WRITABLE |
2074 GUESTFS_HANDLE_HANGUP |
2075 GUESTFS_HANDLE_ERROR)) != 0) {
2076 error (g, "set of events (0x%x) contains unknown events", events);
2081 error (g, "set of events is empty");
2085 if (FD_ISSET (fd, &ml->rset) ||
2086 FD_ISSET (fd, &ml->wset) ||
2087 FD_ISSET (fd, &ml->xset)) {
2088 error (g, "fd %d is already registered", fd);
2093 error (g, "callback is NULL");
2097 if ((events & GUESTFS_HANDLE_READABLE))
2098 FD_SET (fd, &ml->rset);
2099 if ((events & GUESTFS_HANDLE_WRITABLE))
2100 FD_SET (fd, &ml->wset);
2101 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2102 FD_SET (fd, &ml->xset);
2104 if (fd > ml->max_fd) {
2106 ml->handle_cb_data =
2107 safe_realloc (g, ml->handle_cb_data,
2108 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2110 ml->handle_cb_data[fd].cb = cb;
2111 ml->handle_cb_data[fd].g = g;
2112 ml->handle_cb_data[fd].data = data;
2116 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2121 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2123 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2125 if (fd < 0 || fd >= FD_SETSIZE) {
2126 error (g, "fd %d is out of range", fd);
2130 if (!FD_ISSET (fd, &ml->rset) &&
2131 !FD_ISSET (fd, &ml->wset) &&
2132 !FD_ISSET (fd, &ml->xset)) {
2133 error (g, "fd %d was not registered", fd);
2137 FD_CLR (fd, &ml->rset);
2138 FD_CLR (fd, &ml->wset);
2139 FD_CLR (fd, &ml->xset);
2141 if (fd == ml->max_fd) {
2143 ml->handle_cb_data =
2144 safe_realloc (g, ml->handle_cb_data,
2145 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2154 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2155 guestfs_handle_timeout_cb cb, void *data)
2157 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2159 abort (); /* XXX not implemented yet */
2163 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2165 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2167 abort (); /* XXX not implemented yet */
2170 /* The 'g' parameter is just used for error reporting. Events
2171 * for multiple handles can be dispatched by running the main
2175 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2177 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2179 fd_set rset2, wset2, xset2;
2181 if (ml->is_running) {
2182 error (g, "select_main_loop_run: this cannot be called recursively");
2188 while (ml->is_running) {
2189 if (ml->nr_fds == 0)
2195 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2197 if (errno == EINTR || errno == EAGAIN)
2199 perrorf (g, "select");
2204 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2206 if (FD_ISSET (fd, &rset2))
2207 events |= GUESTFS_HANDLE_READABLE;
2208 if (FD_ISSET (fd, &wset2))
2209 events |= GUESTFS_HANDLE_WRITABLE;
2210 if (FD_ISSET (fd, &xset2))
2211 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2214 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2215 ml->handle_cb_data[fd].g,
2216 ml->handle_cb_data[fd].data,
2227 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2229 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2231 /* Note that legitimately ml->is_running can be zero when
2232 * this function is called.