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"
63 #define _(str) dgettext(PACKAGE, (str))
64 #define N_(str) dgettext(PACKAGE, (str))
70 #define error guestfs_error
71 #define perrorf guestfs_perrorf
72 #define safe_malloc guestfs_safe_malloc
73 #define safe_realloc guestfs_safe_realloc
74 #define safe_strdup guestfs_safe_strdup
75 #define safe_memdup guestfs_safe_memdup
77 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
78 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
79 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
80 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
82 static void close_handles (void);
84 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
85 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
86 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
87 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
88 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
89 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
91 /* Default select-based main loop. */
92 struct select_handle_cb_data {
93 guestfs_handle_event_cb cb;
98 struct select_main_loop {
99 /* NB. These fields must be the same as in struct guestfs_main_loop: */
100 guestfs_add_handle_cb add_handle;
101 guestfs_remove_handle_cb remove_handle;
102 guestfs_add_timeout_cb add_timeout;
103 guestfs_remove_timeout_cb remove_timeout;
104 guestfs_main_loop_run_cb main_loop_run;
105 guestfs_main_loop_quit_cb main_loop_quit;
107 /* Additional private data: */
116 struct select_handle_cb_data *handle_cb_data;
119 /* Default main loop. */
120 static struct select_main_loop default_main_loop = {
121 .add_handle = select_add_handle,
122 .remove_handle = select_remove_handle,
123 .add_timeout = select_add_timeout,
124 .remove_timeout = select_remove_timeout,
125 .main_loop_run = select_main_loop_run,
126 .main_loop_quit = select_main_loop_quit,
128 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
129 * set by the normal action of everything being initialized to zero.
134 .handle_cb_data = NULL,
137 #define UNIX_PATH_MAX 108
139 /* Also in guestfsd.c */
140 #define VMCHANNEL_PORT 6666
141 #define VMCHANNEL_ADDR "10.0.2.4"
143 /* GuestFS handle and connection. */
144 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
148 struct guestfs_h *next; /* Linked list of open handles. */
150 /* State: see the state machine diagram in the man page guestfs(3). */
153 int fd[2]; /* Stdin/stdout of qemu. */
154 int sock; /* Daemon communications socket. */
155 pid_t pid; /* Qemu PID. */
156 pid_t recoverypid; /* Recovery process PID. */
157 time_t start_t; /* The time when we started qemu. */
159 int stdout_watch; /* Watches qemu stdout for log messages. */
160 int sock_watch; /* Watches daemon comm socket. */
162 char *tmpdir; /* Temporary directory containing socket. */
164 char **cmdline; /* Qemu command line. */
170 char *path; /* Path to kernel, initrd. */
171 char *qemu; /* Qemu binary. */
172 char *append; /* Append to kernel command line. */
177 guestfs_abort_cb abort_cb;
178 guestfs_error_handler_cb error_cb;
179 void * error_cb_data;
180 guestfs_send_cb send_cb;
182 guestfs_reply_cb reply_cb;
183 void * reply_cb_data;
184 guestfs_log_message_cb log_message_cb;
185 void * log_message_cb_data;
186 guestfs_subprocess_quit_cb subprocess_quit_cb;
187 void * subprocess_quit_cb_data;
188 guestfs_launch_done_cb launch_done_cb;
189 void * launch_done_cb_data;
191 /* Main loop used by this handle. */
192 guestfs_main_loop *main_loop;
194 /* Messages sent and received from the daemon. */
196 int msg_in_size, msg_in_allocated;
198 int msg_out_size, msg_out_pos;
203 static guestfs_h *handles = NULL;
204 static int atexit_handler_set = 0;
207 guestfs_create (void)
212 g = malloc (sizeof (*g));
215 memset (g, 0, sizeof (*g));
222 g->stdout_watch = -1;
226 g->error_cb = default_error_cb;
227 g->error_cb_data = NULL;
229 str = getenv ("LIBGUESTFS_DEBUG");
230 g->verbose = str != NULL && strcmp (str, "1") == 0;
232 str = getenv ("LIBGUESTFS_PATH");
233 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
234 if (!g->path) goto error;
236 str = getenv ("LIBGUESTFS_QEMU");
237 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
238 if (!g->qemu) goto error;
240 str = getenv ("LIBGUESTFS_APPEND");
242 g->append = strdup (str);
243 if (!g->append) goto error;
246 g->main_loop = guestfs_get_default_main_loop ();
248 /* Start with large serial numbers so they are easy to spot
249 * inside the protocol.
251 g->msg_next_serial = 0x00123400;
253 /* Link the handles onto a global list. This is the one area
254 * where the library needs to be made thread-safe. (XXX)
256 /* acquire mutex (XXX) */
259 if (!atexit_handler_set) {
260 atexit (close_handles);
261 atexit_handler_set = 1;
263 /* release mutex (XXX) */
266 fprintf (stderr, "new guestfs handle %p\n", g);
279 guestfs_close (guestfs_h *g)
285 if (g->state == NO_HANDLE) {
286 /* Not safe to call 'error' here, so ... */
287 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
292 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
294 /* Try to sync if autosync flag is set. */
295 if (g->autosync && g->state == READY) {
296 guestfs_umount_all (g);
300 /* Remove any handlers that might be called back before we kill the
303 g->log_message_cb = NULL;
305 if (g->state != CONFIG)
306 guestfs_kill_subprocess (g);
309 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
318 for (i = 0; i < g->cmdline_size; ++i)
319 free (g->cmdline[i]);
323 /* Mark the handle as dead before freeing it. */
324 g->state = NO_HANDLE;
326 /* acquire mutex (XXX) */
330 for (gg = handles; gg->next != g; gg = gg->next)
334 /* release mutex (XXX) */
338 free (g->last_error);
345 /* Close all open handles (called from atexit(3)). */
349 while (handles) guestfs_close (handles);
353 guestfs_last_error (guestfs_h *g)
355 return g->last_error;
359 set_last_error (guestfs_h *g, const char *msg)
361 free (g->last_error);
362 g->last_error = strdup (msg);
366 default_error_cb (guestfs_h *g, void *data, const char *msg)
368 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
372 guestfs_error (guestfs_h *g, const char *fs, ...)
378 vasprintf (&msg, fs, args);
381 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
382 set_last_error (g, msg);
388 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
395 vasprintf (&msg, fs, args);
400 strerror_r (err, buf, sizeof buf);
404 buf = strerror_r (err, _buf, sizeof _buf);
407 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
411 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
412 set_last_error (g, msg);
418 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
420 void *ptr = malloc (nbytes);
421 if (!ptr) g->abort_cb ();
426 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
428 void *p = realloc (ptr, nbytes);
429 if (!p) g->abort_cb ();
434 guestfs_safe_strdup (guestfs_h *g, const char *str)
436 char *s = strdup (str);
437 if (!s) g->abort_cb ();
442 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
444 void *p = malloc (size);
445 if (!p) g->abort_cb ();
446 memcpy (p, ptr, size);
451 xwrite (int fd, const void *buf, size_t len)
456 r = write (fd, buf, len);
468 xread (int fd, void *buf, size_t len)
473 r = read (fd, buf, len);
475 if (errno == EINTR || errno == EAGAIN)
488 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
494 guestfs_get_out_of_memory_handler (guestfs_h *g)
500 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
503 g->error_cb_data = data;
506 guestfs_error_handler_cb
507 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
509 if (data_rtn) *data_rtn = g->error_cb_data;
514 guestfs_set_verbose (guestfs_h *g, int v)
521 guestfs_get_verbose (guestfs_h *g)
527 guestfs_set_autosync (guestfs_h *g, int a)
534 guestfs_get_autosync (guestfs_h *g)
540 guestfs_set_path (guestfs_h *g, const char *path)
547 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
552 guestfs_get_path (guestfs_h *g)
558 guestfs_set_qemu (guestfs_h *g, const char *qemu)
563 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
568 guestfs_get_qemu (guestfs_h *g)
574 guestfs_set_append (guestfs_h *g, const char *append)
579 g->append = append ? safe_strdup (g, append) : NULL;
584 guestfs_get_append (guestfs_h *g)
589 /* Add a string to the current command line. */
591 incr_cmdline_size (guestfs_h *g)
593 if (g->cmdline == NULL) {
594 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
596 g->cmdline = safe_malloc (g, sizeof (char *));
597 g->cmdline[0] = NULL;
601 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
605 add_cmdline (guestfs_h *g, const char *str)
607 if (g->state != CONFIG) {
609 _("command line cannot be altered after qemu subprocess launched"));
613 incr_cmdline_size (g);
614 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
619 guestfs_config (guestfs_h *g,
620 const char *qemu_param, const char *qemu_value)
622 if (qemu_param[0] != '-') {
623 error (g, _("guestfs_config: parameter must begin with '-' character"));
627 /* A bit fascist, but the user will probably break the extra
628 * parameters that we add if they try to set any of these.
630 if (strcmp (qemu_param, "-kernel") == 0 ||
631 strcmp (qemu_param, "-initrd") == 0 ||
632 strcmp (qemu_param, "-nographic") == 0 ||
633 strcmp (qemu_param, "-serial") == 0 ||
634 strcmp (qemu_param, "-vnc") == 0 ||
635 strcmp (qemu_param, "-full-screen") == 0 ||
636 strcmp (qemu_param, "-std-vga") == 0 ||
637 strcmp (qemu_param, "-vnc") == 0) {
638 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
642 if (add_cmdline (g, qemu_param) != 0) return -1;
644 if (qemu_value != NULL) {
645 if (add_cmdline (g, qemu_value) != 0) return -1;
652 guestfs_add_drive (guestfs_h *g, const char *filename)
654 size_t len = strlen (filename) + 64;
657 if (strchr (filename, ',') != NULL) {
658 error (g, _("filename cannot contain ',' (comma) character"));
662 if (access (filename, F_OK) == -1) {
663 perrorf (g, "%s", filename);
667 snprintf (buf, len, "file=%s", filename);
669 return guestfs_config (g, "-drive", buf);
673 guestfs_add_cdrom (guestfs_h *g, const char *filename)
675 if (strchr (filename, ',') != NULL) {
676 error (g, _("filename cannot contain ',' (comma) character"));
680 if (access (filename, F_OK) == -1) {
681 perrorf (g, "%s", filename);
685 return guestfs_config (g, "-cdrom", filename);
689 guestfs_launch (guestfs_h *g)
691 static const char *dir_template = "/tmp/libguestfsXXXXXX";
692 int r, i, pmore, memsize;
696 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
697 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
698 char *path, *pelem, *pend;
699 char *kernel = NULL, *initrd = NULL;
701 struct sockaddr_un addr;
705 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
709 if (g->state != CONFIG) {
710 error (g, _("qemu has already been launched"));
714 /* Search g->path for the kernel and initrd. */
715 pelem = path = safe_strdup (g, g->path);
717 pend = strchrnul (pelem, ':');
718 pmore = *pend == ':';
722 /* Empty element or "." means cwd. */
723 if (len == 0 || (len == 1 && *pelem == '.')) {
726 "looking for kernel and initrd in current directory\n");
727 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
728 kernel = safe_strdup (g, kernel_name);
729 initrd = safe_strdup (g, initrd_name);
733 /* Look at <path>/kernel etc. */
735 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
736 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
737 sprintf (kernel, "%s/%s", pelem, kernel_name);
738 sprintf (initrd, "%s/%s", pelem, initrd_name);
741 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
743 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
747 kernel = initrd = NULL;
755 if (kernel == NULL || initrd == NULL) {
756 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
757 kernel_name, initrd_name, g->path);
761 /* Choose a suitable memory size. Previously we tried to choose
762 * a minimal memory size, but this isn't really necessary since
763 * recent QEMU and KVM don't do anything nasty like locking
764 * memory into core any more. This we can safely choose a
765 * large, generous amount of memory, and it'll just get swapped
766 * on smaller systems.
770 /* Make the temporary directory containing the socket. */
772 g->tmpdir = safe_strdup (g, dir_template);
773 if (mkdtemp (g->tmpdir) == NULL) {
774 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
779 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
782 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
797 if (r == 0) { /* Child (qemu). */
800 char memsize_str[256];
802 /* Set up the full command line. Do this in the subprocess so we
803 * don't need to worry about cleaning up.
805 g->cmdline[0] = g->qemu;
807 /* Construct the -net channel parameter for qemu. */
808 snprintf (vmchannel, sizeof vmchannel,
809 "channel,%d:unix:%s,server,nowait",
810 VMCHANNEL_PORT, unixsock);
812 /* Linux kernel command line. */
813 snprintf (append, sizeof append,
814 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
815 VMCHANNEL_ADDR, VMCHANNEL_PORT,
816 g->verbose ? " guestfs_verbose=1" : "",
817 g->append ? " " : "", g->append ? g->append : "");
819 snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
821 add_cmdline (g, "-m");
822 add_cmdline (g, memsize_str);
824 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
826 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
827 add_cmdline (g, "-kernel");
828 add_cmdline (g, (char *) kernel);
829 add_cmdline (g, "-initrd");
830 add_cmdline (g, (char *) initrd);
831 add_cmdline (g, "-append");
832 add_cmdline (g, append);
833 add_cmdline (g, "-nographic");
834 add_cmdline (g, "-serial");
835 add_cmdline (g, "stdio");
836 add_cmdline (g, "-net");
837 add_cmdline (g, vmchannel);
838 add_cmdline (g, "-net");
839 add_cmdline (g, "user,vlan=0");
840 add_cmdline (g, "-net");
841 add_cmdline (g, "nic,model=virtio,vlan=0");
842 incr_cmdline_size (g);
843 g->cmdline[g->cmdline_size-1] = NULL;
846 fprintf (stderr, "%s", g->qemu);
847 for (i = 0; g->cmdline[i]; ++i)
848 fprintf (stderr, " %s", g->cmdline[i]);
849 fprintf (stderr, "\n");
852 /* Set up stdin, stdout. */
863 /* Set up a new process group, so we can signal this process
864 * and all subprocesses (eg. if qemu is really a shell script).
869 execv (g->qemu, g->cmdline); /* Run qemu. */
874 /* Parent (library). */
882 /* Fork the recovery process off which will kill qemu if the parent
883 * process fails to do so (eg. if the parent segfaults).
887 pid_t qemu_pid = g->pid;
888 pid_t parent_pid = getppid ();
890 /* Writing to argv is hideously complicated and error prone. See:
891 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
894 /* Loop around waiting for one or both of the other processes to
895 * disappear. It's fair to say this is very hairy. The PIDs that
896 * we are looking at might be reused by another process. We are
897 * effectively polling. Is the cure worse than the disease?
900 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
902 if (kill (parent_pid, 0) == -1) {
903 /* Parent's gone away, qemu still around, so kill qemu. */
911 /* Don't worry, if the fork failed, this will be -1. The recovery
912 * process isn't essential.
916 /* Start the clock ... */
919 /* Close the other ends of the pipe. */
923 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
924 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
925 perrorf (g, "fcntl");
929 g->fd[0] = wfd[1]; /* stdin of child */
930 g->fd[1] = rfd[0]; /* stdout of child */
932 /* Open the Unix socket. The vmchannel implementation that got
933 * merged with qemu sucks in a number of ways. Both ends do
934 * connect(2), which means that no one knows what, if anything, is
935 * connected to the other end, or if it becomes disconnected. Even
936 * worse, we have to wait some indeterminate time for qemu to create
937 * the socket and connect to it (which happens very early in qemu's
938 * start-up), so any code that uses vmchannel is inherently racy.
939 * Hence this silly loop.
941 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
943 perrorf (g, "socket");
947 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
948 perrorf (g, "fcntl");
952 addr.sun_family = AF_UNIX;
953 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
954 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
957 /* Always sleep at least once to give qemu a small chance to start up. */
960 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
961 if ((r == -1 && errno == EINPROGRESS) || r == 0)
965 perrorf (g, "connect");
970 error (g, _("failed to connect to vmchannel socket"));
974 /* Watch the file descriptors. */
977 g->msg_in_size = g->msg_in_allocated = 0;
985 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
986 GUESTFS_HANDLE_READABLE,
988 if (g->stdout_watch == -1) {
989 error (g, _("could not watch qemu stdout"));
993 if (guestfs__switch_to_receiving (g) == -1)
996 g->state = LAUNCHING;
1000 if (g->stdout_watch >= 0)
1001 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1002 if (g->sock_watch >= 0)
1003 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1012 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1013 waitpid (g->pid, NULL, 0);
1014 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1021 g->stdout_watch = -1;
1031 finish_wait_ready (guestfs_h *g, void *vp)
1034 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1037 g->main_loop->main_loop_quit (g->main_loop, g);
1041 guestfs_wait_ready (guestfs_h *g)
1043 int finished = 0, r;
1045 if (g->state == READY) return 0;
1047 if (g->state == BUSY) {
1048 error (g, _("qemu has finished launching already"));
1052 if (g->state != LAUNCHING) {
1053 error (g, _("qemu has not been launched yet"));
1057 g->launch_done_cb = finish_wait_ready;
1058 g->launch_done_cb_data = &finished;
1059 r = g->main_loop->main_loop_run (g->main_loop, g);
1060 g->launch_done_cb = NULL;
1061 g->launch_done_cb_data = NULL;
1063 if (r == -1) return -1;
1065 if (finished != 1) {
1066 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1070 /* This is possible in some really strange situations, such as
1071 * guestfsd starts up OK but then qemu immediately exits. Check for
1072 * it because the caller is probably expecting to be able to send
1073 * commands after this function returns.
1075 if (g->state != READY) {
1076 error (g, _("qemu launched and contacted daemon, but state != READY"));
1084 guestfs_kill_subprocess (guestfs_h *g)
1086 if (g->state == CONFIG) {
1087 error (g, _("no subprocess to kill"));
1092 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1094 kill (g->pid, SIGTERM);
1095 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1100 /* Access current state. */
1102 guestfs_is_config (guestfs_h *g)
1104 return g->state == CONFIG;
1108 guestfs_is_launching (guestfs_h *g)
1110 return g->state == LAUNCHING;
1114 guestfs_is_ready (guestfs_h *g)
1116 return g->state == READY;
1120 guestfs_is_busy (guestfs_h *g)
1122 return g->state == BUSY;
1126 guestfs_get_state (guestfs_h *g)
1132 guestfs_set_ready (guestfs_h *g)
1134 if (g->state != BUSY) {
1135 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1144 guestfs_set_busy (guestfs_h *g)
1146 if (g->state != READY) {
1147 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1156 guestfs_end_busy (guestfs_h *g)
1168 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1174 /* Structure-freeing functions. These rely on the fact that the
1175 * structure format is identical to the XDR format. See note in
1179 guestfs_free_int_bool (struct guestfs_int_bool *x)
1185 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1187 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1192 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1194 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1199 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1201 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1205 /* We don't know if stdout_event or sock_read_event will be the
1206 * first to receive EOF if the qemu process dies. This function
1207 * has the common cleanup code for both.
1210 child_cleanup (guestfs_h *g)
1213 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1214 /*kill (g->pid, SIGTERM);*/
1215 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1216 waitpid (g->pid, NULL, 0);
1217 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1218 if (g->stdout_watch >= 0)
1219 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1220 if (g->sock_watch >= 0)
1221 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1231 g->stdout_watch = -1;
1234 if (g->subprocess_quit_cb)
1235 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1238 /* This function is called whenever qemu prints something on stdout.
1239 * Qemu's stdout is also connected to the guest's serial console, so
1240 * we see kernel messages here too.
1243 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1244 int watch, int fd, int events)
1252 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1253 g, g->state, fd, events);
1256 if (g->fd[1] != fd) {
1257 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1261 n = read (fd, buf, sizeof buf);
1263 /* Hopefully this indicates the qemu child process has died. */
1269 if (errno != EINTR && errno != EAGAIN)
1270 perrorf (g, "read");
1274 /* In verbose mode, copy all log messages to stderr. */
1278 /* It's an actual log message, send it upwards if anyone is listening. */
1279 if (g->log_message_cb)
1280 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1283 /* The function is called whenever we can read something on the
1284 * guestfsd (daemon inside the guest) communication socket.
1287 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1288 int watch, int fd, int events)
1296 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1297 g, g->state, fd, events);
1299 if (g->sock != fd) {
1300 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1304 if (g->msg_in_size <= g->msg_in_allocated) {
1305 g->msg_in_allocated += 4096;
1306 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1308 n = read (g->sock, g->msg_in + g->msg_in_size,
1309 g->msg_in_allocated - g->msg_in_size);
1317 if (errno != EINTR && errno != EAGAIN)
1318 perrorf (g, "read");
1322 g->msg_in_size += n;
1324 /* Have we got enough of a message to be able to process it yet? */
1326 if (g->msg_in_size < 4) return;
1328 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1329 if (!xdr_uint32_t (&xdr, &len)) {
1330 error (g, _("can't decode length word"));
1334 /* Length is normally the length of the message, but when guestfsd
1335 * starts up it sends a "magic" value (longer than any possible
1336 * message). Check for this.
1338 if (len == GUESTFS_LAUNCH_FLAG) {
1339 if (g->state != LAUNCHING)
1340 error (g, _("received magic signature from guestfsd, but in state %d"),
1342 else if (g->msg_in_size != 4)
1343 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1347 if (g->launch_done_cb)
1348 g->launch_done_cb (g, g->launch_done_cb_data);
1354 /* This can happen if a cancellation happens right at the end
1355 * of us sending a FileIn parameter to the daemon. Discard. The
1356 * daemon should send us an error message next.
1358 if (len == GUESTFS_CANCEL_FLAG) {
1359 g->msg_in_size -= 4;
1360 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1364 /* If this happens, it's pretty bad and we've probably lost
1367 if (len > GUESTFS_MESSAGE_MAX) {
1368 error (g, _("message length (%u) > maximum possible size (%d)"),
1369 len, GUESTFS_MESSAGE_MAX);
1373 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1375 /* Got the full message, begin processing it. */
1380 for (i = 0; i < g->msg_in_size; i += 16) {
1381 printf ("%04x: ", i);
1382 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1383 printf ("%02x ", (unsigned char) g->msg_in[j]);
1384 for (; j < i+16; ++j)
1387 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1388 if (isprint (g->msg_in[j]))
1389 printf ("%c", g->msg_in[j]);
1392 for (; j < i+16; ++j)
1399 /* Not in the expected state. */
1400 if (g->state != BUSY)
1401 error (g, _("state %d != BUSY"), g->state);
1403 /* Push the message up to the higher layer. */
1405 g->reply_cb (g, g->reply_cb_data, &xdr);
1407 /* This message (probably) should never be printed. */
1408 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1410 g->msg_in_size -= len + 4;
1411 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1412 if (g->msg_in_size > 0) goto again;
1415 /* Free the message buffer if it's grown excessively large. */
1416 if (g->msg_in_allocated > 65536) {
1419 g->msg_in_size = g->msg_in_allocated = 0;
1426 /* The function is called whenever we can write something on the
1427 * guestfsd (daemon inside the guest) communication socket.
1430 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1431 int watch, int fd, int events)
1437 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1438 g, g->state, fd, events);
1440 if (g->sock != fd) {
1441 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1445 if (g->state != BUSY) {
1446 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1451 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1452 g->msg_out_size - g->msg_out_pos);
1454 n = write (g->sock, g->msg_out + g->msg_out_pos,
1455 g->msg_out_size - g->msg_out_pos);
1457 if (errno != EAGAIN)
1458 perrorf (g, "write");
1463 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1465 g->msg_out_pos += n;
1467 /* More to write? */
1468 if (g->msg_out_pos < g->msg_out_size)
1472 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1476 g->msg_out_pos = g->msg_out_size = 0;
1478 /* Done writing, call the higher layer. */
1480 g->send_cb (g, g->send_cb_data);
1484 guestfs_set_send_callback (guestfs_h *g,
1485 guestfs_send_cb cb, void *opaque)
1488 g->send_cb_data = opaque;
1492 guestfs_set_reply_callback (guestfs_h *g,
1493 guestfs_reply_cb cb, void *opaque)
1496 g->reply_cb_data = opaque;
1500 guestfs_set_log_message_callback (guestfs_h *g,
1501 guestfs_log_message_cb cb, void *opaque)
1503 g->log_message_cb = cb;
1504 g->log_message_cb_data = opaque;
1508 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1509 guestfs_subprocess_quit_cb cb, void *opaque)
1511 g->subprocess_quit_cb = cb;
1512 g->subprocess_quit_cb_data = opaque;
1516 guestfs_set_launch_done_callback (guestfs_h *g,
1517 guestfs_launch_done_cb cb, void *opaque)
1519 g->launch_done_cb = cb;
1520 g->launch_done_cb_data = opaque;
1523 /* Access to the handle's main loop and the default main loop. */
1525 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1527 g->main_loop = main_loop;
1531 guestfs_get_main_loop (guestfs_h *g)
1533 return g->main_loop;
1537 guestfs_get_default_main_loop (void)
1539 return (guestfs_main_loop *) &default_main_loop;
1542 /* Change the daemon socket handler so that we are now writing.
1543 * This sets the handle to sock_write_event.
1546 guestfs__switch_to_sending (guestfs_h *g)
1548 if (g->sock_watch >= 0) {
1549 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1550 error (g, _("remove_handle failed"));
1557 g->main_loop->add_handle (g->main_loop, g, g->sock,
1558 GUESTFS_HANDLE_WRITABLE,
1559 sock_write_event, NULL);
1560 if (g->sock_watch == -1) {
1561 error (g, _("add_handle failed"));
1569 guestfs__switch_to_receiving (guestfs_h *g)
1571 if (g->sock_watch >= 0) {
1572 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1573 error (g, _("remove_handle failed"));
1580 g->main_loop->add_handle (g->main_loop, g, g->sock,
1581 GUESTFS_HANDLE_READABLE,
1582 sock_read_event, NULL);
1583 if (g->sock_watch == -1) {
1584 error (g, _("add_handle failed"));
1591 /* Dispatch a call (len + header + args) to the remote daemon,
1592 * synchronously (ie. using the guest's main loop to wait until
1593 * it has been sent). Returns -1 for error, or the serial
1594 * number of the message.
1597 send_cb (guestfs_h *g, void *data)
1599 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1602 ml->main_loop_quit (ml, g);
1606 guestfs__send_sync (guestfs_h *g, int proc_nr,
1607 xdrproc_t xdrp, char *args)
1609 struct guestfs_message_header hdr;
1612 int serial = g->msg_next_serial++;
1614 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1616 if (g->state != BUSY) {
1617 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1621 /* This is probably an internal error. Or perhaps we should just
1622 * free the buffer anyway?
1624 if (g->msg_out != NULL) {
1625 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1629 /* We have to allocate this message buffer on the heap because
1630 * it is quite large (although will be mostly unused). We
1631 * can't allocate it on the stack because in some environments
1632 * we have quite limited stack space available, notably when
1633 * running in the JVM.
1635 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1636 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1638 /* Serialize the header. */
1639 hdr.prog = GUESTFS_PROGRAM;
1640 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1642 hdr.direction = GUESTFS_DIRECTION_CALL;
1643 hdr.serial = serial;
1644 hdr.status = GUESTFS_STATUS_OK;
1646 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1647 error (g, _("xdr_guestfs_message_header failed"));
1651 /* Serialize the args. If any, because some message types
1652 * have no parameters.
1655 if (!(*xdrp) (&xdr, args)) {
1656 error (g, _("dispatch failed to marshal args"));
1661 /* Get the actual length of the message, resize the buffer to match
1662 * the actual length, and write the length word at the beginning.
1664 len = xdr_getpos (&xdr);
1667 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1668 g->msg_out_size = len + 4;
1671 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1672 xdr_uint32_t (&xdr, &len);
1674 if (guestfs__switch_to_sending (g) == -1)
1678 guestfs_set_send_callback (g, send_cb, &sent);
1679 if (ml->main_loop_run (ml, g) == -1)
1682 error (g, _("send failed, see earlier error messages"));
1691 g->msg_out_size = 0;
1695 static int cancel = 0; /* XXX Implement file cancellation. */
1696 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1697 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1698 static int send_file_cancellation_sync (guestfs_h *g);
1699 static int send_file_complete_sync (guestfs_h *g);
1701 /* Synchronously send a file.
1705 * -2 daemon cancelled (we must read the error message)
1708 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1710 char buf[GUESTFS_MAX_CHUNK_SIZE];
1713 fd = open (filename, O_RDONLY);
1715 perrorf (g, "open: %s", filename);
1716 send_file_cancellation_sync (g);
1717 /* Daemon sees cancellation and won't reply, so caller can
1723 /* Send file in chunked encoding. */
1725 r = read (fd, buf, sizeof buf);
1726 if (r == -1 && (errno == EINTR || errno == EAGAIN))
1729 err = send_file_data_sync (g, buf, r);
1731 if (err == -2) /* daemon sent cancellation */
1732 send_file_cancellation_sync (g);
1737 if (cancel) { /* cancel from either end */
1738 send_file_cancellation_sync (g);
1743 perrorf (g, "read: %s", filename);
1744 send_file_cancellation_sync (g);
1748 /* End of file, but before we send that, we need to close
1749 * the file and check for errors.
1751 if (close (fd) == -1) {
1752 perrorf (g, "close: %s", filename);
1753 send_file_cancellation_sync (g);
1757 return send_file_complete_sync (g);
1760 /* Send a chunk of file data. */
1762 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1764 return send_file_chunk_sync (g, 0, buf, len);
1767 /* Send a cancellation message. */
1769 send_file_cancellation_sync (guestfs_h *g)
1771 return send_file_chunk_sync (g, 1, NULL, 0);
1774 /* Send a file complete chunk. */
1776 send_file_complete_sync (guestfs_h *g)
1779 return send_file_chunk_sync (g, 0, buf, 0);
1782 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1785 static int check_for_daemon_cancellation (guestfs_h *g);
1788 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
1792 guestfs_chunk chunk;
1794 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1796 if (g->state != BUSY) {
1797 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
1801 /* This is probably an internal error. Or perhaps we should just
1802 * free the buffer anyway?
1804 if (g->msg_out != NULL) {
1805 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1809 /* Did the daemon send a cancellation message? */
1810 if (check_for_daemon_cancellation (g)) {
1812 fprintf (stderr, "got daemon cancellation\n");
1816 /* Allocate the chunk buffer. Don't use the stack to avoid
1817 * excessive stack usage and unnecessary copies.
1819 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
1820 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1822 /* Serialize the chunk. */
1823 chunk.cancel = cancel;
1824 chunk.data.data_len = buflen;
1825 chunk.data.data_val = (char *) buf;
1827 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1828 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
1834 len = xdr_getpos (&xdr);
1837 /* Reduce the size of the outgoing message buffer to the real length. */
1838 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1839 g->msg_out_size = len + 4;
1842 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1843 xdr_uint32_t (&xdr, &len);
1845 if (guestfs__switch_to_sending (g) == -1)
1849 guestfs_set_send_callback (g, send_cb, &sent);
1850 if (ml->main_loop_run (ml, g) == -1)
1853 error (g, _("send file chunk failed, see earlier error messages"));
1862 g->msg_out_size = 0;
1866 /* At this point we are sending FileIn file(s) to the guest, and not
1867 * expecting to read anything, so if we do read anything, it must be
1868 * a cancellation message. This checks for this case without blocking.
1871 check_for_daemon_cancellation (guestfs_h *g)
1881 FD_SET (g->sock, &rset);
1884 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1886 perrorf (g, "select");
1892 /* Read the message from the daemon. */
1893 r = xread (g->sock, buf, sizeof buf);
1895 perrorf (g, "read");
1899 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1900 xdr_uint32_t (&xdr, &flag);
1903 if (flag != GUESTFS_CANCEL_FLAG) {
1904 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
1905 flag, GUESTFS_CANCEL_FLAG);
1912 /* Synchronously receive a file. */
1914 /* Returns -1 = error, 0 = EOF, 1 = more data */
1915 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
1918 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1924 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1926 perrorf (g, "open: %s", filename);
1930 /* Receive the file in chunked encoding. */
1931 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
1932 if (xwrite (fd, buf, len) == -1) {
1933 perrorf (g, "%s: write", filename);
1938 if (r == 0) break; /* End of file. */
1942 error (g, _("%s: error in chunked encoding"), filename);
1946 if (close (fd) == -1) {
1947 perrorf (g, "close: %s", filename);
1954 /* Send cancellation message to daemon, then wait until it
1955 * cancels (just throwing away data).
1959 uint32_t flag = GUESTFS_CANCEL_FLAG;
1961 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1962 xdr_uint32_t (&xdr, &flag);
1965 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1966 perrorf (g, _("write to daemon socket"));
1970 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
1971 ; /* just discard it */
1976 /* Note that the reply callback can be called multiple times before
1977 * the main loop quits and we get back to the synchronous code. So
1978 * we have to be prepared to save multiple chunks on a list here.
1980 struct receive_file_ctx {
1981 int count; /* 0 if receive_file_cb not called, or
1982 * else count number of chunks.
1984 guestfs_chunk *chunks; /* Array of chunks. */
1988 free_chunks (struct receive_file_ctx *ctx)
1992 for (i = 0; i < ctx->count; ++i)
1993 free (ctx->chunks[i].data.data_val);
1999 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2001 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2002 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2003 guestfs_chunk chunk;
2005 if (ctx->count == -1) /* Parse error occurred previously. */
2008 ml->main_loop_quit (ml, g);
2010 memset (&chunk, 0, sizeof chunk);
2012 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2013 error (g, _("failed to parse file chunk"));
2020 /* Copy the chunk to the list. */
2021 ctx->chunks = safe_realloc (g, ctx->chunks,
2022 sizeof (guestfs_chunk) * (ctx->count+1));
2023 ctx->chunks[ctx->count] = chunk;
2027 /* Receive a chunk of file data. */
2028 /* Returns -1 = error, 0 = EOF, 1 = more data */
2030 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2032 struct receive_file_ctx ctx;
2033 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2040 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2041 (void) ml->main_loop_run (ml, g);
2042 guestfs_set_reply_callback (g, NULL, NULL);
2044 if (ctx.count == 0) {
2045 error (g, _("receive_file_data_sync: reply callback not called\n"));
2049 if (ctx.count == -1) {
2050 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2051 /* callback already freed the chunks */
2056 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2058 /* Process each chunk in the list. */
2059 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2062 for (i = 0; i < ctx.count; ++i) {
2063 if (ctx.chunks[i].cancel) {
2064 error (g, _("file receive cancelled by daemon"));
2066 if (buf) free (*buf);
2067 if (len_r) *len_r = 0;
2071 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2073 if (len_r) *len_r = len;
2078 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2079 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2080 ctx.chunks[i].data.data_len);
2082 len += ctx.chunks[i].data.data_len;
2085 if (len_r) *len_r = len;
2090 /* This is the default main loop implementation, using select(2). */
2093 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2094 guestfs_handle_event_cb cb, void *data)
2096 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2098 if (fd < 0 || fd >= FD_SETSIZE) {
2099 error (g, _("fd %d is out of range"), fd);
2103 if ((events & ~(GUESTFS_HANDLE_READABLE |
2104 GUESTFS_HANDLE_WRITABLE |
2105 GUESTFS_HANDLE_HANGUP |
2106 GUESTFS_HANDLE_ERROR)) != 0) {
2107 error (g, _("set of events (0x%x) contains unknown events"), events);
2112 error (g, _("set of events is empty"));
2116 if (FD_ISSET (fd, &ml->rset) ||
2117 FD_ISSET (fd, &ml->wset) ||
2118 FD_ISSET (fd, &ml->xset)) {
2119 error (g, _("fd %d is already registered"), fd);
2124 error (g, _("callback is NULL"));
2128 if ((events & GUESTFS_HANDLE_READABLE))
2129 FD_SET (fd, &ml->rset);
2130 if ((events & GUESTFS_HANDLE_WRITABLE))
2131 FD_SET (fd, &ml->wset);
2132 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2133 FD_SET (fd, &ml->xset);
2135 if (fd > ml->max_fd) {
2137 ml->handle_cb_data =
2138 safe_realloc (g, ml->handle_cb_data,
2139 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2141 ml->handle_cb_data[fd].cb = cb;
2142 ml->handle_cb_data[fd].g = g;
2143 ml->handle_cb_data[fd].data = data;
2147 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2152 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2154 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2156 if (fd < 0 || fd >= FD_SETSIZE) {
2157 error (g, _("fd %d is out of range"), fd);
2161 if (!FD_ISSET (fd, &ml->rset) &&
2162 !FD_ISSET (fd, &ml->wset) &&
2163 !FD_ISSET (fd, &ml->xset)) {
2164 error (g, _("fd %d was not registered"), fd);
2168 FD_CLR (fd, &ml->rset);
2169 FD_CLR (fd, &ml->wset);
2170 FD_CLR (fd, &ml->xset);
2172 if (fd == ml->max_fd) {
2174 ml->handle_cb_data =
2175 safe_realloc (g, ml->handle_cb_data,
2176 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2185 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2186 guestfs_handle_timeout_cb cb, void *data)
2188 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2190 abort (); /* XXX not implemented yet */
2194 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2196 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2198 abort (); /* XXX not implemented yet */
2201 /* The 'g' parameter is just used for error reporting. Events
2202 * for multiple handles can be dispatched by running the main
2206 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2208 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2210 fd_set rset2, wset2, xset2;
2212 if (ml->is_running) {
2213 error (g, _("select_main_loop_run: this cannot be called recursively"));
2219 while (ml->is_running) {
2220 if (ml->nr_fds == 0)
2226 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2228 if (errno == EINTR || errno == EAGAIN)
2230 perrorf (g, "select");
2235 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2237 if (FD_ISSET (fd, &rset2))
2238 events |= GUESTFS_HANDLE_READABLE;
2239 if (FD_ISSET (fd, &wset2))
2240 events |= GUESTFS_HANDLE_WRITABLE;
2241 if (FD_ISSET (fd, &xset2))
2242 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2245 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2246 ml->handle_cb_data[fd].g,
2247 ml->handle_cb_data[fd].data,
2258 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2260 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2262 /* Note that legitimately ml->is_running can be zero when
2263 * this function is called.