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 (nbytes > 0 && !ptr) g->abort_cb ();
426 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
428 void *p = realloc (ptr, nbytes);
429 if (nbytes > 0 && !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_drive_ro (guestfs_h *g, const char *filename)
675 size_t len = strlen (filename) + 64;
678 if (strchr (filename, ',') != NULL) {
679 error (g, _("filename cannot contain ',' (comma) character"));
683 if (access (filename, F_OK) == -1) {
684 perrorf (g, "%s", filename);
688 snprintf (buf, len, "file=%s,snapshot=on", filename);
690 return guestfs_config (g, "-drive", buf);
694 guestfs_add_cdrom (guestfs_h *g, const char *filename)
696 if (strchr (filename, ',') != NULL) {
697 error (g, _("filename cannot contain ',' (comma) character"));
701 if (access (filename, F_OK) == -1) {
702 perrorf (g, "%s", filename);
706 return guestfs_config (g, "-cdrom", filename);
710 guestfs_launch (guestfs_h *g)
712 static const char *dir_template = "/tmp/libguestfsXXXXXX";
713 int r, i, pmore, memsize;
717 const char *kernel_name = "vmlinuz." REPO "." host_cpu;
718 const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
719 char *path, *pelem, *pend;
720 char *kernel = NULL, *initrd = NULL;
722 struct sockaddr_un addr;
726 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
730 if (g->state != CONFIG) {
731 error (g, _("qemu has already been launched"));
735 /* Search g->path for the kernel and initrd. */
736 pelem = path = safe_strdup (g, g->path);
738 pend = strchrnul (pelem, ':');
739 pmore = *pend == ':';
743 /* Empty element or "." means cwd. */
744 if (len == 0 || (len == 1 && *pelem == '.')) {
747 "looking for kernel and initrd in current directory\n");
748 if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
749 kernel = safe_strdup (g, kernel_name);
750 initrd = safe_strdup (g, initrd_name);
754 /* Look at <path>/kernel etc. */
756 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
757 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
758 sprintf (kernel, "%s/%s", pelem, kernel_name);
759 sprintf (initrd, "%s/%s", pelem, initrd_name);
762 fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
764 if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
768 kernel = initrd = NULL;
776 if (kernel == NULL || initrd == NULL) {
777 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
778 kernel_name, initrd_name, g->path);
782 /* Choose a suitable memory size. Previously we tried to choose
783 * a minimal memory size, but this isn't really necessary since
784 * recent QEMU and KVM don't do anything nasty like locking
785 * memory into core any more. This we can safely choose a
786 * large, generous amount of memory, and it'll just get swapped
787 * on smaller systems.
791 /* Make the temporary directory containing the socket. */
793 g->tmpdir = safe_strdup (g, dir_template);
794 if (mkdtemp (g->tmpdir) == NULL) {
795 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
800 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
803 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
818 if (r == 0) { /* Child (qemu). */
821 char memsize_str[256];
823 /* Set up the full command line. Do this in the subprocess so we
824 * don't need to worry about cleaning up.
826 g->cmdline[0] = g->qemu;
828 /* Construct the -net channel parameter for qemu. */
829 snprintf (vmchannel, sizeof vmchannel,
830 "channel,%d:unix:%s,server,nowait",
831 VMCHANNEL_PORT, unixsock);
833 /* Linux kernel command line. */
834 snprintf (append, sizeof append,
835 "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
836 VMCHANNEL_ADDR, VMCHANNEL_PORT,
837 g->verbose ? " guestfs_verbose=1" : "",
838 g->append ? " " : "", g->append ? g->append : "");
840 snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
842 add_cmdline (g, "-m");
843 add_cmdline (g, memsize_str);
845 add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
847 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
848 add_cmdline (g, "-kernel");
849 add_cmdline (g, (char *) kernel);
850 add_cmdline (g, "-initrd");
851 add_cmdline (g, (char *) initrd);
852 add_cmdline (g, "-append");
853 add_cmdline (g, append);
854 add_cmdline (g, "-nographic");
855 add_cmdline (g, "-serial");
856 add_cmdline (g, "stdio");
857 add_cmdline (g, "-net");
858 add_cmdline (g, vmchannel);
859 add_cmdline (g, "-net");
860 add_cmdline (g, "user,vlan=0");
861 add_cmdline (g, "-net");
862 add_cmdline (g, "nic,model=virtio,vlan=0");
863 incr_cmdline_size (g);
864 g->cmdline[g->cmdline_size-1] = NULL;
867 fprintf (stderr, "%s", g->qemu);
868 for (i = 0; g->cmdline[i]; ++i)
869 fprintf (stderr, " %s", g->cmdline[i]);
870 fprintf (stderr, "\n");
873 /* Set up stdin, stdout. */
884 /* Set up a new process group, so we can signal this process
885 * and all subprocesses (eg. if qemu is really a shell script).
890 execv (g->qemu, g->cmdline); /* Run qemu. */
895 /* Parent (library). */
903 /* Fork the recovery process off which will kill qemu if the parent
904 * process fails to do so (eg. if the parent segfaults).
908 pid_t qemu_pid = g->pid;
909 pid_t parent_pid = getppid ();
911 /* Writing to argv is hideously complicated and error prone. See:
912 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
915 /* Loop around waiting for one or both of the other processes to
916 * disappear. It's fair to say this is very hairy. The PIDs that
917 * we are looking at might be reused by another process. We are
918 * effectively polling. Is the cure worse than the disease?
921 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
923 if (kill (parent_pid, 0) == -1) {
924 /* Parent's gone away, qemu still around, so kill qemu. */
932 /* Don't worry, if the fork failed, this will be -1. The recovery
933 * process isn't essential.
937 /* Start the clock ... */
940 /* Close the other ends of the pipe. */
944 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
945 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
946 perrorf (g, "fcntl");
950 g->fd[0] = wfd[1]; /* stdin of child */
951 g->fd[1] = rfd[0]; /* stdout of child */
953 /* Open the Unix socket. The vmchannel implementation that got
954 * merged with qemu sucks in a number of ways. Both ends do
955 * connect(2), which means that no one knows what, if anything, is
956 * connected to the other end, or if it becomes disconnected. Even
957 * worse, we have to wait some indeterminate time for qemu to create
958 * the socket and connect to it (which happens very early in qemu's
959 * start-up), so any code that uses vmchannel is inherently racy.
960 * Hence this silly loop.
962 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
964 perrorf (g, "socket");
968 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
969 perrorf (g, "fcntl");
973 addr.sun_family = AF_UNIX;
974 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
975 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
978 /* Always sleep at least once to give qemu a small chance to start up. */
981 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
982 if ((r == -1 && errno == EINPROGRESS) || r == 0)
986 perrorf (g, "connect");
991 error (g, _("failed to connect to vmchannel socket"));
995 /* Watch the file descriptors. */
998 g->msg_in_size = g->msg_in_allocated = 0;
1002 g->msg_out_size = 0;
1006 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1007 GUESTFS_HANDLE_READABLE,
1008 stdout_event, NULL);
1009 if (g->stdout_watch == -1) {
1010 error (g, _("could not watch qemu stdout"));
1014 if (guestfs__switch_to_receiving (g) == -1)
1017 g->state = LAUNCHING;
1021 if (g->stdout_watch >= 0)
1022 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1023 if (g->sock_watch >= 0)
1024 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1033 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1034 waitpid (g->pid, NULL, 0);
1035 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1042 g->stdout_watch = -1;
1052 finish_wait_ready (guestfs_h *g, void *vp)
1055 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1058 g->main_loop->main_loop_quit (g->main_loop, g);
1062 guestfs_wait_ready (guestfs_h *g)
1064 int finished = 0, r;
1066 if (g->state == READY) return 0;
1068 if (g->state == BUSY) {
1069 error (g, _("qemu has finished launching already"));
1073 if (g->state != LAUNCHING) {
1074 error (g, _("qemu has not been launched yet"));
1078 g->launch_done_cb = finish_wait_ready;
1079 g->launch_done_cb_data = &finished;
1080 r = g->main_loop->main_loop_run (g->main_loop, g);
1081 g->launch_done_cb = NULL;
1082 g->launch_done_cb_data = NULL;
1084 if (r == -1) return -1;
1086 if (finished != 1) {
1087 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1091 /* This is possible in some really strange situations, such as
1092 * guestfsd starts up OK but then qemu immediately exits. Check for
1093 * it because the caller is probably expecting to be able to send
1094 * commands after this function returns.
1096 if (g->state != READY) {
1097 error (g, _("qemu launched and contacted daemon, but state != READY"));
1105 guestfs_kill_subprocess (guestfs_h *g)
1107 if (g->state == CONFIG) {
1108 error (g, _("no subprocess to kill"));
1113 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1115 kill (g->pid, SIGTERM);
1116 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1121 /* Access current state. */
1123 guestfs_is_config (guestfs_h *g)
1125 return g->state == CONFIG;
1129 guestfs_is_launching (guestfs_h *g)
1131 return g->state == LAUNCHING;
1135 guestfs_is_ready (guestfs_h *g)
1137 return g->state == READY;
1141 guestfs_is_busy (guestfs_h *g)
1143 return g->state == BUSY;
1147 guestfs_get_state (guestfs_h *g)
1153 guestfs_set_ready (guestfs_h *g)
1155 if (g->state != BUSY) {
1156 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1165 guestfs_set_busy (guestfs_h *g)
1167 if (g->state != READY) {
1168 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1177 guestfs_end_busy (guestfs_h *g)
1189 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1195 /* Structure-freeing functions. These rely on the fact that the
1196 * structure format is identical to the XDR format. See note in
1200 guestfs_free_int_bool (struct guestfs_int_bool *x)
1206 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1208 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1213 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1215 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1220 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1222 xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1226 /* We don't know if stdout_event or sock_read_event will be the
1227 * first to receive EOF if the qemu process dies. This function
1228 * has the common cleanup code for both.
1231 child_cleanup (guestfs_h *g)
1234 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1235 /*kill (g->pid, SIGTERM);*/
1236 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1237 waitpid (g->pid, NULL, 0);
1238 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1239 if (g->stdout_watch >= 0)
1240 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1241 if (g->sock_watch >= 0)
1242 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1252 g->stdout_watch = -1;
1255 if (g->subprocess_quit_cb)
1256 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1259 /* This function is called whenever qemu prints something on stdout.
1260 * Qemu's stdout is also connected to the guest's serial console, so
1261 * we see kernel messages here too.
1264 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1265 int watch, int fd, int events)
1273 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1274 g, g->state, fd, events);
1277 if (g->fd[1] != fd) {
1278 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1282 n = read (fd, buf, sizeof buf);
1284 /* Hopefully this indicates the qemu child process has died. */
1290 if (errno != EINTR && errno != EAGAIN)
1291 perrorf (g, "read");
1295 /* In verbose mode, copy all log messages to stderr. */
1299 /* It's an actual log message, send it upwards if anyone is listening. */
1300 if (g->log_message_cb)
1301 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1304 /* The function is called whenever we can read something on the
1305 * guestfsd (daemon inside the guest) communication socket.
1308 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1309 int watch, int fd, int events)
1317 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1318 g, g->state, fd, events);
1320 if (g->sock != fd) {
1321 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1325 if (g->msg_in_size <= g->msg_in_allocated) {
1326 g->msg_in_allocated += 4096;
1327 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1329 n = read (g->sock, g->msg_in + g->msg_in_size,
1330 g->msg_in_allocated - g->msg_in_size);
1338 if (errno != EINTR && errno != EAGAIN)
1339 perrorf (g, "read");
1343 g->msg_in_size += n;
1345 /* Have we got enough of a message to be able to process it yet? */
1347 if (g->msg_in_size < 4) return;
1349 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1350 if (!xdr_uint32_t (&xdr, &len)) {
1351 error (g, _("can't decode length word"));
1355 /* Length is normally the length of the message, but when guestfsd
1356 * starts up it sends a "magic" value (longer than any possible
1357 * message). Check for this.
1359 if (len == GUESTFS_LAUNCH_FLAG) {
1360 if (g->state != LAUNCHING)
1361 error (g, _("received magic signature from guestfsd, but in state %d"),
1363 else if (g->msg_in_size != 4)
1364 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1368 if (g->launch_done_cb)
1369 g->launch_done_cb (g, g->launch_done_cb_data);
1375 /* This can happen if a cancellation happens right at the end
1376 * of us sending a FileIn parameter to the daemon. Discard. The
1377 * daemon should send us an error message next.
1379 if (len == GUESTFS_CANCEL_FLAG) {
1380 g->msg_in_size -= 4;
1381 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1385 /* If this happens, it's pretty bad and we've probably lost
1388 if (len > GUESTFS_MESSAGE_MAX) {
1389 error (g, _("message length (%u) > maximum possible size (%d)"),
1390 len, GUESTFS_MESSAGE_MAX);
1394 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1396 /* Got the full message, begin processing it. */
1401 for (i = 0; i < g->msg_in_size; i += 16) {
1402 printf ("%04x: ", i);
1403 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1404 printf ("%02x ", (unsigned char) g->msg_in[j]);
1405 for (; j < i+16; ++j)
1408 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1409 if (isprint (g->msg_in[j]))
1410 printf ("%c", g->msg_in[j]);
1413 for (; j < i+16; ++j)
1420 /* Not in the expected state. */
1421 if (g->state != BUSY)
1422 error (g, _("state %d != BUSY"), g->state);
1424 /* Push the message up to the higher layer. */
1426 g->reply_cb (g, g->reply_cb_data, &xdr);
1428 /* This message (probably) should never be printed. */
1429 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1431 g->msg_in_size -= len + 4;
1432 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1433 if (g->msg_in_size > 0) goto again;
1436 /* Free the message buffer if it's grown excessively large. */
1437 if (g->msg_in_allocated > 65536) {
1440 g->msg_in_size = g->msg_in_allocated = 0;
1447 /* The function is called whenever we can write something on the
1448 * guestfsd (daemon inside the guest) communication socket.
1451 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1452 int watch, int fd, int events)
1458 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1459 g, g->state, fd, events);
1461 if (g->sock != fd) {
1462 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1466 if (g->state != BUSY) {
1467 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1472 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1473 g->msg_out_size - g->msg_out_pos);
1475 n = write (g->sock, g->msg_out + g->msg_out_pos,
1476 g->msg_out_size - g->msg_out_pos);
1478 if (errno != EAGAIN)
1479 perrorf (g, "write");
1484 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1486 g->msg_out_pos += n;
1488 /* More to write? */
1489 if (g->msg_out_pos < g->msg_out_size)
1493 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1497 g->msg_out_pos = g->msg_out_size = 0;
1499 /* Done writing, call the higher layer. */
1501 g->send_cb (g, g->send_cb_data);
1505 guestfs_set_send_callback (guestfs_h *g,
1506 guestfs_send_cb cb, void *opaque)
1509 g->send_cb_data = opaque;
1513 guestfs_set_reply_callback (guestfs_h *g,
1514 guestfs_reply_cb cb, void *opaque)
1517 g->reply_cb_data = opaque;
1521 guestfs_set_log_message_callback (guestfs_h *g,
1522 guestfs_log_message_cb cb, void *opaque)
1524 g->log_message_cb = cb;
1525 g->log_message_cb_data = opaque;
1529 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1530 guestfs_subprocess_quit_cb cb, void *opaque)
1532 g->subprocess_quit_cb = cb;
1533 g->subprocess_quit_cb_data = opaque;
1537 guestfs_set_launch_done_callback (guestfs_h *g,
1538 guestfs_launch_done_cb cb, void *opaque)
1540 g->launch_done_cb = cb;
1541 g->launch_done_cb_data = opaque;
1544 /* Access to the handle's main loop and the default main loop. */
1546 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1548 g->main_loop = main_loop;
1552 guestfs_get_main_loop (guestfs_h *g)
1554 return g->main_loop;
1558 guestfs_get_default_main_loop (void)
1560 return (guestfs_main_loop *) &default_main_loop;
1563 /* Change the daemon socket handler so that we are now writing.
1564 * This sets the handle to sock_write_event.
1567 guestfs__switch_to_sending (guestfs_h *g)
1569 if (g->sock_watch >= 0) {
1570 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1571 error (g, _("remove_handle failed"));
1578 g->main_loop->add_handle (g->main_loop, g, g->sock,
1579 GUESTFS_HANDLE_WRITABLE,
1580 sock_write_event, NULL);
1581 if (g->sock_watch == -1) {
1582 error (g, _("add_handle failed"));
1590 guestfs__switch_to_receiving (guestfs_h *g)
1592 if (g->sock_watch >= 0) {
1593 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1594 error (g, _("remove_handle failed"));
1601 g->main_loop->add_handle (g->main_loop, g, g->sock,
1602 GUESTFS_HANDLE_READABLE,
1603 sock_read_event, NULL);
1604 if (g->sock_watch == -1) {
1605 error (g, _("add_handle failed"));
1612 /* Dispatch a call (len + header + args) to the remote daemon,
1613 * synchronously (ie. using the guest's main loop to wait until
1614 * it has been sent). Returns -1 for error, or the serial
1615 * number of the message.
1618 send_cb (guestfs_h *g, void *data)
1620 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1623 ml->main_loop_quit (ml, g);
1627 guestfs__send_sync (guestfs_h *g, int proc_nr,
1628 xdrproc_t xdrp, char *args)
1630 struct guestfs_message_header hdr;
1633 int serial = g->msg_next_serial++;
1635 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1637 if (g->state != BUSY) {
1638 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1642 /* This is probably an internal error. Or perhaps we should just
1643 * free the buffer anyway?
1645 if (g->msg_out != NULL) {
1646 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1650 /* We have to allocate this message buffer on the heap because
1651 * it is quite large (although will be mostly unused). We
1652 * can't allocate it on the stack because in some environments
1653 * we have quite limited stack space available, notably when
1654 * running in the JVM.
1656 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1657 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1659 /* Serialize the header. */
1660 hdr.prog = GUESTFS_PROGRAM;
1661 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1663 hdr.direction = GUESTFS_DIRECTION_CALL;
1664 hdr.serial = serial;
1665 hdr.status = GUESTFS_STATUS_OK;
1667 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1668 error (g, _("xdr_guestfs_message_header failed"));
1672 /* Serialize the args. If any, because some message types
1673 * have no parameters.
1676 if (!(*xdrp) (&xdr, args)) {
1677 error (g, _("dispatch failed to marshal args"));
1682 /* Get the actual length of the message, resize the buffer to match
1683 * the actual length, and write the length word at the beginning.
1685 len = xdr_getpos (&xdr);
1688 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1689 g->msg_out_size = len + 4;
1692 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1693 xdr_uint32_t (&xdr, &len);
1695 if (guestfs__switch_to_sending (g) == -1)
1699 guestfs_set_send_callback (g, send_cb, &sent);
1700 if (ml->main_loop_run (ml, g) == -1)
1703 error (g, _("send failed, see earlier error messages"));
1712 g->msg_out_size = 0;
1716 static int cancel = 0; /* XXX Implement file cancellation. */
1717 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1718 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1719 static int send_file_cancellation_sync (guestfs_h *g);
1720 static int send_file_complete_sync (guestfs_h *g);
1722 /* Synchronously send a file.
1726 * -2 daemon cancelled (we must read the error message)
1729 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1731 char buf[GUESTFS_MAX_CHUNK_SIZE];
1734 fd = open (filename, O_RDONLY);
1736 perrorf (g, "open: %s", filename);
1737 send_file_cancellation_sync (g);
1738 /* Daemon sees cancellation and won't reply, so caller can
1744 /* Send file in chunked encoding. */
1746 r = read (fd, buf, sizeof buf);
1747 if (r == -1 && (errno == EINTR || errno == EAGAIN))
1750 err = send_file_data_sync (g, buf, r);
1752 if (err == -2) /* daemon sent cancellation */
1753 send_file_cancellation_sync (g);
1758 if (cancel) { /* cancel from either end */
1759 send_file_cancellation_sync (g);
1764 perrorf (g, "read: %s", filename);
1765 send_file_cancellation_sync (g);
1769 /* End of file, but before we send that, we need to close
1770 * the file and check for errors.
1772 if (close (fd) == -1) {
1773 perrorf (g, "close: %s", filename);
1774 send_file_cancellation_sync (g);
1778 return send_file_complete_sync (g);
1781 /* Send a chunk of file data. */
1783 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1785 return send_file_chunk_sync (g, 0, buf, len);
1788 /* Send a cancellation message. */
1790 send_file_cancellation_sync (guestfs_h *g)
1792 return send_file_chunk_sync (g, 1, NULL, 0);
1795 /* Send a file complete chunk. */
1797 send_file_complete_sync (guestfs_h *g)
1800 return send_file_chunk_sync (g, 0, buf, 0);
1803 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1806 static int check_for_daemon_cancellation (guestfs_h *g);
1809 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
1813 guestfs_chunk chunk;
1815 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1817 if (g->state != BUSY) {
1818 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
1822 /* This is probably an internal error. Or perhaps we should just
1823 * free the buffer anyway?
1825 if (g->msg_out != NULL) {
1826 error (g, _("guestfs__send_sync: msg_out should be NULL"));
1830 /* Did the daemon send a cancellation message? */
1831 if (check_for_daemon_cancellation (g)) {
1833 fprintf (stderr, "got daemon cancellation\n");
1837 /* Allocate the chunk buffer. Don't use the stack to avoid
1838 * excessive stack usage and unnecessary copies.
1840 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
1841 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1843 /* Serialize the chunk. */
1844 chunk.cancel = cancel;
1845 chunk.data.data_len = buflen;
1846 chunk.data.data_val = (char *) buf;
1848 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1849 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
1855 len = xdr_getpos (&xdr);
1858 /* Reduce the size of the outgoing message buffer to the real length. */
1859 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1860 g->msg_out_size = len + 4;
1863 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1864 xdr_uint32_t (&xdr, &len);
1866 if (guestfs__switch_to_sending (g) == -1)
1870 guestfs_set_send_callback (g, send_cb, &sent);
1871 if (ml->main_loop_run (ml, g) == -1)
1874 error (g, _("send file chunk failed, see earlier error messages"));
1883 g->msg_out_size = 0;
1887 /* At this point we are sending FileIn file(s) to the guest, and not
1888 * expecting to read anything, so if we do read anything, it must be
1889 * a cancellation message. This checks for this case without blocking.
1892 check_for_daemon_cancellation (guestfs_h *g)
1902 FD_SET (g->sock, &rset);
1905 r = select (g->sock+1, &rset, NULL, NULL, &tv);
1907 perrorf (g, "select");
1913 /* Read the message from the daemon. */
1914 r = xread (g->sock, buf, sizeof buf);
1916 perrorf (g, "read");
1920 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1921 xdr_uint32_t (&xdr, &flag);
1924 if (flag != GUESTFS_CANCEL_FLAG) {
1925 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
1926 flag, GUESTFS_CANCEL_FLAG);
1933 /* Synchronously receive a file. */
1935 /* Returns -1 = error, 0 = EOF, 1 = more data */
1936 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
1939 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1945 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1947 perrorf (g, "open: %s", filename);
1951 /* Receive the file in chunked encoding. */
1952 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
1953 if (xwrite (fd, buf, len) == -1) {
1954 perrorf (g, "%s: write", filename);
1959 if (r == 0) break; /* End of file. */
1963 error (g, _("%s: error in chunked encoding"), filename);
1967 if (close (fd) == -1) {
1968 perrorf (g, "close: %s", filename);
1975 /* Send cancellation message to daemon, then wait until it
1976 * cancels (just throwing away data).
1980 uint32_t flag = GUESTFS_CANCEL_FLAG;
1982 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1983 xdr_uint32_t (&xdr, &flag);
1986 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1987 perrorf (g, _("write to daemon socket"));
1991 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
1992 ; /* just discard it */
1997 /* Note that the reply callback can be called multiple times before
1998 * the main loop quits and we get back to the synchronous code. So
1999 * we have to be prepared to save multiple chunks on a list here.
2001 struct receive_file_ctx {
2002 int count; /* 0 if receive_file_cb not called, or
2003 * else count number of chunks.
2005 guestfs_chunk *chunks; /* Array of chunks. */
2009 free_chunks (struct receive_file_ctx *ctx)
2013 for (i = 0; i < ctx->count; ++i)
2014 free (ctx->chunks[i].data.data_val);
2020 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2022 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2023 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2024 guestfs_chunk chunk;
2026 if (ctx->count == -1) /* Parse error occurred previously. */
2029 ml->main_loop_quit (ml, g);
2031 memset (&chunk, 0, sizeof chunk);
2033 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2034 error (g, _("failed to parse file chunk"));
2041 /* Copy the chunk to the list. */
2042 ctx->chunks = safe_realloc (g, ctx->chunks,
2043 sizeof (guestfs_chunk) * (ctx->count+1));
2044 ctx->chunks[ctx->count] = chunk;
2048 /* Receive a chunk of file data. */
2049 /* Returns -1 = error, 0 = EOF, 1 = more data */
2051 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2053 struct receive_file_ctx ctx;
2054 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2061 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2062 (void) ml->main_loop_run (ml, g);
2063 guestfs_set_reply_callback (g, NULL, NULL);
2065 if (ctx.count == 0) {
2066 error (g, _("receive_file_data_sync: reply callback not called\n"));
2070 if (ctx.count == -1) {
2071 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2072 /* callback already freed the chunks */
2077 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2079 /* Process each chunk in the list. */
2080 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2083 for (i = 0; i < ctx.count; ++i) {
2084 if (ctx.chunks[i].cancel) {
2085 error (g, _("file receive cancelled by daemon"));
2087 if (buf) free (*buf);
2088 if (len_r) *len_r = 0;
2092 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2094 if (len_r) *len_r = len;
2099 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2100 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2101 ctx.chunks[i].data.data_len);
2103 len += ctx.chunks[i].data.data_len;
2106 if (len_r) *len_r = len;
2111 /* This is the default main loop implementation, using select(2). */
2114 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2115 guestfs_handle_event_cb cb, void *data)
2117 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2119 if (fd < 0 || fd >= FD_SETSIZE) {
2120 error (g, _("fd %d is out of range"), fd);
2124 if ((events & ~(GUESTFS_HANDLE_READABLE |
2125 GUESTFS_HANDLE_WRITABLE |
2126 GUESTFS_HANDLE_HANGUP |
2127 GUESTFS_HANDLE_ERROR)) != 0) {
2128 error (g, _("set of events (0x%x) contains unknown events"), events);
2133 error (g, _("set of events is empty"));
2137 if (FD_ISSET (fd, &ml->rset) ||
2138 FD_ISSET (fd, &ml->wset) ||
2139 FD_ISSET (fd, &ml->xset)) {
2140 error (g, _("fd %d is already registered"), fd);
2145 error (g, _("callback is NULL"));
2149 if ((events & GUESTFS_HANDLE_READABLE))
2150 FD_SET (fd, &ml->rset);
2151 if ((events & GUESTFS_HANDLE_WRITABLE))
2152 FD_SET (fd, &ml->wset);
2153 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2154 FD_SET (fd, &ml->xset);
2156 if (fd > ml->max_fd) {
2158 ml->handle_cb_data =
2159 safe_realloc (g, ml->handle_cb_data,
2160 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2162 ml->handle_cb_data[fd].cb = cb;
2163 ml->handle_cb_data[fd].g = g;
2164 ml->handle_cb_data[fd].data = data;
2168 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2173 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2175 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2177 if (fd < 0 || fd >= FD_SETSIZE) {
2178 error (g, _("fd %d is out of range"), fd);
2182 if (!FD_ISSET (fd, &ml->rset) &&
2183 !FD_ISSET (fd, &ml->wset) &&
2184 !FD_ISSET (fd, &ml->xset)) {
2185 error (g, _("fd %d was not registered"), fd);
2189 FD_CLR (fd, &ml->rset);
2190 FD_CLR (fd, &ml->wset);
2191 FD_CLR (fd, &ml->xset);
2193 if (fd == ml->max_fd) {
2195 ml->handle_cb_data =
2196 safe_realloc (g, ml->handle_cb_data,
2197 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2206 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2207 guestfs_handle_timeout_cb cb, void *data)
2209 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2211 abort (); /* XXX not implemented yet */
2215 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2217 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2219 abort (); /* XXX not implemented yet */
2222 /* The 'g' parameter is just used for error reporting. Events
2223 * for multiple handles can be dispatched by running the main
2227 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2229 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2231 fd_set rset2, wset2, xset2;
2233 if (ml->is_running) {
2234 error (g, _("select_main_loop_run: this cannot be called recursively"));
2240 while (ml->is_running) {
2241 if (ml->nr_fds == 0)
2247 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2249 if (errno == EINTR || errno == EAGAIN)
2251 perrorf (g, "select");
2256 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2258 if (FD_ISSET (fd, &rset2))
2259 events |= GUESTFS_HANDLE_READABLE;
2260 if (FD_ISSET (fd, &wset2))
2261 events |= GUESTFS_HANDLE_WRITABLE;
2262 if (FD_ISSET (fd, &xset2))
2263 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2266 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2267 ml->handle_cb_data[fd].g,
2268 ml->handle_cb_data[fd].data,
2279 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2281 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2283 /* Note that legitimately ml->is_running can be zero when
2284 * this function is called.