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);
95 #define UNIX_PATH_MAX 108
97 /* Also in guestfsd.c */
98 #define GUESTFWD_ADDR "10.0.2.4"
99 #define GUESTFWD_PORT "6666"
101 /* GuestFS handle and connection. */
102 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
106 struct guestfs_h *next; /* Linked list of open handles. */
108 /* State: see the state machine diagram in the man page guestfs(3). */
111 int fd[2]; /* Stdin/stdout of qemu. */
112 int sock; /* Daemon communications socket. */
113 pid_t pid; /* Qemu PID. */
114 pid_t recoverypid; /* Recovery process PID. */
116 struct timeval launch_t; /* The time that we called guestfs_launch. */
118 char *tmpdir; /* Temporary directory containing socket. */
120 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
122 char **cmdline; /* Qemu command line. */
131 char *path; /* Path to kernel, initrd. */
132 char *qemu; /* Qemu binary. */
133 char *append; /* Append to kernel command line. */
135 int memsize; /* Size of RAM (megabytes). */
137 int selinux; /* selinux enabled? */
142 guestfs_abort_cb abort_cb;
143 guestfs_error_handler_cb error_cb;
144 void * error_cb_data;
145 guestfs_log_message_cb log_message_cb;
146 void * log_message_cb_data;
147 guestfs_subprocess_quit_cb subprocess_quit_cb;
148 void * subprocess_quit_cb_data;
149 guestfs_launch_done_cb launch_done_cb;
150 void * launch_done_cb_data;
155 gl_lock_define_initialized (static, handles_lock);
156 static guestfs_h *handles = NULL;
157 static int atexit_handler_set = 0;
160 guestfs_create (void)
165 g = malloc (sizeof (*g));
168 memset (g, 0, sizeof (*g));
177 g->error_cb = default_error_cb;
178 g->error_cb_data = NULL;
180 g->recovery_proc = 1;
182 str = getenv ("LIBGUESTFS_DEBUG");
183 g->verbose = str != NULL && STREQ (str, "1");
185 str = getenv ("LIBGUESTFS_TRACE");
186 g->trace = str != NULL && STREQ (str, "1");
188 str = getenv ("LIBGUESTFS_PATH");
189 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
190 if (!g->path) goto error;
192 str = getenv ("LIBGUESTFS_QEMU");
193 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
194 if (!g->qemu) goto error;
196 str = getenv ("LIBGUESTFS_APPEND");
198 g->append = strdup (str);
199 if (!g->append) goto error;
202 /* Choose a suitable memory size. Previously we tried to choose
203 * a minimal memory size, but this isn't really necessary since
204 * recent QEMU and KVM don't do anything nasty like locking
205 * memory into core any more. Thus we can safely choose a
206 * large, generous amount of memory, and it'll just get swapped
207 * on smaller systems.
209 str = getenv ("LIBGUESTFS_MEMSIZE");
211 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
212 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
218 /* Start with large serial numbers so they are easy to spot
219 * inside the protocol.
221 g->msg_next_serial = 0x00123400;
223 /* Link the handles onto a global list. */
224 gl_lock_lock (handles_lock);
227 if (!atexit_handler_set) {
228 atexit (close_handles);
229 atexit_handler_set = 1;
231 gl_lock_unlock (handles_lock);
234 fprintf (stderr, "new guestfs handle %p\n", g);
247 guestfs_close (guestfs_h *g)
253 if (g->state == NO_HANDLE) {
254 /* Not safe to call 'error' here, so ... */
255 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
260 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
262 /* Try to sync if autosync flag is set. */
263 if (g->autosync && g->state == READY) {
264 guestfs_umount_all (g);
268 /* Remove any handlers that might be called back before we kill the
271 g->log_message_cb = NULL;
273 if (g->state != CONFIG)
274 guestfs_kill_subprocess (g);
287 /* Wait for subprocess(es) to exit. */
288 waitpid (g->pid, NULL, 0);
289 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
291 /* Remove tmpfiles. */
293 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
296 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
299 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
308 for (i = 0; i < g->cmdline_size; ++i)
309 free (g->cmdline[i]);
313 /* Mark the handle as dead before freeing it. */
314 g->state = NO_HANDLE;
316 gl_lock_lock (handles_lock);
320 for (gg = handles; gg->next != g; gg = gg->next)
324 gl_lock_unlock (handles_lock);
326 free (g->last_error);
331 free (g->qemu_version);
335 /* Close all open handles (called from atexit(3)). */
339 while (handles) guestfs_close (handles);
343 guestfs_last_error (guestfs_h *g)
345 return g->last_error;
349 set_last_error (guestfs_h *g, const char *msg)
351 free (g->last_error);
352 g->last_error = strdup (msg);
356 default_error_cb (guestfs_h *g, void *data, const char *msg)
358 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
362 guestfs_error (guestfs_h *g, const char *fs, ...)
368 int err = vasprintf (&msg, fs, args);
373 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
374 set_last_error (g, msg);
380 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
387 int err = vasprintf (&msg, fs, args);
394 strerror_r (errnum, buf, sizeof buf);
398 buf = strerror_r (errnum, _buf, sizeof _buf);
401 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
405 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
406 set_last_error (g, msg);
412 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
414 void *ptr = malloc (nbytes);
415 if (nbytes > 0 && !ptr) g->abort_cb ();
419 /* Return 1 if an array of N objects, each of size S, cannot exist due
420 to size arithmetic overflow. S must be positive and N must be
421 nonnegative. This is a macro, not an inline function, so that it
422 works correctly even when SIZE_MAX < N.
424 By gnulib convention, SIZE_MAX represents overflow in size
425 calculations, so the conservative dividend to use here is
426 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
427 However, malloc (SIZE_MAX) fails on all known hosts where
428 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
429 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
430 branch when S is known to be 1. */
431 # define xalloc_oversized(n, s) \
432 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
434 /* Technically we should add an autoconf test for this, testing for the desired
435 functionality, like what's done in gnulib, but for now, this is fine. */
436 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
438 /* Allocate zeroed memory for N elements of S bytes, with error
439 checking. S must be nonzero. */
441 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
443 /* From gnulib's calloc function in xmalloc.c. */
445 /* Test for overflow, since some calloc implementations don't have
446 proper overflow checks. But omit overflow and size-zero tests if
447 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
448 returns NULL if successful. */
449 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
450 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
456 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
458 void *p = realloc (ptr, nbytes);
459 if (nbytes > 0 && !p) g->abort_cb ();
464 guestfs_safe_strdup (guestfs_h *g, const char *str)
466 char *s = strdup (str);
467 if (!s) g->abort_cb ();
472 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
474 void *p = malloc (size);
475 if (!p) g->abort_cb ();
476 memcpy (p, ptr, size);
481 xwrite (int fd, const void *v_buf, size_t len)
483 const char *buf = v_buf;
487 r = write (fd, buf, len);
499 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
505 guestfs_get_out_of_memory_handler (guestfs_h *g)
511 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
514 g->error_cb_data = data;
517 guestfs_error_handler_cb
518 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
520 if (data_rtn) *data_rtn = g->error_cb_data;
525 guestfs__set_verbose (guestfs_h *g, int v)
532 guestfs__get_verbose (guestfs_h *g)
538 guestfs__set_autosync (guestfs_h *g, int a)
545 guestfs__get_autosync (guestfs_h *g)
551 guestfs__set_path (guestfs_h *g, const char *path)
558 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
563 guestfs__get_path (guestfs_h *g)
569 guestfs__set_qemu (guestfs_h *g, const char *qemu)
574 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
579 guestfs__get_qemu (guestfs_h *g)
585 guestfs__set_append (guestfs_h *g, const char *append)
590 g->append = append ? safe_strdup (g, append) : NULL;
595 guestfs__get_append (guestfs_h *g)
601 guestfs__set_memsize (guestfs_h *g, int memsize)
603 g->memsize = memsize;
608 guestfs__get_memsize (guestfs_h *g)
614 guestfs__set_selinux (guestfs_h *g, int selinux)
616 g->selinux = selinux;
621 guestfs__get_selinux (guestfs_h *g)
627 guestfs__get_pid (guestfs_h *g)
632 error (g, "get_pid: no qemu subprocess");
637 struct guestfs_version *
638 guestfs__version (guestfs_h *g)
640 struct guestfs_version *r;
642 r = safe_malloc (g, sizeof *r);
643 r->major = PACKAGE_VERSION_MAJOR;
644 r->minor = PACKAGE_VERSION_MINOR;
645 r->release = PACKAGE_VERSION_RELEASE;
646 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
651 guestfs__set_trace (guestfs_h *g, int t)
658 guestfs__get_trace (guestfs_h *g)
664 guestfs__set_direct (guestfs_h *g, int d)
671 guestfs__get_direct (guestfs_h *g)
677 guestfs__set_recovery_proc (guestfs_h *g, int f)
679 g->recovery_proc = !!f;
684 guestfs__get_recovery_proc (guestfs_h *g)
686 return g->recovery_proc;
689 /* Add a string to the current command line. */
691 incr_cmdline_size (guestfs_h *g)
693 if (g->cmdline == NULL) {
694 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
696 g->cmdline = safe_malloc (g, sizeof (char *));
697 g->cmdline[0] = NULL;
701 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
705 add_cmdline (guestfs_h *g, const char *str)
707 if (g->state != CONFIG) {
709 _("command line cannot be altered after qemu subprocess launched"));
713 incr_cmdline_size (g);
714 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
719 guestfs__config (guestfs_h *g,
720 const char *qemu_param, const char *qemu_value)
722 if (qemu_param[0] != '-') {
723 error (g, _("guestfs_config: parameter must begin with '-' character"));
727 /* A bit fascist, but the user will probably break the extra
728 * parameters that we add if they try to set any of these.
730 if (STREQ (qemu_param, "-kernel") ||
731 STREQ (qemu_param, "-initrd") ||
732 STREQ (qemu_param, "-nographic") ||
733 STREQ (qemu_param, "-serial") ||
734 STREQ (qemu_param, "-full-screen") ||
735 STREQ (qemu_param, "-std-vga") ||
736 STREQ (qemu_param, "-vnc")) {
737 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
741 if (add_cmdline (g, qemu_param) != 0) return -1;
743 if (qemu_value != NULL) {
744 if (add_cmdline (g, qemu_value) != 0) return -1;
751 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
752 const char *drive_if)
754 size_t len = strlen (filename) + 64;
757 if (strchr (filename, ',') != NULL) {
758 error (g, _("filename cannot contain ',' (comma) character"));
762 /* cache=off improves reliability in the event of a host crash.
764 * However this option causes qemu to try to open the file with
765 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
766 * So we check if we can open the file with or without O_DIRECT,
767 * and use cache=off (or not) accordingly.
769 * This test also checks for the presence of the file, which
770 * is a documented semantic of this interface.
772 int fd = open (filename, O_RDONLY|O_DIRECT);
775 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
777 fd = open (filename, O_RDONLY);
780 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
782 perrorf (g, "%s", filename);
787 return guestfs__config (g, "-drive", buf);
791 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
792 const char *drive_if)
794 size_t len = strlen (filename) + 64;
797 if (strchr (filename, ',') != NULL) {
798 error (g, _("filename cannot contain ',' (comma) character"));
802 if (access (filename, F_OK) == -1) {
803 perrorf (g, "%s", filename);
807 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
809 return guestfs__config (g, "-drive", buf);
813 guestfs__add_drive (guestfs_h *g, const char *filename)
815 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
819 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
821 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
825 guestfs__add_cdrom (guestfs_h *g, const char *filename)
827 if (strchr (filename, ',') != NULL) {
828 error (g, _("filename cannot contain ',' (comma) character"));
832 if (access (filename, F_OK) == -1) {
833 perrorf (g, "%s", filename);
837 return guestfs__config (g, "-cdrom", filename);
840 /* Returns true iff file is contained in dir. */
842 dir_contains_file (const char *dir, const char *file)
844 int dirlen = strlen (dir);
845 int filelen = strlen (file);
846 int len = dirlen+filelen+2;
849 snprintf (path, len, "%s/%s", dir, file);
850 return access (path, F_OK) == 0;
853 /* Returns true iff every listed file is contained in 'dir'. */
855 dir_contains_files (const char *dir, ...)
860 va_start (args, dir);
861 while ((file = va_arg (args, const char *)) != NULL) {
862 if (!dir_contains_file (dir, file)) {
871 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
872 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
873 static int test_qemu (guestfs_h *g);
874 static int qemu_supports (guestfs_h *g, const char *option);
875 static int is_openable (guestfs_h *g, const char *path, int flags);
876 static void print_cmdline (guestfs_h *g);
878 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
879 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
880 static const char *supermin_name =
881 "initramfs." REPO "." host_cpu ".supermin.img";
882 static const char *supermin_hostfiles_name =
883 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
886 guestfs__launch (guestfs_h *g)
889 char dir_template[PATH_MAX];
894 char *path, *pelem, *pend;
895 char *kernel = NULL, *initrd = NULL;
896 int null_vmchannel_sock;
898 struct sockaddr_un addr;
900 /* Start the clock ... */
901 gettimeofday (&g->launch_t, NULL);
909 tmpdir = getenv ("TMPDIR") ? : tmpdir;
910 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
914 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
918 if (g->state != CONFIG) {
919 error (g, _("qemu has already been launched"));
923 /* Make the temporary directory. */
925 g->tmpdir = safe_strdup (g, dir_template);
926 if (mkdtemp (g->tmpdir) == NULL) {
927 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
932 /* First search g->path for the supermin appliance, and try to
933 * synthesize a kernel and initrd from that. If it fails, we
934 * try the path search again looking for a backup ordinary
937 pelem = path = safe_strdup (g, g->path);
939 pend = strchrnul (pelem, ':');
940 pmore = *pend == ':';
944 /* Empty element of "." means cwd. */
945 if (len == 0 || (len == 1 && *pelem == '.')) {
948 "looking for supermin appliance in current directory\n");
949 if (dir_contains_files (".",
950 supermin_name, supermin_hostfiles_name,
951 "kmod.whitelist", NULL)) {
952 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
957 /* Look at <path>/supermin* etc. */
960 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
962 if (dir_contains_files (pelem,
963 supermin_name, supermin_hostfiles_name,
964 "kmod.whitelist", NULL)) {
965 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
976 if (kernel == NULL || initrd == NULL) {
977 /* Search g->path for the kernel and initrd. */
978 pelem = path = safe_strdup (g, g->path);
980 pend = strchrnul (pelem, ':');
981 pmore = *pend == ':';
985 /* Empty element or "." means cwd. */
986 if (len == 0 || (len == 1 && *pelem == '.')) {
989 "looking for appliance in current directory\n");
990 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
991 kernel = safe_strdup (g, kernel_name);
992 initrd = safe_strdup (g, initrd_name);
996 /* Look at <path>/kernel etc. */
999 fprintf (stderr, "looking for appliance in %s\n", pelem);
1001 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1002 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1003 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1004 sprintf (kernel, "%s/%s", pelem, kernel_name);
1005 sprintf (initrd, "%s/%s", pelem, initrd_name);
1016 if (kernel == NULL || initrd == NULL) {
1017 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1018 kernel_name, initrd_name, g->path);
1023 print_timestamped_message (g, "begin testing qemu features");
1025 /* Get qemu help text and version. */
1026 if (test_qemu (g) == -1)
1029 /* Choose which vmchannel implementation to use. */
1030 if (qemu_supports (g, "-net user")) {
1031 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1032 * networking in qemu) but no other vmchannel support. The daemon
1033 * will connect back to a random port number on localhost.
1035 struct sockaddr_in addr;
1036 socklen_t addrlen = sizeof addr;
1038 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1039 if (g->sock == -1) {
1040 perrorf (g, "socket");
1043 addr.sin_family = AF_INET;
1044 addr.sin_port = htons (0);
1045 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1046 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1047 perrorf (g, "bind");
1051 if (listen (g->sock, 256) == -1) {
1052 perrorf (g, "listen");
1056 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1057 perrorf (g, "getsockname");
1061 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1062 perrorf (g, "fcntl");
1066 null_vmchannel_sock = ntohs (addr.sin_port);
1068 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1070 /* Using some vmchannel impl. We need to create a local Unix
1071 * domain socket for qemu to use.
1073 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1075 null_vmchannel_sock = 0;
1079 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1080 perrorf (g, "pipe");
1086 print_timestamped_message (g, "finished testing qemu features");
1090 perrorf (g, "fork");
1100 if (r == 0) { /* Child (qemu). */
1102 const char *vmchannel = NULL;
1104 /* Set up the full command line. Do this in the subprocess so we
1105 * don't need to worry about cleaning up.
1107 g->cmdline[0] = g->qemu;
1109 /* qemu sometimes needs this option to enable hardware
1110 * virtualization, but some versions of 'qemu-kvm' will use KVM
1111 * regardless (even where this option appears in the help text).
1112 * It is rumoured that there are versions of qemu where supplying
1113 * this option when hardware virtualization is not available will
1114 * cause qemu to fail, so we we have to check at least that
1115 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1116 * might be openable by qemu but not by us (think: SELinux) in
1117 * which case the user would not get hardware virtualization,
1118 * although at least shouldn't fail. A giant clusterfuck with the
1119 * qemu command line, again.
1121 if (qemu_supports (g, "-enable-kvm") &&
1122 is_openable (g, "/dev/kvm", O_RDWR))
1123 add_cmdline (g, "-enable-kvm");
1125 /* Newer versions of qemu (from around 2009/12) changed the
1126 * behaviour of monitors so that an implicit '-monitor stdio' is
1127 * assumed if we are in -nographic mode and there is no other
1128 * -monitor option. Only a single stdio device is allowed, so
1129 * this broke the '-serial stdio' option. There is a new flag
1130 * called -nodefaults which gets rid of all this default crud, so
1131 * let's use that to avoid this and any future surprises.
1133 if (qemu_supports (g, "-nodefaults"))
1134 add_cmdline (g, "-nodefaults");
1136 add_cmdline (g, "-nographic");
1137 add_cmdline (g, "-serial");
1138 add_cmdline (g, "stdio");
1140 snprintf (buf, sizeof buf, "%d", g->memsize);
1141 add_cmdline (g, "-m");
1142 add_cmdline (g, buf);
1144 /* Force exit instead of reboot on panic */
1145 add_cmdline (g, "-no-reboot");
1147 /* These options recommended by KVM developers to improve reliability. */
1148 if (qemu_supports (g, "-no-hpet"))
1149 add_cmdline (g, "-no-hpet");
1151 if (qemu_supports (g, "-rtc-td-hack"))
1152 add_cmdline (g, "-rtc-td-hack");
1154 /* If qemu has SLIRP (user mode network) enabled then we can get
1155 * away with "no vmchannel", where we just connect back to a random
1158 if (null_vmchannel_sock) {
1159 add_cmdline (g, "-net");
1160 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1162 snprintf (buf, sizeof buf,
1163 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1164 vmchannel = strdup (buf);
1167 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1169 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1171 * The original suggested format doesn't work, see:
1173 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1175 * However Gerd Hoffman privately suggested to me using -chardev
1176 * instead, which does work.
1178 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1179 snprintf (buf, sizeof buf,
1180 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1182 add_cmdline (g, "-chardev");
1183 add_cmdline (g, buf);
1185 snprintf (buf, sizeof buf,
1186 "user,vlan=0,net=10.0.2.0/8,"
1187 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1188 "-chardev:guestfsvmc");
1190 add_cmdline (g, "-net");
1191 add_cmdline (g, buf);
1193 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1196 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1197 * syntax, or if not then we'll get a quick failure.
1200 snprintf (buf, sizeof buf,
1201 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1203 add_cmdline (g, "-net");
1204 add_cmdline (g, buf);
1205 add_cmdline (g, "-net");
1206 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1208 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1210 add_cmdline (g, "-net");
1211 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1213 #define LINUX_CMDLINE \
1214 "panic=1 " /* force kernel to panic if daemon exits */ \
1215 "console=ttyS0 " /* serial console */ \
1216 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1217 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1218 "acpi=off " /* we don't need ACPI, turn it off */ \
1219 "printk.time=1 " /* display timestamp before kernel messages */ \
1220 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1222 /* Linux kernel command line. */
1223 snprintf (buf, sizeof buf,
1225 "%s " /* (selinux) */
1226 "%s " /* (vmchannel) */
1227 "%s " /* (verbose) */
1228 "%s", /* (append) */
1229 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1230 vmchannel ? vmchannel : "",
1231 g->verbose ? "guestfs_verbose=1" : "",
1232 g->append ? g->append : "");
1234 add_cmdline (g, "-kernel");
1235 add_cmdline (g, (char *) kernel);
1236 add_cmdline (g, "-initrd");
1237 add_cmdline (g, (char *) initrd);
1238 add_cmdline (g, "-append");
1239 add_cmdline (g, buf);
1241 /* Finish off the command line. */
1242 incr_cmdline_size (g);
1243 g->cmdline[g->cmdline_size-1] = NULL;
1249 /* Set up stdin, stdout. */
1255 if (dup (wfd[0]) == -1) {
1257 perror ("dup failed");
1260 if (dup (rfd[1]) == -1)
1268 /* Set up a new process group, so we can signal this process
1269 * and all subprocesses (eg. if qemu is really a shell script).
1274 setenv ("LC_ALL", "C", 1);
1276 execv (g->qemu, g->cmdline); /* Run qemu. */
1281 /* Parent (library). */
1289 /* Fork the recovery process off which will kill qemu if the parent
1290 * process fails to do so (eg. if the parent segfaults).
1292 g->recoverypid = -1;
1293 if (g->recovery_proc) {
1296 pid_t qemu_pid = g->pid;
1297 pid_t parent_pid = getppid ();
1299 /* Writing to argv is hideously complicated and error prone. See:
1300 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1303 /* Loop around waiting for one or both of the other processes to
1304 * disappear. It's fair to say this is very hairy. The PIDs that
1305 * we are looking at might be reused by another process. We are
1306 * effectively polling. Is the cure worse than the disease?
1309 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1311 if (kill (parent_pid, 0) == -1) {
1312 /* Parent's gone away, qemu still around, so kill qemu. */
1320 /* Don't worry, if the fork failed, this will be -1. The recovery
1321 * process isn't essential.
1327 /* Close the other ends of the pipe. */
1331 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1332 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1333 perrorf (g, "fcntl");
1337 g->fd[0] = wfd[1]; /* stdin of child */
1338 g->fd[1] = rfd[0]; /* stdout of child */
1340 g->fd[0] = open ("/dev/null", O_RDWR);
1341 if (g->fd[0] == -1) {
1342 perrorf (g, "open /dev/null");
1345 g->fd[1] = dup (g->fd[0]);
1346 if (g->fd[1] == -1) {
1353 if (null_vmchannel_sock) {
1357 /* Null vmchannel implementation: We listen on g->sock for a
1358 * connection. The connection could come from any local process
1359 * so we must check it comes from the appliance (or at least
1360 * from our UID) for security reasons.
1362 while (sock == -1) {
1363 sock = accept_from_daemon (g);
1367 if (check_peer_euid (g, sock, &uid) == -1)
1369 if (uid != geteuid ()) {
1371 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1372 uid, null_vmchannel_sock);
1378 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1379 perrorf (g, "fcntl");
1386 /* Other vmchannel. Open the Unix socket.
1388 * The vmchannel implementation that got merged with qemu sucks in
1389 * a number of ways. Both ends do connect(2), which means that no
1390 * one knows what, if anything, is connected to the other end, or
1391 * if it becomes disconnected. Even worse, we have to wait some
1392 * indeterminate time for qemu to create the socket and connect to
1393 * it (which happens very early in qemu's start-up), so any code
1394 * that uses vmchannel is inherently racy. Hence this silly loop.
1396 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1397 if (g->sock == -1) {
1398 perrorf (g, "socket");
1402 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1403 perrorf (g, "fcntl");
1407 addr.sun_family = AF_UNIX;
1408 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1409 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1412 /* Always sleep at least once to give qemu a small chance to start up. */
1415 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1416 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1419 if (errno != ENOENT)
1420 perrorf (g, "connect");
1425 error (g, _("failed to connect to vmchannel socket"));
1431 g->state = LAUNCHING;
1433 /* Wait for qemu to start and to connect back to us via vmchannel and
1434 * send the GUESTFS_LAUNCH_FLAG message.
1438 r = recv_from_daemon (g, &size, &buf);
1441 if (r == -1) return -1;
1443 if (size != GUESTFS_LAUNCH_FLAG) {
1444 error (g, _("guestfs_launch failed, see earlier error messages"));
1449 print_timestamped_message (g, "appliance is up");
1451 /* This is possible in some really strange situations, such as
1452 * guestfsd starts up OK but then qemu immediately exits. Check for
1453 * it because the caller is probably expecting to be able to send
1454 * commands after this function returns.
1456 if (g->state != READY) {
1457 error (g, _("qemu launched and contacted daemon, but state != READY"));
1469 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1470 waitpid (g->pid, NULL, 0);
1471 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1476 memset (&g->launch_t, 0, sizeof g->launch_t);
1489 /* This function is used to print the qemu command line before it gets
1490 * executed, when in verbose mode.
1493 print_cmdline (guestfs_h *g)
1498 while (g->cmdline[i]) {
1499 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1500 fprintf (stderr, " \\\n ");
1502 if (i > 0) fputc (' ', stderr);
1504 /* Does it need shell quoting? This only deals with simple cases. */
1505 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1507 if (needs_quote) fputc ('\'', stderr);
1508 fprintf (stderr, "%s", g->cmdline[i]);
1509 if (needs_quote) fputc ('\'', stderr);
1513 fputc ('\n', stderr);
1516 /* This function does the hard work of building the supermin appliance
1517 * on the fly. 'path' is the directory containing the control files.
1518 * 'kernel' and 'initrd' are where we will return the names of the
1519 * kernel and initrd (only initrd is built). The work is done by
1520 * an external script. We just tell it where to put the result.
1523 build_supermin_appliance (guestfs_h *g, const char *path,
1524 char **kernel, char **initrd)
1530 print_timestamped_message (g, "begin building supermin appliance");
1532 len = strlen (g->tmpdir);
1533 *kernel = safe_malloc (g, len + 8);
1534 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1535 *initrd = safe_malloc (g, len + 8);
1536 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1538 snprintf (cmd, sizeof cmd,
1540 "libguestfs-supermin-helper%s '%s' " host_cpu " " REPO " %s %s",
1542 g->verbose ? " --verbose" : "",
1543 path, *kernel, *initrd);
1545 print_timestamped_message (g, "%s", cmd);
1548 if (r == -1 || WEXITSTATUS(r) != 0) {
1549 error (g, _("external command failed: %s"), cmd);
1552 *kernel = *initrd = NULL;
1557 print_timestamped_message (g, "finished building supermin appliance");
1562 /* Compute Y - X and return the result in milliseconds.
1563 * Approximately the same as this code:
1564 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1567 timeval_diff (const struct timeval *x, const struct timeval *y)
1571 msec = (y->tv_sec - x->tv_sec) * 1000;
1572 msec += (y->tv_usec - x->tv_usec) / 1000;
1577 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1584 va_start (args, fs);
1585 err = vasprintf (&msg, fs, args);
1588 if (err < 0) return;
1590 gettimeofday (&tv, NULL);
1592 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1593 timeval_diff (&g->launch_t, &tv), msg);
1598 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1600 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1601 * 'qemu -version' so we know what options this qemu supports and
1605 test_qemu (guestfs_h *g)
1610 free (g->qemu_help);
1611 free (g->qemu_version);
1612 g->qemu_help = NULL;
1613 g->qemu_version = NULL;
1615 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -help", g->qemu);
1617 fp = popen (cmd, "r");
1618 /* qemu -help should always work (qemu -version OTOH wasn't
1619 * supported by qemu 0.9). If this command doesn't work then it
1620 * probably indicates that the qemu binary is missing.
1623 /* XXX This error is never printed, even if the qemu binary
1624 * doesn't exist. Why?
1627 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1631 if (read_all (g, fp, &g->qemu_help) == -1)
1634 if (pclose (fp) == -1)
1637 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -version 2>/dev/null", g->qemu);
1639 fp = popen (cmd, "r");
1641 /* Intentionally ignore errors. */
1642 read_all (g, fp, &g->qemu_version);
1650 read_all (guestfs_h *g, FILE *fp, char **ret)
1657 *ret = safe_realloc (g, *ret, n + 1);
1662 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1664 r = fread (p, 1, BUFSIZ, fp);
1666 perrorf (g, "read");
1673 /* Test if option is supported by qemu command line (just by grepping
1677 qemu_supports (guestfs_h *g, const char *option)
1679 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1682 /* Check if a file can be opened. */
1684 is_openable (guestfs_h *g, const char *path, int flags)
1686 int fd = open (path, flags);
1696 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1697 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1698 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1701 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1703 struct sockaddr_in peer;
1704 socklen_t addrlen = sizeof peer;
1706 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1707 perrorf (g, "getpeername");
1711 if (peer.sin_family != AF_INET ||
1712 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1713 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1714 peer.sin_family, inet_ntoa (peer.sin_addr));
1718 struct sockaddr_in our;
1719 addrlen = sizeof our;
1720 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1721 perrorf (g, "getsockname");
1725 FILE *fp = fopen ("/proc/net/tcp", "r");
1727 perrorf (g, "/proc/net/tcp");
1732 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1733 error (g, "unexpected end of file in /proc/net/tcp");
1738 while (fgets (line, sizeof line, fp) != NULL) {
1739 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1740 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1743 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1745 &line_our_addr, &line_our_port,
1746 &line_peer_addr, &line_peer_port,
1747 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1749 /* Note about /proc/net/tcp: local_address and rem_address are
1750 * always in network byte order. However the port part is
1751 * always in host byte order.
1753 * The sockname and peername that we got above are in network
1754 * byte order. So we have to byte swap the port but not the
1757 if (line_our_addr == our.sin_addr.s_addr &&
1758 line_our_port == ntohs (our.sin_port) &&
1759 line_peer_addr == peer.sin_addr.s_addr &&
1760 line_peer_port == ntohs (peer.sin_port)) {
1768 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1773 /* You had to call this function after launch in versions <= 1.0.70,
1774 * but it is now a no-op.
1777 guestfs__wait_ready (guestfs_h *g)
1779 if (g->state != READY) {
1780 error (g, _("qemu has not been launched yet"));
1788 guestfs__kill_subprocess (guestfs_h *g)
1790 if (g->state == CONFIG) {
1791 error (g, _("no subprocess to kill"));
1796 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1798 kill (g->pid, SIGTERM);
1799 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1804 /* Access current state. */
1806 guestfs__is_config (guestfs_h *g)
1808 return g->state == CONFIG;
1812 guestfs__is_launching (guestfs_h *g)
1814 return g->state == LAUNCHING;
1818 guestfs__is_ready (guestfs_h *g)
1820 return g->state == READY;
1824 guestfs__is_busy (guestfs_h *g)
1826 return g->state == BUSY;
1830 guestfs__get_state (guestfs_h *g)
1836 guestfs_set_log_message_callback (guestfs_h *g,
1837 guestfs_log_message_cb cb, void *opaque)
1839 g->log_message_cb = cb;
1840 g->log_message_cb_data = opaque;
1844 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1845 guestfs_subprocess_quit_cb cb, void *opaque)
1847 g->subprocess_quit_cb = cb;
1848 g->subprocess_quit_cb_data = opaque;
1852 guestfs_set_launch_done_callback (guestfs_h *g,
1853 guestfs_launch_done_cb cb, void *opaque)
1855 g->launch_done_cb = cb;
1856 g->launch_done_cb_data = opaque;
1859 /*----------------------------------------------------------------------*/
1861 /* This is the code used to send and receive RPC messages and (for
1862 * certain types of message) to perform file transfers. This code is
1863 * driven from the generated actions (src/guestfs-actions.c). There
1864 * are five different cases to consider:
1866 * (1) A non-daemon function. There is no RPC involved at all, it's
1867 * all handled inside the library.
1869 * (2) A simple RPC (eg. "mount"). We write the request, then read
1870 * the reply. The sequence of calls is:
1872 * guestfs___set_busy
1875 * guestfs___end_busy
1877 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1878 * request, then write the file(s), then read the reply. The sequence
1881 * guestfs___set_busy
1883 * guestfs___send_file (possibly multiple times)
1885 * guestfs___end_busy
1887 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1888 * request, then read the reply, then read the file(s). The sequence
1891 * guestfs___set_busy
1894 * guestfs___recv_file (possibly multiple times)
1895 * guestfs___end_busy
1897 * (5) Both FileOut and FileIn parameters. There are no calls like
1898 * this in the current API, but they would be implemented as a
1899 * combination of cases (3) and (4).
1901 * During all writes and reads, we also select(2) on qemu stdout
1902 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1903 * anything received is passed up through the log_message_cb. This is
1904 * also the reason why all the sockets are non-blocking. We also have
1905 * to check for EOF (qemu died). All of this is handled by the
1906 * functions send_to_daemon and recv_from_daemon.
1910 guestfs___set_busy (guestfs_h *g)
1912 if (g->state != READY) {
1913 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1922 guestfs___end_busy (guestfs_h *g)
1936 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1942 /* This is called if we detect EOF, ie. qemu died. */
1944 child_cleanup (guestfs_h *g)
1947 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1949 /*kill (g->pid, SIGTERM);*/
1950 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1951 waitpid (g->pid, NULL, 0);
1952 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1961 memset (&g->launch_t, 0, sizeof g->launch_t);
1963 if (g->subprocess_quit_cb)
1964 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1968 read_log_message_or_eof (guestfs_h *g, int fd)
1976 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1980 /* QEMU's console emulates a 16550A serial port. The real 16550A
1981 * device has a small FIFO buffer (16 bytes) which means here we see
1982 * lots of small reads of 1-16 bytes in length, usually single
1985 n = read (fd, buf, sizeof buf);
1987 /* Hopefully this indicates the qemu child process has died. */
1993 if (errno == EINTR || errno == EAGAIN)
1996 perrorf (g, "read");
2000 /* In verbose mode, copy all log messages to stderr. */
2002 ignore_value (write (STDERR_FILENO, buf, n));
2004 /* It's an actual log message, send it upwards if anyone is listening. */
2005 if (g->log_message_cb)
2006 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2012 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2021 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2024 n = read (fd, buf, 4);
2026 /* Hopefully this indicates the qemu child process has died. */
2032 if (errno == EINTR || errno == EAGAIN)
2035 perrorf (g, "read");
2039 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2040 xdr_uint32_t (&xdr, &flag);
2043 if (flag != GUESTFS_CANCEL_FLAG) {
2044 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2045 flag, GUESTFS_CANCEL_FLAG);
2052 /* This writes the whole N bytes of BUF to the daemon socket.
2054 * If the whole write is successful, it returns 0.
2055 * If there was an error, it returns -1.
2056 * If the daemon sent a cancellation message, it returns -2.
2058 * It also checks qemu stdout for log messages and passes those up
2059 * through log_message_cb.
2061 * It also checks for EOF (qemu died) and passes that up through the
2062 * child_cleanup function above.
2065 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2067 const char *buf = v_buf;
2073 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2078 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2079 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2080 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2082 int max_fd = MAX (g->sock, g->fd[1]);
2087 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2089 if (errno == EINTR || errno == EAGAIN)
2091 perrorf (g, "select");
2095 if (FD_ISSET (g->fd[1], &rset2)) {
2096 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2099 if (FD_ISSET (g->sock, &rset2)) {
2100 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2104 if (FD_ISSET (g->sock, &wset2)) {
2105 r = write (g->sock, buf, n);
2107 if (errno == EINTR || errno == EAGAIN)
2109 perrorf (g, "write");
2110 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2122 /* This reads a single message, file chunk, launch flag or
2123 * cancellation flag from the daemon. If something was read, it
2124 * returns 0, otherwise -1.
2126 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2128 * *size_rtn returns the size of the returned message or it may be
2129 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2131 * *buf_rtn is returned containing the message (if any) or will be set
2132 * to NULL. *buf_rtn must be freed by the caller.
2134 * It also checks qemu stdout for log messages and passes those up
2135 * through log_message_cb.
2137 * It also checks for EOF (qemu died) and passes that up through the
2138 * child_cleanup function above.
2141 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2147 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2148 g, g->state, size_rtn, buf_rtn);
2152 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2153 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2155 int max_fd = MAX (g->sock, g->fd[1]);
2161 /* nr is the size of the message, but we prime it as -4 because we
2162 * have to read the message length word first.
2166 while (nr < (ssize_t) *size_rtn) {
2168 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2170 if (errno == EINTR || errno == EAGAIN)
2172 perrorf (g, "select");
2178 if (FD_ISSET (g->fd[1], &rset2)) {
2179 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2185 if (FD_ISSET (g->sock, &rset2)) {
2186 if (nr < 0) { /* Have we read the message length word yet? */
2187 r = read (g->sock, lenbuf+nr+4, -nr);
2189 if (errno == EINTR || errno == EAGAIN)
2192 perrorf (g, "read");
2193 /* Under some circumstances we see "Connection reset by peer"
2194 * here when the child dies suddenly. Catch this and call
2195 * the cleanup function, same as for EOF.
2197 if (err == ECONNRESET)
2202 error (g, _("unexpected end of file when reading from daemon"));
2208 if (nr < 0) /* Still not got the whole length word. */
2212 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2213 xdr_uint32_t (&xdr, size_rtn);
2216 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2217 if (g->state != LAUNCHING)
2218 error (g, _("received magic signature from guestfsd, but in state %d"),
2222 if (g->launch_done_cb)
2223 g->launch_done_cb (g, g->launch_done_cb_data);
2227 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2229 /* If this happens, it's pretty bad and we've probably lost
2232 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2233 error (g, _("message length (%u) > maximum possible size (%d)"),
2234 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2238 /* Allocate the complete buffer, size now known. */
2239 *buf_rtn = safe_malloc (g, *size_rtn);
2243 size_t sizetoread = *size_rtn - nr;
2244 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2246 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2248 if (errno == EINTR || errno == EAGAIN)
2250 perrorf (g, "read");
2256 error (g, _("unexpected end of file when reading from daemon"));
2266 /* Got the full message, caller can start processing it. */
2267 #ifdef ENABLE_PACKET_DUMP
2271 for (i = 0; i < nr; i += 16) {
2272 printf ("%04zx: ", i);
2273 for (j = i; j < MIN (i+16, nr); ++j)
2274 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2275 for (; j < i+16; ++j)
2278 for (j = i; j < MIN (i+16, nr); ++j)
2279 if (c_isprint ((*(char **)buf_rtn)[j]))
2280 printf ("%c", (*(char **)buf_rtn)[j]);
2283 for (; j < i+16; ++j)
2293 /* This is very much like recv_from_daemon above, but g->sock is
2294 * a listening socket and we are accepting a new connection on
2295 * that socket instead of reading anything. Returns the newly
2299 accept_from_daemon (guestfs_h *g)
2305 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2309 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2310 FD_SET (g->sock, &rset); /* Read socket for accept. */
2312 int max_fd = MAX (g->sock, g->fd[1]);
2315 while (sock == -1) {
2317 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2319 if (errno == EINTR || errno == EAGAIN)
2321 perrorf (g, "select");
2325 if (FD_ISSET (g->fd[1], &rset2)) {
2326 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2329 if (FD_ISSET (g->sock, &rset2)) {
2330 sock = accept (g->sock, NULL, NULL);
2332 if (errno == EINTR || errno == EAGAIN)
2334 perrorf (g, "accept");
2344 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2346 struct guestfs_message_header hdr;
2349 int serial = g->msg_next_serial++;
2352 size_t msg_out_size;
2354 if (g->state != BUSY) {
2355 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2359 /* We have to allocate this message buffer on the heap because
2360 * it is quite large (although will be mostly unused). We
2361 * can't allocate it on the stack because in some environments
2362 * we have quite limited stack space available, notably when
2363 * running in the JVM.
2365 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2366 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2368 /* Serialize the header. */
2369 hdr.prog = GUESTFS_PROGRAM;
2370 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2372 hdr.direction = GUESTFS_DIRECTION_CALL;
2373 hdr.serial = serial;
2374 hdr.status = GUESTFS_STATUS_OK;
2376 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2377 error (g, _("xdr_guestfs_message_header failed"));
2381 /* Serialize the args. If any, because some message types
2382 * have no parameters.
2385 if (!(*xdrp) (&xdr, args)) {
2386 error (g, _("dispatch failed to marshal args"));
2391 /* Get the actual length of the message, resize the buffer to match
2392 * the actual length, and write the length word at the beginning.
2394 len = xdr_getpos (&xdr);
2397 msg_out = safe_realloc (g, msg_out, len + 4);
2398 msg_out_size = len + 4;
2400 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2401 xdr_uint32_t (&xdr, &len);
2404 r = send_to_daemon (g, msg_out, msg_out_size);
2405 if (r == -2) /* Ignore stray daemon cancellations. */
2418 static int cancel = 0; /* XXX Implement file cancellation. */
2419 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2420 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2421 static int send_file_cancellation (guestfs_h *g);
2422 static int send_file_complete (guestfs_h *g);
2428 * -2 daemon cancelled (we must read the error message)
2431 guestfs___send_file (guestfs_h *g, const char *filename)
2433 char buf[GUESTFS_MAX_CHUNK_SIZE];
2436 fd = open (filename, O_RDONLY);
2438 perrorf (g, "open: %s", filename);
2439 send_file_cancellation (g);
2440 /* Daemon sees cancellation and won't reply, so caller can
2446 /* Send file in chunked encoding. */
2448 r = read (fd, buf, sizeof buf);
2449 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2452 err = send_file_data (g, buf, r);
2454 if (err == -2) /* daemon sent cancellation */
2455 send_file_cancellation (g);
2460 if (cancel) { /* cancel from either end */
2461 send_file_cancellation (g);
2466 perrorf (g, "read: %s", filename);
2467 send_file_cancellation (g);
2471 /* End of file, but before we send that, we need to close
2472 * the file and check for errors.
2474 if (close (fd) == -1) {
2475 perrorf (g, "close: %s", filename);
2476 send_file_cancellation (g);
2480 return send_file_complete (g);
2483 /* Send a chunk of file data. */
2485 send_file_data (guestfs_h *g, const char *buf, size_t len)
2487 return send_file_chunk (g, 0, buf, len);
2490 /* Send a cancellation message. */
2492 send_file_cancellation (guestfs_h *g)
2494 return send_file_chunk (g, 1, NULL, 0);
2497 /* Send a file complete chunk. */
2499 send_file_complete (guestfs_h *g)
2502 return send_file_chunk (g, 0, buf, 0);
2506 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2510 guestfs_chunk chunk;
2513 size_t msg_out_size;
2515 if (g->state != BUSY) {
2516 error (g, _("send_file_chunk: state %d != READY"), g->state);
2520 /* Allocate the chunk buffer. Don't use the stack to avoid
2521 * excessive stack usage and unnecessary copies.
2523 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2524 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2526 /* Serialize the chunk. */
2527 chunk.cancel = cancel;
2528 chunk.data.data_len = buflen;
2529 chunk.data.data_val = (char *) buf;
2531 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2532 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2538 len = xdr_getpos (&xdr);
2541 /* Reduce the size of the outgoing message buffer to the real length. */
2542 msg_out = safe_realloc (g, msg_out, len + 4);
2543 msg_out_size = len + 4;
2545 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2546 xdr_uint32_t (&xdr, &len);
2548 r = send_to_daemon (g, msg_out, msg_out_size);
2550 /* Did the daemon send a cancellation message? */
2553 fprintf (stderr, "got daemon cancellation\n");
2569 /* Receive a reply. */
2571 guestfs___recv (guestfs_h *g, const char *fn,
2572 guestfs_message_header *hdr,
2573 guestfs_message_error *err,
2574 xdrproc_t xdrp, char *ret)
2582 r = recv_from_daemon (g, &size, &buf);
2586 /* This can happen if a cancellation happens right at the end
2587 * of us sending a FileIn parameter to the daemon. Discard. The
2588 * daemon should send us an error message next.
2590 if (size == GUESTFS_CANCEL_FLAG)
2593 if (size == GUESTFS_LAUNCH_FLAG) {
2594 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2598 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2600 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2601 error (g, "%s: failed to parse reply header", fn);
2606 if (hdr->status == GUESTFS_STATUS_ERROR) {
2607 if (!xdr_guestfs_message_error (&xdr, err)) {
2608 error (g, "%s: failed to parse reply error", fn);
2614 if (xdrp && ret && !xdrp (&xdr, ret)) {
2615 error (g, "%s: failed to parse reply", fn);
2627 /* Receive a file. */
2629 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2630 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2633 guestfs___recv_file (guestfs_h *g, const char *filename)
2638 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2640 perrorf (g, "open: %s", filename);
2644 /* Receive the file in chunked encoding. */
2645 while ((r = receive_file_data (g, &buf)) > 0) {
2646 if (xwrite (fd, buf, r) == -1) {
2647 perrorf (g, "%s: write", filename);
2655 error (g, _("%s: error in chunked encoding"), filename);
2659 if (close (fd) == -1) {
2660 perrorf (g, "close: %s", filename);
2667 /* Send cancellation message to daemon, then wait until it
2668 * cancels (just throwing away data).
2672 uint32_t flag = GUESTFS_CANCEL_FLAG;
2675 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2678 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2679 xdr_uint32_t (&xdr, &flag);
2682 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2683 perrorf (g, _("write to daemon socket"));
2687 while (receive_file_data (g, NULL) > 0)
2688 ; /* just discard it */
2693 /* Receive a chunk of file data. */
2694 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2696 receive_file_data (guestfs_h *g, void **buf_r)
2702 guestfs_chunk chunk;
2704 r = recv_from_daemon (g, &len, &buf);
2706 error (g, _("receive_file_data: parse error in reply callback"));
2710 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2711 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2715 memset (&chunk, 0, sizeof chunk);
2717 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2718 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2719 error (g, _("failed to parse file chunk"));
2724 /* After decoding, the original buffer is no longer used. */
2728 error (g, _("file receive cancelled by daemon"));
2729 free (chunk.data.data_val);
2733 if (chunk.data.data_len == 0) { /* end of transfer */
2734 free (chunk.data.data_val);
2738 if (buf_r) *buf_r = chunk.data.data_val;
2739 else free (chunk.data.data_val); /* else caller frees */
2741 return chunk.data.data_len;