2 * Copyright (C) 2009-2010 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 */
34 #include <sys/select.h>
37 #include <rpc/types.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
48 #ifdef HAVE_SYS_WAIT_H
52 #ifdef HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
60 #include <arpa/inet.h>
61 #include <netinet/in.h>
64 #include "glthread/lock.h"
65 #include "ignore-value.h"
68 #include "guestfs-internal.h"
69 #include "guestfs-internal-actions.h"
70 #include "guestfs_protocol.h"
74 #define _(str) dgettext(PACKAGE, (str))
75 //#define N_(str) dgettext(PACKAGE, (str))
81 #define error guestfs_error
82 #define perrorf guestfs_perrorf
83 #define safe_malloc guestfs_safe_malloc
84 #define safe_realloc guestfs_safe_realloc
85 #define safe_strdup guestfs_safe_strdup
86 //#define safe_memdup guestfs_safe_memdup
88 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
89 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
90 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
91 static int accept_from_daemon (guestfs_h *g);
92 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
93 static void close_handles (void);
94 static int qemu_supports (guestfs_h *g, const char *option);
96 #define UNIX_PATH_MAX 108
98 /* Also in guestfsd.c */
99 #define GUESTFWD_ADDR "10.0.2.4"
100 #define GUESTFWD_PORT "6666"
102 /* GuestFS handle and connection. */
103 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
107 struct guestfs_h *next; /* Linked list of open handles. */
109 /* State: see the state machine diagram in the man page guestfs(3). */
112 int fd[2]; /* Stdin/stdout of qemu. */
113 int sock; /* Daemon communications socket. */
114 pid_t pid; /* Qemu PID. */
115 pid_t recoverypid; /* Recovery process PID. */
117 struct timeval launch_t; /* The time that we called guestfs_launch. */
119 char *tmpdir; /* Temporary directory containing socket. */
121 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
123 char **cmdline; /* Qemu command line. */
132 char *path; /* Path to kernel, initrd. */
133 char *qemu; /* Qemu binary. */
134 char *append; /* Append to kernel command line. */
136 int memsize; /* Size of RAM (megabytes). */
138 int selinux; /* selinux enabled? */
143 guestfs_abort_cb abort_cb;
144 guestfs_error_handler_cb error_cb;
145 void * error_cb_data;
146 guestfs_log_message_cb log_message_cb;
147 void * log_message_cb_data;
148 guestfs_subprocess_quit_cb subprocess_quit_cb;
149 void * subprocess_quit_cb_data;
150 guestfs_launch_done_cb launch_done_cb;
151 void * launch_done_cb_data;
156 gl_lock_define_initialized (static, handles_lock);
157 static guestfs_h *handles = NULL;
158 static int atexit_handler_set = 0;
161 guestfs_create (void)
166 g = malloc (sizeof (*g));
169 memset (g, 0, sizeof (*g));
178 g->error_cb = default_error_cb;
179 g->error_cb_data = NULL;
181 g->recovery_proc = 1;
183 str = getenv ("LIBGUESTFS_DEBUG");
184 g->verbose = str != NULL && STREQ (str, "1");
186 str = getenv ("LIBGUESTFS_TRACE");
187 g->trace = str != NULL && STREQ (str, "1");
189 str = getenv ("LIBGUESTFS_PATH");
190 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
191 if (!g->path) goto error;
193 str = getenv ("LIBGUESTFS_QEMU");
194 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
195 if (!g->qemu) goto error;
197 str = getenv ("LIBGUESTFS_APPEND");
199 g->append = strdup (str);
200 if (!g->append) goto error;
203 /* Choose a suitable memory size. Previously we tried to choose
204 * a minimal memory size, but this isn't really necessary since
205 * recent QEMU and KVM don't do anything nasty like locking
206 * memory into core any more. Thus we can safely choose a
207 * large, generous amount of memory, and it'll just get swapped
208 * on smaller systems.
210 str = getenv ("LIBGUESTFS_MEMSIZE");
212 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
213 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
219 /* Start with large serial numbers so they are easy to spot
220 * inside the protocol.
222 g->msg_next_serial = 0x00123400;
224 /* Link the handles onto a global list. */
225 gl_lock_lock (handles_lock);
228 if (!atexit_handler_set) {
229 atexit (close_handles);
230 atexit_handler_set = 1;
232 gl_lock_unlock (handles_lock);
235 fprintf (stderr, "new guestfs handle %p\n", g);
248 guestfs_close (guestfs_h *g)
254 if (g->state == NO_HANDLE) {
255 /* Not safe to call 'error' here, so ... */
256 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
261 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
263 /* Try to sync if autosync flag is set. */
264 if (g->autosync && g->state == READY) {
265 guestfs_umount_all (g);
269 /* Remove any handlers that might be called back before we kill the
272 g->log_message_cb = NULL;
274 if (g->state != CONFIG)
275 guestfs_kill_subprocess (g);
288 /* Wait for subprocess(es) to exit. */
289 waitpid (g->pid, NULL, 0);
290 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
292 /* Remove tmpfiles. */
294 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
297 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
300 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
309 for (i = 0; i < g->cmdline_size; ++i)
310 free (g->cmdline[i]);
314 /* Mark the handle as dead before freeing it. */
315 g->state = NO_HANDLE;
317 gl_lock_lock (handles_lock);
321 for (gg = handles; gg->next != g; gg = gg->next)
325 gl_lock_unlock (handles_lock);
327 free (g->last_error);
332 free (g->qemu_version);
336 /* Close all open handles (called from atexit(3)). */
340 while (handles) guestfs_close (handles);
344 guestfs_last_error (guestfs_h *g)
346 return g->last_error;
350 set_last_error (guestfs_h *g, const char *msg)
352 free (g->last_error);
353 g->last_error = strdup (msg);
357 default_error_cb (guestfs_h *g, void *data, const char *msg)
359 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
363 guestfs_error (guestfs_h *g, const char *fs, ...)
369 int err = vasprintf (&msg, fs, args);
374 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
375 set_last_error (g, msg);
381 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
388 int err = vasprintf (&msg, fs, args);
395 strerror_r (errnum, buf, sizeof buf);
399 buf = strerror_r (errnum, _buf, sizeof _buf);
402 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
406 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
407 set_last_error (g, msg);
413 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
415 void *ptr = malloc (nbytes);
416 if (nbytes > 0 && !ptr) g->abort_cb ();
420 /* Return 1 if an array of N objects, each of size S, cannot exist due
421 to size arithmetic overflow. S must be positive and N must be
422 nonnegative. This is a macro, not an inline function, so that it
423 works correctly even when SIZE_MAX < N.
425 By gnulib convention, SIZE_MAX represents overflow in size
426 calculations, so the conservative dividend to use here is
427 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
428 However, malloc (SIZE_MAX) fails on all known hosts where
429 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
430 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
431 branch when S is known to be 1. */
432 # define xalloc_oversized(n, s) \
433 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
435 /* Technically we should add an autoconf test for this, testing for the desired
436 functionality, like what's done in gnulib, but for now, this is fine. */
437 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
439 /* Allocate zeroed memory for N elements of S bytes, with error
440 checking. S must be nonzero. */
442 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
444 /* From gnulib's calloc function in xmalloc.c. */
446 /* Test for overflow, since some calloc implementations don't have
447 proper overflow checks. But omit overflow and size-zero tests if
448 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
449 returns NULL if successful. */
450 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
451 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
457 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
459 void *p = realloc (ptr, nbytes);
460 if (nbytes > 0 && !p) g->abort_cb ();
465 guestfs_safe_strdup (guestfs_h *g, const char *str)
467 char *s = strdup (str);
468 if (!s) g->abort_cb ();
473 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
475 void *p = malloc (size);
476 if (!p) g->abort_cb ();
477 memcpy (p, ptr, size);
482 xwrite (int fd, const void *v_buf, size_t len)
484 const char *buf = v_buf;
488 r = write (fd, buf, len);
500 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
506 guestfs_get_out_of_memory_handler (guestfs_h *g)
512 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
515 g->error_cb_data = data;
518 guestfs_error_handler_cb
519 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
521 if (data_rtn) *data_rtn = g->error_cb_data;
526 guestfs__set_verbose (guestfs_h *g, int v)
533 guestfs__get_verbose (guestfs_h *g)
539 guestfs__set_autosync (guestfs_h *g, int a)
546 guestfs__get_autosync (guestfs_h *g)
552 guestfs__set_path (guestfs_h *g, const char *path)
559 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
564 guestfs__get_path (guestfs_h *g)
570 guestfs__set_qemu (guestfs_h *g, const char *qemu)
575 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
580 guestfs__get_qemu (guestfs_h *g)
586 guestfs__set_append (guestfs_h *g, const char *append)
591 g->append = append ? safe_strdup (g, append) : NULL;
596 guestfs__get_append (guestfs_h *g)
602 guestfs__set_memsize (guestfs_h *g, int memsize)
604 g->memsize = memsize;
609 guestfs__get_memsize (guestfs_h *g)
615 guestfs__set_selinux (guestfs_h *g, int selinux)
617 g->selinux = selinux;
622 guestfs__get_selinux (guestfs_h *g)
628 guestfs__get_pid (guestfs_h *g)
633 error (g, "get_pid: no qemu subprocess");
638 struct guestfs_version *
639 guestfs__version (guestfs_h *g)
641 struct guestfs_version *r;
643 r = safe_malloc (g, sizeof *r);
644 r->major = PACKAGE_VERSION_MAJOR;
645 r->minor = PACKAGE_VERSION_MINOR;
646 r->release = PACKAGE_VERSION_RELEASE;
647 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
652 guestfs__set_trace (guestfs_h *g, int t)
659 guestfs__get_trace (guestfs_h *g)
665 guestfs__set_direct (guestfs_h *g, int d)
672 guestfs__get_direct (guestfs_h *g)
678 guestfs__set_recovery_proc (guestfs_h *g, int f)
680 g->recovery_proc = !!f;
685 guestfs__get_recovery_proc (guestfs_h *g)
687 return g->recovery_proc;
690 /* Add a string to the current command line. */
692 incr_cmdline_size (guestfs_h *g)
694 if (g->cmdline == NULL) {
695 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
697 g->cmdline = safe_malloc (g, sizeof (char *));
698 g->cmdline[0] = NULL;
702 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
706 add_cmdline (guestfs_h *g, const char *str)
708 if (g->state != CONFIG) {
710 _("command line cannot be altered after qemu subprocess launched"));
714 incr_cmdline_size (g);
715 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
720 guestfs__config (guestfs_h *g,
721 const char *qemu_param, const char *qemu_value)
723 if (qemu_param[0] != '-') {
724 error (g, _("guestfs_config: parameter must begin with '-' character"));
728 /* A bit fascist, but the user will probably break the extra
729 * parameters that we add if they try to set any of these.
731 if (STREQ (qemu_param, "-kernel") ||
732 STREQ (qemu_param, "-initrd") ||
733 STREQ (qemu_param, "-nographic") ||
734 STREQ (qemu_param, "-serial") ||
735 STREQ (qemu_param, "-full-screen") ||
736 STREQ (qemu_param, "-std-vga") ||
737 STREQ (qemu_param, "-vnc")) {
738 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
742 if (add_cmdline (g, qemu_param) != 0) return -1;
744 if (qemu_value != NULL) {
745 if (add_cmdline (g, qemu_value) != 0) return -1;
752 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
753 const char *drive_if)
755 size_t len = strlen (filename) + 64;
758 if (strchr (filename, ',') != NULL) {
759 error (g, _("filename cannot contain ',' (comma) character"));
763 /* cache=off improves reliability in the event of a host crash.
765 * However this option causes qemu to try to open the file with
766 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
767 * So we check if we can open the file with or without O_DIRECT,
768 * and use cache=off (or not) accordingly.
770 * This test also checks for the presence of the file, which
771 * is a documented semantic of this interface.
773 int fd = open (filename, O_RDONLY|O_DIRECT);
776 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
778 fd = open (filename, O_RDONLY);
781 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
783 perrorf (g, "%s", filename);
788 return guestfs__config (g, "-drive", buf);
792 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
793 const char *drive_if)
795 if (strchr (filename, ',') != NULL) {
796 error (g, _("filename cannot contain ',' (comma) character"));
800 if (access (filename, F_OK) == -1) {
801 perrorf (g, "%s", filename);
805 if (qemu_supports (g, NULL) == -1)
808 /* Only SCSI and virtio drivers support readonly mode.
809 * This is only supported as a QEMU feature since 2010/01.
812 if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
813 qemu_supports (g, "readonly=on"))
816 size_t len = strlen (filename) + 100;
819 snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
821 supports_ro ? "readonly=on," : "",
824 return guestfs__config (g, "-drive", buf);
828 guestfs__add_drive (guestfs_h *g, const char *filename)
830 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
834 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
836 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
840 guestfs__add_cdrom (guestfs_h *g, const char *filename)
842 if (strchr (filename, ',') != NULL) {
843 error (g, _("filename cannot contain ',' (comma) character"));
847 if (access (filename, F_OK) == -1) {
848 perrorf (g, "%s", filename);
852 return guestfs__config (g, "-cdrom", filename);
855 /* Returns true iff file is contained in dir. */
857 dir_contains_file (const char *dir, const char *file)
859 int dirlen = strlen (dir);
860 int filelen = strlen (file);
861 int len = dirlen+filelen+2;
864 snprintf (path, len, "%s/%s", dir, file);
865 return access (path, F_OK) == 0;
868 /* Returns true iff every listed file is contained in 'dir'. */
870 dir_contains_files (const char *dir, ...)
875 va_start (args, dir);
876 while ((file = va_arg (args, const char *)) != NULL) {
877 if (!dir_contains_file (dir, file)) {
886 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
887 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
888 static int is_openable (guestfs_h *g, const char *path, int flags);
889 static void print_cmdline (guestfs_h *g);
891 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
892 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
893 static const char *supermin_name =
894 "initramfs." REPO "." host_cpu ".supermin.img";
895 static const char *supermin_hostfiles_name =
896 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
899 guestfs__launch (guestfs_h *g)
902 char dir_template[PATH_MAX];
907 char *path, *pelem, *pend;
908 char *kernel = NULL, *initrd = NULL;
909 int null_vmchannel_sock;
911 struct sockaddr_un addr;
913 /* Start the clock ... */
914 gettimeofday (&g->launch_t, NULL);
922 tmpdir = getenv ("TMPDIR") ? : tmpdir;
923 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
927 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
931 if (g->state != CONFIG) {
932 error (g, _("qemu has already been launched"));
936 /* Make the temporary directory. */
938 g->tmpdir = safe_strdup (g, dir_template);
939 if (mkdtemp (g->tmpdir) == NULL) {
940 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
945 /* First search g->path for the supermin appliance, and try to
946 * synthesize a kernel and initrd from that. If it fails, we
947 * try the path search again looking for a backup ordinary
950 pelem = path = safe_strdup (g, g->path);
952 pend = strchrnul (pelem, ':');
953 pmore = *pend == ':';
957 /* Empty element of "." means cwd. */
958 if (len == 0 || (len == 1 && *pelem == '.')) {
961 "looking for supermin appliance in current directory\n");
962 if (dir_contains_files (".",
963 supermin_name, supermin_hostfiles_name,
964 "kmod.whitelist", NULL)) {
965 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
970 /* Look at <path>/supermin* etc. */
973 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
975 if (dir_contains_files (pelem,
976 supermin_name, supermin_hostfiles_name,
977 "kmod.whitelist", NULL)) {
978 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
989 if (kernel == NULL || initrd == NULL) {
990 /* Search g->path for the kernel and initrd. */
991 pelem = path = safe_strdup (g, g->path);
993 pend = strchrnul (pelem, ':');
994 pmore = *pend == ':';
998 /* Empty element or "." means cwd. */
999 if (len == 0 || (len == 1 && *pelem == '.')) {
1002 "looking for appliance in current directory\n");
1003 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1004 kernel = safe_strdup (g, kernel_name);
1005 initrd = safe_strdup (g, initrd_name);
1009 /* Look at <path>/kernel etc. */
1012 fprintf (stderr, "looking for appliance in %s\n", pelem);
1014 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1015 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1016 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1017 sprintf (kernel, "%s/%s", pelem, kernel_name);
1018 sprintf (initrd, "%s/%s", pelem, initrd_name);
1029 if (kernel == NULL || initrd == NULL) {
1030 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1031 kernel_name, initrd_name, g->path);
1036 print_timestamped_message (g, "begin testing qemu features");
1038 /* Get qemu help text and version. */
1039 if (qemu_supports (g, NULL) == -1)
1042 /* Choose which vmchannel implementation to use. */
1043 if (qemu_supports (g, "-net user")) {
1044 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1045 * networking in qemu) but no other vmchannel support. The daemon
1046 * will connect back to a random port number on localhost.
1048 struct sockaddr_in addr;
1049 socklen_t addrlen = sizeof addr;
1051 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1052 if (g->sock == -1) {
1053 perrorf (g, "socket");
1056 addr.sin_family = AF_INET;
1057 addr.sin_port = htons (0);
1058 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1059 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1060 perrorf (g, "bind");
1064 if (listen (g->sock, 256) == -1) {
1065 perrorf (g, "listen");
1069 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1070 perrorf (g, "getsockname");
1074 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1075 perrorf (g, "fcntl");
1079 null_vmchannel_sock = ntohs (addr.sin_port);
1081 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1083 /* Using some vmchannel impl. We need to create a local Unix
1084 * domain socket for qemu to use.
1086 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1088 null_vmchannel_sock = 0;
1092 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1093 perrorf (g, "pipe");
1099 print_timestamped_message (g, "finished testing qemu features");
1103 perrorf (g, "fork");
1113 if (r == 0) { /* Child (qemu). */
1115 const char *vmchannel = NULL;
1117 /* Set up the full command line. Do this in the subprocess so we
1118 * don't need to worry about cleaning up.
1120 g->cmdline[0] = g->qemu;
1122 /* qemu sometimes needs this option to enable hardware
1123 * virtualization, but some versions of 'qemu-kvm' will use KVM
1124 * regardless (even where this option appears in the help text).
1125 * It is rumoured that there are versions of qemu where supplying
1126 * this option when hardware virtualization is not available will
1127 * cause qemu to fail, so we we have to check at least that
1128 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1129 * might be openable by qemu but not by us (think: SELinux) in
1130 * which case the user would not get hardware virtualization,
1131 * although at least shouldn't fail. A giant clusterfuck with the
1132 * qemu command line, again.
1134 if (qemu_supports (g, "-enable-kvm") &&
1135 is_openable (g, "/dev/kvm", O_RDWR))
1136 add_cmdline (g, "-enable-kvm");
1138 /* Newer versions of qemu (from around 2009/12) changed the
1139 * behaviour of monitors so that an implicit '-monitor stdio' is
1140 * assumed if we are in -nographic mode and there is no other
1141 * -monitor option. Only a single stdio device is allowed, so
1142 * this broke the '-serial stdio' option. There is a new flag
1143 * called -nodefaults which gets rid of all this default crud, so
1144 * let's use that to avoid this and any future surprises.
1146 if (qemu_supports (g, "-nodefaults"))
1147 add_cmdline (g, "-nodefaults");
1149 add_cmdline (g, "-nographic");
1150 add_cmdline (g, "-serial");
1151 add_cmdline (g, "stdio");
1153 snprintf (buf, sizeof buf, "%d", g->memsize);
1154 add_cmdline (g, "-m");
1155 add_cmdline (g, buf);
1157 /* Force exit instead of reboot on panic */
1158 add_cmdline (g, "-no-reboot");
1160 /* These options recommended by KVM developers to improve reliability. */
1161 if (qemu_supports (g, "-no-hpet"))
1162 add_cmdline (g, "-no-hpet");
1164 if (qemu_supports (g, "-rtc-td-hack"))
1165 add_cmdline (g, "-rtc-td-hack");
1167 /* If qemu has SLIRP (user mode network) enabled then we can get
1168 * away with "no vmchannel", where we just connect back to a random
1171 if (null_vmchannel_sock) {
1172 add_cmdline (g, "-net");
1173 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1175 snprintf (buf, sizeof buf,
1176 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1177 vmchannel = strdup (buf);
1180 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1182 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1184 * The original suggested format doesn't work, see:
1186 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1188 * However Gerd Hoffman privately suggested to me using -chardev
1189 * instead, which does work.
1191 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1192 snprintf (buf, sizeof buf,
1193 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1195 add_cmdline (g, "-chardev");
1196 add_cmdline (g, buf);
1198 snprintf (buf, sizeof buf,
1199 "user,vlan=0,net=10.0.2.0/8,"
1200 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1201 "-chardev:guestfsvmc");
1203 add_cmdline (g, "-net");
1204 add_cmdline (g, buf);
1206 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1209 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1210 * syntax, or if not then we'll get a quick failure.
1213 snprintf (buf, sizeof buf,
1214 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1216 add_cmdline (g, "-net");
1217 add_cmdline (g, buf);
1218 add_cmdline (g, "-net");
1219 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1221 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1223 add_cmdline (g, "-net");
1224 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1226 #define LINUX_CMDLINE \
1227 "panic=1 " /* force kernel to panic if daemon exits */ \
1228 "console=ttyS0 " /* serial console */ \
1229 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1230 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1231 "acpi=off " /* we don't need ACPI, turn it off */ \
1232 "printk.time=1 " /* display timestamp before kernel messages */ \
1233 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1235 /* Linux kernel command line. */
1236 snprintf (buf, sizeof buf,
1238 "%s " /* (selinux) */
1239 "%s " /* (vmchannel) */
1240 "%s " /* (verbose) */
1241 "%s", /* (append) */
1242 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1243 vmchannel ? vmchannel : "",
1244 g->verbose ? "guestfs_verbose=1" : "",
1245 g->append ? g->append : "");
1247 add_cmdline (g, "-kernel");
1248 add_cmdline (g, (char *) kernel);
1249 add_cmdline (g, "-initrd");
1250 add_cmdline (g, (char *) initrd);
1251 add_cmdline (g, "-append");
1252 add_cmdline (g, buf);
1254 /* Finish off the command line. */
1255 incr_cmdline_size (g);
1256 g->cmdline[g->cmdline_size-1] = NULL;
1262 /* Set up stdin, stdout. */
1268 if (dup (wfd[0]) == -1) {
1270 perror ("dup failed");
1273 if (dup (rfd[1]) == -1)
1281 /* Set up a new process group, so we can signal this process
1282 * and all subprocesses (eg. if qemu is really a shell script).
1287 setenv ("LC_ALL", "C", 1);
1289 execv (g->qemu, g->cmdline); /* Run qemu. */
1294 /* Parent (library). */
1302 /* Fork the recovery process off which will kill qemu if the parent
1303 * process fails to do so (eg. if the parent segfaults).
1305 g->recoverypid = -1;
1306 if (g->recovery_proc) {
1309 pid_t qemu_pid = g->pid;
1310 pid_t parent_pid = getppid ();
1312 /* Writing to argv is hideously complicated and error prone. See:
1313 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1316 /* Loop around waiting for one or both of the other processes to
1317 * disappear. It's fair to say this is very hairy. The PIDs that
1318 * we are looking at might be reused by another process. We are
1319 * effectively polling. Is the cure worse than the disease?
1322 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1324 if (kill (parent_pid, 0) == -1) {
1325 /* Parent's gone away, qemu still around, so kill qemu. */
1333 /* Don't worry, if the fork failed, this will be -1. The recovery
1334 * process isn't essential.
1340 /* Close the other ends of the pipe. */
1344 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1345 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1346 perrorf (g, "fcntl");
1350 g->fd[0] = wfd[1]; /* stdin of child */
1351 g->fd[1] = rfd[0]; /* stdout of child */
1353 g->fd[0] = open ("/dev/null", O_RDWR);
1354 if (g->fd[0] == -1) {
1355 perrorf (g, "open /dev/null");
1358 g->fd[1] = dup (g->fd[0]);
1359 if (g->fd[1] == -1) {
1366 if (null_vmchannel_sock) {
1370 /* Null vmchannel implementation: We listen on g->sock for a
1371 * connection. The connection could come from any local process
1372 * so we must check it comes from the appliance (or at least
1373 * from our UID) for security reasons.
1375 while (sock == -1) {
1376 sock = accept_from_daemon (g);
1380 if (check_peer_euid (g, sock, &uid) == -1)
1382 if (uid != geteuid ()) {
1384 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1385 uid, null_vmchannel_sock);
1391 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1392 perrorf (g, "fcntl");
1399 /* Other vmchannel. Open the Unix socket.
1401 * The vmchannel implementation that got merged with qemu sucks in
1402 * a number of ways. Both ends do connect(2), which means that no
1403 * one knows what, if anything, is connected to the other end, or
1404 * if it becomes disconnected. Even worse, we have to wait some
1405 * indeterminate time for qemu to create the socket and connect to
1406 * it (which happens very early in qemu's start-up), so any code
1407 * that uses vmchannel is inherently racy. Hence this silly loop.
1409 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1410 if (g->sock == -1) {
1411 perrorf (g, "socket");
1415 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1416 perrorf (g, "fcntl");
1420 addr.sun_family = AF_UNIX;
1421 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1422 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1425 /* Always sleep at least once to give qemu a small chance to start up. */
1428 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1429 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1432 if (errno != ENOENT)
1433 perrorf (g, "connect");
1438 error (g, _("failed to connect to vmchannel socket"));
1444 g->state = LAUNCHING;
1446 /* Wait for qemu to start and to connect back to us via vmchannel and
1447 * send the GUESTFS_LAUNCH_FLAG message.
1451 r = recv_from_daemon (g, &size, &buf);
1454 if (r == -1) return -1;
1456 if (size != GUESTFS_LAUNCH_FLAG) {
1457 error (g, _("guestfs_launch failed, see earlier error messages"));
1462 print_timestamped_message (g, "appliance is up");
1464 /* This is possible in some really strange situations, such as
1465 * guestfsd starts up OK but then qemu immediately exits. Check for
1466 * it because the caller is probably expecting to be able to send
1467 * commands after this function returns.
1469 if (g->state != READY) {
1470 error (g, _("qemu launched and contacted daemon, but state != READY"));
1482 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1483 waitpid (g->pid, NULL, 0);
1484 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1489 memset (&g->launch_t, 0, sizeof g->launch_t);
1502 /* This function is used to print the qemu command line before it gets
1503 * executed, when in verbose mode.
1506 print_cmdline (guestfs_h *g)
1511 while (g->cmdline[i]) {
1512 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1513 fprintf (stderr, " \\\n ");
1515 if (i > 0) fputc (' ', stderr);
1517 /* Does it need shell quoting? This only deals with simple cases. */
1518 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1520 if (needs_quote) fputc ('\'', stderr);
1521 fprintf (stderr, "%s", g->cmdline[i]);
1522 if (needs_quote) fputc ('\'', stderr);
1526 fputc ('\n', stderr);
1529 /* This function does the hard work of building the supermin appliance
1530 * on the fly. 'path' is the directory containing the control files.
1531 * 'kernel' and 'initrd' are where we will return the names of the
1532 * kernel and initrd (only initrd is built). The work is done by
1533 * an external script. We just tell it where to put the result.
1536 build_supermin_appliance (guestfs_h *g, const char *path,
1537 char **kernel, char **initrd)
1543 print_timestamped_message (g, "begin building supermin appliance");
1545 len = strlen (g->tmpdir);
1546 *kernel = safe_malloc (g, len + 8);
1547 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1548 *initrd = safe_malloc (g, len + 8);
1549 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1551 snprintf (cmd, sizeof cmd,
1553 "libguestfs-supermin-helper%s '%s' " host_cpu " " REPO " %s %s",
1555 g->verbose ? " --verbose" : "",
1556 path, *kernel, *initrd);
1558 print_timestamped_message (g, "%s", cmd);
1561 if (r == -1 || WEXITSTATUS(r) != 0) {
1562 error (g, _("external command failed: %s"), cmd);
1565 *kernel = *initrd = NULL;
1570 print_timestamped_message (g, "finished building supermin appliance");
1575 /* Compute Y - X and return the result in milliseconds.
1576 * Approximately the same as this code:
1577 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1580 timeval_diff (const struct timeval *x, const struct timeval *y)
1584 msec = (y->tv_sec - x->tv_sec) * 1000;
1585 msec += (y->tv_usec - x->tv_usec) / 1000;
1590 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1597 va_start (args, fs);
1598 err = vasprintf (&msg, fs, args);
1601 if (err < 0) return;
1603 gettimeofday (&tv, NULL);
1605 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1606 timeval_diff (&g->launch_t, &tv), msg);
1611 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1613 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1614 * 'qemu -version' so we know what options this qemu supports and
1618 test_qemu (guestfs_h *g)
1623 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1625 fp = popen (cmd, "r");
1626 /* qemu -help should always work (qemu -version OTOH wasn't
1627 * supported by qemu 0.9). If this command doesn't work then it
1628 * probably indicates that the qemu binary is missing.
1631 /* XXX This error is never printed, even if the qemu binary
1632 * doesn't exist. Why?
1635 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1639 if (read_all (g, fp, &g->qemu_help) == -1)
1642 if (pclose (fp) == -1)
1645 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1648 fp = popen (cmd, "r");
1650 /* Intentionally ignore errors. */
1651 read_all (g, fp, &g->qemu_version);
1659 read_all (guestfs_h *g, FILE *fp, char **ret)
1666 *ret = safe_realloc (g, *ret, n + 1);
1671 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1673 r = fread (p, 1, BUFSIZ, fp);
1675 perrorf (g, "read");
1682 /* Test if option is supported by qemu command line (just by grepping
1685 * The first time this is used, it has to run the external qemu
1686 * binary. If that fails, it returns -1.
1688 * To just do the first-time run of the qemu binary, call this with
1689 * option == NULL, in which case it will return -1 if there was an
1693 qemu_supports (guestfs_h *g, const char *option)
1695 if (!g->qemu_help) {
1696 if (test_qemu (g) == -1)
1703 return strstr (g->qemu_help, option) != NULL;
1706 /* Check if a file can be opened. */
1708 is_openable (guestfs_h *g, const char *path, int flags)
1710 int fd = open (path, flags);
1720 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1721 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1722 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1725 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1727 struct sockaddr_in peer;
1728 socklen_t addrlen = sizeof peer;
1730 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1731 perrorf (g, "getpeername");
1735 if (peer.sin_family != AF_INET ||
1736 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1737 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1738 peer.sin_family, inet_ntoa (peer.sin_addr));
1742 struct sockaddr_in our;
1743 addrlen = sizeof our;
1744 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1745 perrorf (g, "getsockname");
1749 FILE *fp = fopen ("/proc/net/tcp", "r");
1751 perrorf (g, "/proc/net/tcp");
1756 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1757 error (g, "unexpected end of file in /proc/net/tcp");
1762 while (fgets (line, sizeof line, fp) != NULL) {
1763 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1764 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1767 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1769 &line_our_addr, &line_our_port,
1770 &line_peer_addr, &line_peer_port,
1771 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1773 /* Note about /proc/net/tcp: local_address and rem_address are
1774 * always in network byte order. However the port part is
1775 * always in host byte order.
1777 * The sockname and peername that we got above are in network
1778 * byte order. So we have to byte swap the port but not the
1781 if (line_our_addr == our.sin_addr.s_addr &&
1782 line_our_port == ntohs (our.sin_port) &&
1783 line_peer_addr == peer.sin_addr.s_addr &&
1784 line_peer_port == ntohs (peer.sin_port)) {
1792 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1797 /* You had to call this function after launch in versions <= 1.0.70,
1798 * but it is now a no-op.
1801 guestfs__wait_ready (guestfs_h *g)
1803 if (g->state != READY) {
1804 error (g, _("qemu has not been launched yet"));
1812 guestfs__kill_subprocess (guestfs_h *g)
1814 if (g->state == CONFIG) {
1815 error (g, _("no subprocess to kill"));
1820 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1822 kill (g->pid, SIGTERM);
1823 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1828 /* Access current state. */
1830 guestfs__is_config (guestfs_h *g)
1832 return g->state == CONFIG;
1836 guestfs__is_launching (guestfs_h *g)
1838 return g->state == LAUNCHING;
1842 guestfs__is_ready (guestfs_h *g)
1844 return g->state == READY;
1848 guestfs__is_busy (guestfs_h *g)
1850 return g->state == BUSY;
1854 guestfs__get_state (guestfs_h *g)
1860 guestfs_set_log_message_callback (guestfs_h *g,
1861 guestfs_log_message_cb cb, void *opaque)
1863 g->log_message_cb = cb;
1864 g->log_message_cb_data = opaque;
1868 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1869 guestfs_subprocess_quit_cb cb, void *opaque)
1871 g->subprocess_quit_cb = cb;
1872 g->subprocess_quit_cb_data = opaque;
1876 guestfs_set_launch_done_callback (guestfs_h *g,
1877 guestfs_launch_done_cb cb, void *opaque)
1879 g->launch_done_cb = cb;
1880 g->launch_done_cb_data = opaque;
1883 /*----------------------------------------------------------------------*/
1885 /* This is the code used to send and receive RPC messages and (for
1886 * certain types of message) to perform file transfers. This code is
1887 * driven from the generated actions (src/guestfs-actions.c). There
1888 * are five different cases to consider:
1890 * (1) A non-daemon function. There is no RPC involved at all, it's
1891 * all handled inside the library.
1893 * (2) A simple RPC (eg. "mount"). We write the request, then read
1894 * the reply. The sequence of calls is:
1896 * guestfs___set_busy
1899 * guestfs___end_busy
1901 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1902 * request, then write the file(s), then read the reply. The sequence
1905 * guestfs___set_busy
1907 * guestfs___send_file (possibly multiple times)
1909 * guestfs___end_busy
1911 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1912 * request, then read the reply, then read the file(s). The sequence
1915 * guestfs___set_busy
1918 * guestfs___recv_file (possibly multiple times)
1919 * guestfs___end_busy
1921 * (5) Both FileOut and FileIn parameters. There are no calls like
1922 * this in the current API, but they would be implemented as a
1923 * combination of cases (3) and (4).
1925 * During all writes and reads, we also select(2) on qemu stdout
1926 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1927 * anything received is passed up through the log_message_cb. This is
1928 * also the reason why all the sockets are non-blocking. We also have
1929 * to check for EOF (qemu died). All of this is handled by the
1930 * functions send_to_daemon and recv_from_daemon.
1934 guestfs___set_busy (guestfs_h *g)
1936 if (g->state != READY) {
1937 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1946 guestfs___end_busy (guestfs_h *g)
1960 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1966 /* This is called if we detect EOF, ie. qemu died. */
1968 child_cleanup (guestfs_h *g)
1971 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1973 /*kill (g->pid, SIGTERM);*/
1974 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1975 waitpid (g->pid, NULL, 0);
1976 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1985 memset (&g->launch_t, 0, sizeof g->launch_t);
1987 if (g->subprocess_quit_cb)
1988 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1992 read_log_message_or_eof (guestfs_h *g, int fd)
2000 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2004 /* QEMU's console emulates a 16550A serial port. The real 16550A
2005 * device has a small FIFO buffer (16 bytes) which means here we see
2006 * lots of small reads of 1-16 bytes in length, usually single
2009 n = read (fd, buf, sizeof buf);
2011 /* Hopefully this indicates the qemu child process has died. */
2017 if (errno == EINTR || errno == EAGAIN)
2020 perrorf (g, "read");
2024 /* In verbose mode, copy all log messages to stderr. */
2026 ignore_value (write (STDERR_FILENO, buf, n));
2028 /* It's an actual log message, send it upwards if anyone is listening. */
2029 if (g->log_message_cb)
2030 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2036 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2045 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2048 n = read (fd, buf, 4);
2050 /* Hopefully this indicates the qemu child process has died. */
2056 if (errno == EINTR || errno == EAGAIN)
2059 perrorf (g, "read");
2063 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2064 xdr_uint32_t (&xdr, &flag);
2067 if (flag != GUESTFS_CANCEL_FLAG) {
2068 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2069 flag, GUESTFS_CANCEL_FLAG);
2076 /* This writes the whole N bytes of BUF to the daemon socket.
2078 * If the whole write is successful, it returns 0.
2079 * If there was an error, it returns -1.
2080 * If the daemon sent a cancellation message, it returns -2.
2082 * It also checks qemu stdout for log messages and passes those up
2083 * through log_message_cb.
2085 * It also checks for EOF (qemu died) and passes that up through the
2086 * child_cleanup function above.
2089 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2091 const char *buf = v_buf;
2097 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2102 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2103 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2104 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2106 int max_fd = MAX (g->sock, g->fd[1]);
2111 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2113 if (errno == EINTR || errno == EAGAIN)
2115 perrorf (g, "select");
2119 if (FD_ISSET (g->fd[1], &rset2)) {
2120 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2123 if (FD_ISSET (g->sock, &rset2)) {
2124 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2128 if (FD_ISSET (g->sock, &wset2)) {
2129 r = write (g->sock, buf, n);
2131 if (errno == EINTR || errno == EAGAIN)
2133 perrorf (g, "write");
2134 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2146 /* This reads a single message, file chunk, launch flag or
2147 * cancellation flag from the daemon. If something was read, it
2148 * returns 0, otherwise -1.
2150 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2152 * *size_rtn returns the size of the returned message or it may be
2153 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2155 * *buf_rtn is returned containing the message (if any) or will be set
2156 * to NULL. *buf_rtn must be freed by the caller.
2158 * It also checks qemu stdout for log messages and passes those up
2159 * through log_message_cb.
2161 * It also checks for EOF (qemu died) and passes that up through the
2162 * child_cleanup function above.
2165 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2171 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2172 g, g->state, size_rtn, buf_rtn);
2176 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2177 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2179 int max_fd = MAX (g->sock, g->fd[1]);
2185 /* nr is the size of the message, but we prime it as -4 because we
2186 * have to read the message length word first.
2190 while (nr < (ssize_t) *size_rtn) {
2192 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2194 if (errno == EINTR || errno == EAGAIN)
2196 perrorf (g, "select");
2202 if (FD_ISSET (g->fd[1], &rset2)) {
2203 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2209 if (FD_ISSET (g->sock, &rset2)) {
2210 if (nr < 0) { /* Have we read the message length word yet? */
2211 r = read (g->sock, lenbuf+nr+4, -nr);
2213 if (errno == EINTR || errno == EAGAIN)
2216 perrorf (g, "read");
2217 /* Under some circumstances we see "Connection reset by peer"
2218 * here when the child dies suddenly. Catch this and call
2219 * the cleanup function, same as for EOF.
2221 if (err == ECONNRESET)
2226 error (g, _("unexpected end of file when reading from daemon"));
2232 if (nr < 0) /* Still not got the whole length word. */
2236 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2237 xdr_uint32_t (&xdr, size_rtn);
2240 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2241 if (g->state != LAUNCHING)
2242 error (g, _("received magic signature from guestfsd, but in state %d"),
2246 if (g->launch_done_cb)
2247 g->launch_done_cb (g, g->launch_done_cb_data);
2251 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2253 /* If this happens, it's pretty bad and we've probably lost
2256 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2257 error (g, _("message length (%u) > maximum possible size (%d)"),
2258 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2262 /* Allocate the complete buffer, size now known. */
2263 *buf_rtn = safe_malloc (g, *size_rtn);
2267 size_t sizetoread = *size_rtn - nr;
2268 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2270 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2272 if (errno == EINTR || errno == EAGAIN)
2274 perrorf (g, "read");
2280 error (g, _("unexpected end of file when reading from daemon"));
2290 /* Got the full message, caller can start processing it. */
2291 #ifdef ENABLE_PACKET_DUMP
2295 for (i = 0; i < nr; i += 16) {
2296 printf ("%04zx: ", i);
2297 for (j = i; j < MIN (i+16, nr); ++j)
2298 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2299 for (; j < i+16; ++j)
2302 for (j = i; j < MIN (i+16, nr); ++j)
2303 if (c_isprint ((*(char **)buf_rtn)[j]))
2304 printf ("%c", (*(char **)buf_rtn)[j]);
2307 for (; j < i+16; ++j)
2317 /* This is very much like recv_from_daemon above, but g->sock is
2318 * a listening socket and we are accepting a new connection on
2319 * that socket instead of reading anything. Returns the newly
2323 accept_from_daemon (guestfs_h *g)
2329 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2333 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2334 FD_SET (g->sock, &rset); /* Read socket for accept. */
2336 int max_fd = MAX (g->sock, g->fd[1]);
2339 while (sock == -1) {
2341 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2343 if (errno == EINTR || errno == EAGAIN)
2345 perrorf (g, "select");
2349 if (FD_ISSET (g->fd[1], &rset2)) {
2350 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2353 if (FD_ISSET (g->sock, &rset2)) {
2354 sock = accept (g->sock, NULL, NULL);
2356 if (errno == EINTR || errno == EAGAIN)
2358 perrorf (g, "accept");
2368 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2370 struct guestfs_message_header hdr;
2373 int serial = g->msg_next_serial++;
2376 size_t msg_out_size;
2378 if (g->state != BUSY) {
2379 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2383 /* We have to allocate this message buffer on the heap because
2384 * it is quite large (although will be mostly unused). We
2385 * can't allocate it on the stack because in some environments
2386 * we have quite limited stack space available, notably when
2387 * running in the JVM.
2389 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2390 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2392 /* Serialize the header. */
2393 hdr.prog = GUESTFS_PROGRAM;
2394 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2396 hdr.direction = GUESTFS_DIRECTION_CALL;
2397 hdr.serial = serial;
2398 hdr.status = GUESTFS_STATUS_OK;
2400 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2401 error (g, _("xdr_guestfs_message_header failed"));
2405 /* Serialize the args. If any, because some message types
2406 * have no parameters.
2409 if (!(*xdrp) (&xdr, args)) {
2410 error (g, _("dispatch failed to marshal args"));
2415 /* Get the actual length of the message, resize the buffer to match
2416 * the actual length, and write the length word at the beginning.
2418 len = xdr_getpos (&xdr);
2421 msg_out = safe_realloc (g, msg_out, len + 4);
2422 msg_out_size = len + 4;
2424 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2425 xdr_uint32_t (&xdr, &len);
2428 r = send_to_daemon (g, msg_out, msg_out_size);
2429 if (r == -2) /* Ignore stray daemon cancellations. */
2442 static int cancel = 0; /* XXX Implement file cancellation. */
2443 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2444 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2445 static int send_file_cancellation (guestfs_h *g);
2446 static int send_file_complete (guestfs_h *g);
2452 * -2 daemon cancelled (we must read the error message)
2455 guestfs___send_file (guestfs_h *g, const char *filename)
2457 char buf[GUESTFS_MAX_CHUNK_SIZE];
2460 fd = open (filename, O_RDONLY);
2462 perrorf (g, "open: %s", filename);
2463 send_file_cancellation (g);
2464 /* Daemon sees cancellation and won't reply, so caller can
2470 /* Send file in chunked encoding. */
2472 r = read (fd, buf, sizeof buf);
2473 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2476 err = send_file_data (g, buf, r);
2478 if (err == -2) /* daemon sent cancellation */
2479 send_file_cancellation (g);
2484 if (cancel) { /* cancel from either end */
2485 send_file_cancellation (g);
2490 perrorf (g, "read: %s", filename);
2491 send_file_cancellation (g);
2495 /* End of file, but before we send that, we need to close
2496 * the file and check for errors.
2498 if (close (fd) == -1) {
2499 perrorf (g, "close: %s", filename);
2500 send_file_cancellation (g);
2504 return send_file_complete (g);
2507 /* Send a chunk of file data. */
2509 send_file_data (guestfs_h *g, const char *buf, size_t len)
2511 return send_file_chunk (g, 0, buf, len);
2514 /* Send a cancellation message. */
2516 send_file_cancellation (guestfs_h *g)
2518 return send_file_chunk (g, 1, NULL, 0);
2521 /* Send a file complete chunk. */
2523 send_file_complete (guestfs_h *g)
2526 return send_file_chunk (g, 0, buf, 0);
2530 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2534 guestfs_chunk chunk;
2537 size_t msg_out_size;
2539 if (g->state != BUSY) {
2540 error (g, _("send_file_chunk: state %d != READY"), g->state);
2544 /* Allocate the chunk buffer. Don't use the stack to avoid
2545 * excessive stack usage and unnecessary copies.
2547 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2548 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2550 /* Serialize the chunk. */
2551 chunk.cancel = cancel;
2552 chunk.data.data_len = buflen;
2553 chunk.data.data_val = (char *) buf;
2555 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2556 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2562 len = xdr_getpos (&xdr);
2565 /* Reduce the size of the outgoing message buffer to the real length. */
2566 msg_out = safe_realloc (g, msg_out, len + 4);
2567 msg_out_size = len + 4;
2569 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2570 xdr_uint32_t (&xdr, &len);
2572 r = send_to_daemon (g, msg_out, msg_out_size);
2574 /* Did the daemon send a cancellation message? */
2577 fprintf (stderr, "got daemon cancellation\n");
2593 /* Receive a reply. */
2595 guestfs___recv (guestfs_h *g, const char *fn,
2596 guestfs_message_header *hdr,
2597 guestfs_message_error *err,
2598 xdrproc_t xdrp, char *ret)
2606 r = recv_from_daemon (g, &size, &buf);
2610 /* This can happen if a cancellation happens right at the end
2611 * of us sending a FileIn parameter to the daemon. Discard. The
2612 * daemon should send us an error message next.
2614 if (size == GUESTFS_CANCEL_FLAG)
2617 if (size == GUESTFS_LAUNCH_FLAG) {
2618 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2622 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2624 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2625 error (g, "%s: failed to parse reply header", fn);
2630 if (hdr->status == GUESTFS_STATUS_ERROR) {
2631 if (!xdr_guestfs_message_error (&xdr, err)) {
2632 error (g, "%s: failed to parse reply error", fn);
2638 if (xdrp && ret && !xdrp (&xdr, ret)) {
2639 error (g, "%s: failed to parse reply", fn);
2651 /* Receive a file. */
2653 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2654 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2657 guestfs___recv_file (guestfs_h *g, const char *filename)
2662 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2664 perrorf (g, "open: %s", filename);
2668 /* Receive the file in chunked encoding. */
2669 while ((r = receive_file_data (g, &buf)) > 0) {
2670 if (xwrite (fd, buf, r) == -1) {
2671 perrorf (g, "%s: write", filename);
2679 error (g, _("%s: error in chunked encoding"), filename);
2683 if (close (fd) == -1) {
2684 perrorf (g, "close: %s", filename);
2691 /* Send cancellation message to daemon, then wait until it
2692 * cancels (just throwing away data).
2696 uint32_t flag = GUESTFS_CANCEL_FLAG;
2699 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2702 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2703 xdr_uint32_t (&xdr, &flag);
2706 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2707 perrorf (g, _("write to daemon socket"));
2711 while (receive_file_data (g, NULL) > 0)
2712 ; /* just discard it */
2717 /* Receive a chunk of file data. */
2718 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2720 receive_file_data (guestfs_h *g, void **buf_r)
2726 guestfs_chunk chunk;
2728 r = recv_from_daemon (g, &len, &buf);
2730 error (g, _("receive_file_data: parse error in reply callback"));
2734 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2735 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2739 memset (&chunk, 0, sizeof chunk);
2741 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2742 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2743 error (g, _("failed to parse file chunk"));
2748 /* After decoding, the original buffer is no longer used. */
2752 error (g, _("file receive cancelled by daemon"));
2753 free (chunk.data.data_val);
2757 if (chunk.data.data_len == 0) { /* end of transfer */
2758 free (chunk.data.data_val);
2762 if (buf_r) *buf_r = chunk.data.data_val;
2763 else free (chunk.data.data_val); /* else caller frees */
2765 return chunk.data.data_len;