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>
38 #include <rpc/types.h>
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
49 #ifdef HAVE_SYS_WAIT_H
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
65 #include "glthread/lock.h"
66 #include "ignore-value.h"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
75 #define _(str) dgettext(PACKAGE, (str))
76 //#define N_(str) dgettext(PACKAGE, (str))
82 #define error guestfs_error
83 #define perrorf guestfs_perrorf
84 #define safe_malloc guestfs_safe_malloc
85 #define safe_realloc guestfs_safe_realloc
86 #define safe_strdup guestfs_safe_strdup
87 //#define safe_memdup guestfs_safe_memdup
89 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
90 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
91 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
92 static int accept_from_daemon (guestfs_h *g);
93 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
94 static void close_handles (void);
95 static int qemu_supports (guestfs_h *g, const char *option);
97 #define UNIX_PATH_MAX 108
99 /* Also in guestfsd.c */
100 #define GUESTFWD_ADDR "10.0.2.4"
101 #define GUESTFWD_PORT "6666"
103 /* GuestFS handle and connection. */
104 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
108 struct guestfs_h *next; /* Linked list of open handles. */
110 /* State: see the state machine diagram in the man page guestfs(3). */
113 int fd[2]; /* Stdin/stdout of qemu. */
114 int sock; /* Daemon communications socket. */
115 pid_t pid; /* Qemu PID. */
116 pid_t recoverypid; /* Recovery process PID. */
118 struct timeval launch_t; /* The time that we called guestfs_launch. */
120 char *tmpdir; /* Temporary directory containing socket. */
122 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
124 char **cmdline; /* Qemu command line. */
133 char *path; /* Path to kernel, initrd. */
134 char *qemu; /* Qemu binary. */
135 char *append; /* Append to kernel command line. */
137 int memsize; /* Size of RAM (megabytes). */
139 int selinux; /* selinux enabled? */
144 guestfs_abort_cb abort_cb;
145 guestfs_error_handler_cb error_cb;
146 void * error_cb_data;
147 guestfs_log_message_cb log_message_cb;
148 void * log_message_cb_data;
149 guestfs_subprocess_quit_cb subprocess_quit_cb;
150 void * subprocess_quit_cb_data;
151 guestfs_launch_done_cb launch_done_cb;
152 void * launch_done_cb_data;
157 gl_lock_define_initialized (static, handles_lock);
158 static guestfs_h *handles = NULL;
159 static int atexit_handler_set = 0;
162 guestfs_create (void)
167 g = malloc (sizeof (*g));
170 memset (g, 0, sizeof (*g));
179 g->error_cb = default_error_cb;
180 g->error_cb_data = NULL;
182 g->recovery_proc = 1;
184 str = getenv ("LIBGUESTFS_DEBUG");
185 g->verbose = str != NULL && STREQ (str, "1");
187 str = getenv ("LIBGUESTFS_TRACE");
188 g->trace = str != NULL && STREQ (str, "1");
190 str = getenv ("LIBGUESTFS_PATH");
191 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
192 if (!g->path) goto error;
194 str = getenv ("LIBGUESTFS_QEMU");
195 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
196 if (!g->qemu) goto error;
198 str = getenv ("LIBGUESTFS_APPEND");
200 g->append = strdup (str);
201 if (!g->append) goto error;
204 /* Choose a suitable memory size. Previously we tried to choose
205 * a minimal memory size, but this isn't really necessary since
206 * recent QEMU and KVM don't do anything nasty like locking
207 * memory into core any more. Thus we can safely choose a
208 * large, generous amount of memory, and it'll just get swapped
209 * on smaller systems.
211 str = getenv ("LIBGUESTFS_MEMSIZE");
213 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
214 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
220 /* Start with large serial numbers so they are easy to spot
221 * inside the protocol.
223 g->msg_next_serial = 0x00123400;
225 /* Link the handles onto a global list. */
226 gl_lock_lock (handles_lock);
229 if (!atexit_handler_set) {
230 atexit (close_handles);
231 atexit_handler_set = 1;
233 gl_lock_unlock (handles_lock);
236 fprintf (stderr, "new guestfs handle %p\n", g);
249 guestfs_close (guestfs_h *g)
255 if (g->state == NO_HANDLE) {
256 /* Not safe to call 'error' here, so ... */
257 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
262 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
264 /* Try to sync if autosync flag is set. */
265 if (g->autosync && g->state == READY) {
266 guestfs_umount_all (g);
270 /* Remove any handlers that might be called back before we kill the
273 g->log_message_cb = NULL;
275 if (g->state != CONFIG)
276 guestfs_kill_subprocess (g);
289 /* Wait for subprocess(es) to exit. */
290 waitpid (g->pid, NULL, 0);
291 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
293 /* Remove tmpfiles. */
295 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
298 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
301 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
310 for (i = 0; i < g->cmdline_size; ++i)
311 free (g->cmdline[i]);
315 /* Mark the handle as dead before freeing it. */
316 g->state = NO_HANDLE;
318 gl_lock_lock (handles_lock);
322 for (gg = handles; gg->next != g; gg = gg->next)
326 gl_lock_unlock (handles_lock);
328 free (g->last_error);
333 free (g->qemu_version);
337 /* Close all open handles (called from atexit(3)). */
341 while (handles) guestfs_close (handles);
345 guestfs_last_error (guestfs_h *g)
347 return g->last_error;
351 set_last_error (guestfs_h *g, const char *msg)
353 free (g->last_error);
354 g->last_error = strdup (msg);
358 default_error_cb (guestfs_h *g, void *data, const char *msg)
360 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
364 guestfs_error (guestfs_h *g, const char *fs, ...)
370 int err = vasprintf (&msg, fs, args);
375 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
376 set_last_error (g, msg);
382 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
389 int err = vasprintf (&msg, fs, args);
396 strerror_r (errnum, buf, sizeof buf);
400 buf = strerror_r (errnum, _buf, sizeof _buf);
403 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
407 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
408 set_last_error (g, msg);
414 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
416 void *ptr = malloc (nbytes);
417 if (nbytes > 0 && !ptr) g->abort_cb ();
421 /* Return 1 if an array of N objects, each of size S, cannot exist due
422 to size arithmetic overflow. S must be positive and N must be
423 nonnegative. This is a macro, not an inline function, so that it
424 works correctly even when SIZE_MAX < N.
426 By gnulib convention, SIZE_MAX represents overflow in size
427 calculations, so the conservative dividend to use here is
428 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
429 However, malloc (SIZE_MAX) fails on all known hosts where
430 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
431 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
432 branch when S is known to be 1. */
433 # define xalloc_oversized(n, s) \
434 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
436 /* Technically we should add an autoconf test for this, testing for the desired
437 functionality, like what's done in gnulib, but for now, this is fine. */
438 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
440 /* Allocate zeroed memory for N elements of S bytes, with error
441 checking. S must be nonzero. */
443 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
445 /* From gnulib's calloc function in xmalloc.c. */
447 /* Test for overflow, since some calloc implementations don't have
448 proper overflow checks. But omit overflow and size-zero tests if
449 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
450 returns NULL if successful. */
451 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
452 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
458 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
460 void *p = realloc (ptr, nbytes);
461 if (nbytes > 0 && !p) g->abort_cb ();
466 guestfs_safe_strdup (guestfs_h *g, const char *str)
468 char *s = strdup (str);
469 if (!s) g->abort_cb ();
474 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
476 void *p = malloc (size);
477 if (!p) g->abort_cb ();
478 memcpy (p, ptr, size);
483 xwrite (int fd, const void *v_buf, size_t len)
485 const char *buf = v_buf;
489 r = write (fd, buf, len);
501 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
507 guestfs_get_out_of_memory_handler (guestfs_h *g)
513 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
516 g->error_cb_data = data;
519 guestfs_error_handler_cb
520 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
522 if (data_rtn) *data_rtn = g->error_cb_data;
527 guestfs__set_verbose (guestfs_h *g, int v)
534 guestfs__get_verbose (guestfs_h *g)
540 guestfs__set_autosync (guestfs_h *g, int a)
547 guestfs__get_autosync (guestfs_h *g)
553 guestfs__set_path (guestfs_h *g, const char *path)
560 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
565 guestfs__get_path (guestfs_h *g)
571 guestfs__set_qemu (guestfs_h *g, const char *qemu)
576 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
581 guestfs__get_qemu (guestfs_h *g)
587 guestfs__set_append (guestfs_h *g, const char *append)
592 g->append = append ? safe_strdup (g, append) : NULL;
597 guestfs__get_append (guestfs_h *g)
603 guestfs__set_memsize (guestfs_h *g, int memsize)
605 g->memsize = memsize;
610 guestfs__get_memsize (guestfs_h *g)
616 guestfs__set_selinux (guestfs_h *g, int selinux)
618 g->selinux = selinux;
623 guestfs__get_selinux (guestfs_h *g)
629 guestfs__get_pid (guestfs_h *g)
634 error (g, "get_pid: no qemu subprocess");
639 struct guestfs_version *
640 guestfs__version (guestfs_h *g)
642 struct guestfs_version *r;
644 r = safe_malloc (g, sizeof *r);
645 r->major = PACKAGE_VERSION_MAJOR;
646 r->minor = PACKAGE_VERSION_MINOR;
647 r->release = PACKAGE_VERSION_RELEASE;
648 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
653 guestfs__set_trace (guestfs_h *g, int t)
660 guestfs__get_trace (guestfs_h *g)
666 guestfs__set_direct (guestfs_h *g, int d)
673 guestfs__get_direct (guestfs_h *g)
679 guestfs__set_recovery_proc (guestfs_h *g, int f)
681 g->recovery_proc = !!f;
686 guestfs__get_recovery_proc (guestfs_h *g)
688 return g->recovery_proc;
691 /* Add a string to the current command line. */
693 incr_cmdline_size (guestfs_h *g)
695 if (g->cmdline == NULL) {
696 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
698 g->cmdline = safe_malloc (g, sizeof (char *));
699 g->cmdline[0] = NULL;
703 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
707 add_cmdline (guestfs_h *g, const char *str)
709 if (g->state != CONFIG) {
711 _("command line cannot be altered after qemu subprocess launched"));
715 incr_cmdline_size (g);
716 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
721 guestfs__config (guestfs_h *g,
722 const char *qemu_param, const char *qemu_value)
724 if (qemu_param[0] != '-') {
725 error (g, _("guestfs_config: parameter must begin with '-' character"));
729 /* A bit fascist, but the user will probably break the extra
730 * parameters that we add if they try to set any of these.
732 if (STREQ (qemu_param, "-kernel") ||
733 STREQ (qemu_param, "-initrd") ||
734 STREQ (qemu_param, "-nographic") ||
735 STREQ (qemu_param, "-serial") ||
736 STREQ (qemu_param, "-full-screen") ||
737 STREQ (qemu_param, "-std-vga") ||
738 STREQ (qemu_param, "-vnc")) {
739 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
743 if (add_cmdline (g, qemu_param) != 0) return -1;
745 if (qemu_value != NULL) {
746 if (add_cmdline (g, qemu_value) != 0) return -1;
753 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
754 const char *drive_if)
756 size_t len = strlen (filename) + 64;
759 if (strchr (filename, ',') != NULL) {
760 error (g, _("filename cannot contain ',' (comma) character"));
764 /* cache=off improves reliability in the event of a host crash.
766 * However this option causes qemu to try to open the file with
767 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
768 * So we check if we can open the file with or without O_DIRECT,
769 * and use cache=off (or not) accordingly.
771 * This test also checks for the presence of the file, which
772 * is a documented semantic of this interface.
774 int fd = open (filename, O_RDONLY|O_DIRECT);
777 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
779 fd = open (filename, O_RDONLY);
782 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
784 perrorf (g, "%s", filename);
789 return guestfs__config (g, "-drive", buf);
793 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
794 const char *drive_if)
796 if (strchr (filename, ',') != NULL) {
797 error (g, _("filename cannot contain ',' (comma) character"));
801 if (access (filename, F_OK) == -1) {
802 perrorf (g, "%s", filename);
806 if (qemu_supports (g, NULL) == -1)
809 /* Only SCSI and virtio drivers support readonly mode.
810 * This is only supported as a QEMU feature since 2010/01.
813 if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
814 qemu_supports (g, "readonly=on"))
817 size_t len = strlen (filename) + 100;
820 snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
822 supports_ro ? "readonly=on," : "",
825 return guestfs__config (g, "-drive", buf);
829 guestfs__add_drive (guestfs_h *g, const char *filename)
831 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
835 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
837 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
841 guestfs__add_cdrom (guestfs_h *g, const char *filename)
843 if (strchr (filename, ',') != NULL) {
844 error (g, _("filename cannot contain ',' (comma) character"));
848 if (access (filename, F_OK) == -1) {
849 perrorf (g, "%s", filename);
853 return guestfs__config (g, "-cdrom", filename);
856 /* Returns true iff file is contained in dir. */
858 dir_contains_file (const char *dir, const char *file)
860 int dirlen = strlen (dir);
861 int filelen = strlen (file);
862 int len = dirlen+filelen+2;
865 snprintf (path, len, "%s/%s", dir, file);
866 return access (path, F_OK) == 0;
869 /* Returns true iff every listed file is contained in 'dir'. */
871 dir_contains_files (const char *dir, ...)
876 va_start (args, dir);
877 while ((file = va_arg (args, const char *)) != NULL) {
878 if (!dir_contains_file (dir, file)) {
887 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
888 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
889 static int is_openable (guestfs_h *g, const char *path, int flags);
890 static void print_cmdline (guestfs_h *g);
892 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
893 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
894 static const char *supermin_name =
895 "initramfs." REPO "." host_cpu ".supermin.img";
896 static const char *supermin_hostfiles_name =
897 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
900 guestfs__launch (guestfs_h *g)
903 char dir_template[PATH_MAX];
908 char *path, *pelem, *pend;
909 char *kernel = NULL, *initrd = NULL;
910 int null_vmchannel_sock;
912 struct sockaddr_un addr;
914 /* Start the clock ... */
915 gettimeofday (&g->launch_t, NULL);
923 tmpdir = getenv ("TMPDIR") ? : tmpdir;
924 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
928 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
932 if (g->state != CONFIG) {
933 error (g, _("qemu has already been launched"));
937 /* Make the temporary directory. */
939 g->tmpdir = safe_strdup (g, dir_template);
940 if (mkdtemp (g->tmpdir) == NULL) {
941 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
946 /* First search g->path for the supermin appliance, and try to
947 * synthesize a kernel and initrd from that. If it fails, we
948 * try the path search again looking for a backup ordinary
951 pelem = path = safe_strdup (g, g->path);
953 pend = strchrnul (pelem, ':');
954 pmore = *pend == ':';
958 /* Empty element of "." means cwd. */
959 if (len == 0 || (len == 1 && *pelem == '.')) {
962 "looking for supermin appliance in current directory\n");
963 if (dir_contains_files (".",
964 supermin_name, supermin_hostfiles_name,
965 "kmod.whitelist", NULL)) {
966 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
971 /* Look at <path>/supermin* etc. */
974 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
976 if (dir_contains_files (pelem,
977 supermin_name, supermin_hostfiles_name,
978 "kmod.whitelist", NULL)) {
979 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
990 if (kernel == NULL || initrd == NULL) {
991 /* Search g->path for the kernel and initrd. */
992 pelem = path = safe_strdup (g, g->path);
994 pend = strchrnul (pelem, ':');
995 pmore = *pend == ':';
999 /* Empty element or "." means cwd. */
1000 if (len == 0 || (len == 1 && *pelem == '.')) {
1003 "looking for appliance in current directory\n");
1004 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1005 kernel = safe_strdup (g, kernel_name);
1006 initrd = safe_strdup (g, initrd_name);
1010 /* Look at <path>/kernel etc. */
1013 fprintf (stderr, "looking for appliance in %s\n", pelem);
1015 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1016 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1017 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1018 sprintf (kernel, "%s/%s", pelem, kernel_name);
1019 sprintf (initrd, "%s/%s", pelem, initrd_name);
1030 if (kernel == NULL || initrd == NULL) {
1031 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1032 kernel_name, initrd_name, g->path);
1037 print_timestamped_message (g, "begin testing qemu features");
1039 /* Get qemu help text and version. */
1040 if (qemu_supports (g, NULL) == -1)
1043 /* Choose which vmchannel implementation to use. */
1044 if (qemu_supports (g, "-net user")) {
1045 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1046 * networking in qemu) but no other vmchannel support. The daemon
1047 * will connect back to a random port number on localhost.
1049 struct sockaddr_in addr;
1050 socklen_t addrlen = sizeof addr;
1052 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1053 if (g->sock == -1) {
1054 perrorf (g, "socket");
1057 addr.sin_family = AF_INET;
1058 addr.sin_port = htons (0);
1059 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1060 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1061 perrorf (g, "bind");
1065 if (listen (g->sock, 256) == -1) {
1066 perrorf (g, "listen");
1070 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1071 perrorf (g, "getsockname");
1075 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1076 perrorf (g, "fcntl");
1080 null_vmchannel_sock = ntohs (addr.sin_port);
1082 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1084 /* Using some vmchannel impl. We need to create a local Unix
1085 * domain socket for qemu to use.
1087 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1089 null_vmchannel_sock = 0;
1093 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1094 perrorf (g, "pipe");
1100 print_timestamped_message (g, "finished testing qemu features");
1104 perrorf (g, "fork");
1114 if (r == 0) { /* Child (qemu). */
1116 const char *vmchannel = NULL;
1118 /* Set up the full command line. Do this in the subprocess so we
1119 * don't need to worry about cleaning up.
1121 g->cmdline[0] = g->qemu;
1123 /* qemu sometimes needs this option to enable hardware
1124 * virtualization, but some versions of 'qemu-kvm' will use KVM
1125 * regardless (even where this option appears in the help text).
1126 * It is rumoured that there are versions of qemu where supplying
1127 * this option when hardware virtualization is not available will
1128 * cause qemu to fail, so we we have to check at least that
1129 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1130 * might be openable by qemu but not by us (think: SELinux) in
1131 * which case the user would not get hardware virtualization,
1132 * although at least shouldn't fail. A giant clusterfuck with the
1133 * qemu command line, again.
1135 if (qemu_supports (g, "-enable-kvm") &&
1136 is_openable (g, "/dev/kvm", O_RDWR))
1137 add_cmdline (g, "-enable-kvm");
1139 /* Newer versions of qemu (from around 2009/12) changed the
1140 * behaviour of monitors so that an implicit '-monitor stdio' is
1141 * assumed if we are in -nographic mode and there is no other
1142 * -monitor option. Only a single stdio device is allowed, so
1143 * this broke the '-serial stdio' option. There is a new flag
1144 * called -nodefaults which gets rid of all this default crud, so
1145 * let's use that to avoid this and any future surprises.
1147 if (qemu_supports (g, "-nodefaults"))
1148 add_cmdline (g, "-nodefaults");
1150 add_cmdline (g, "-nographic");
1151 add_cmdline (g, "-serial");
1152 add_cmdline (g, "stdio");
1154 snprintf (buf, sizeof buf, "%d", g->memsize);
1155 add_cmdline (g, "-m");
1156 add_cmdline (g, buf);
1158 /* Force exit instead of reboot on panic */
1159 add_cmdline (g, "-no-reboot");
1161 /* These options recommended by KVM developers to improve reliability. */
1162 if (qemu_supports (g, "-no-hpet"))
1163 add_cmdline (g, "-no-hpet");
1165 if (qemu_supports (g, "-rtc-td-hack"))
1166 add_cmdline (g, "-rtc-td-hack");
1168 /* If qemu has SLIRP (user mode network) enabled then we can get
1169 * away with "no vmchannel", where we just connect back to a random
1172 if (null_vmchannel_sock) {
1173 add_cmdline (g, "-net");
1174 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1176 snprintf (buf, sizeof buf,
1177 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1178 vmchannel = strdup (buf);
1181 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1183 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1185 * The original suggested format doesn't work, see:
1187 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1189 * However Gerd Hoffman privately suggested to me using -chardev
1190 * instead, which does work.
1192 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1193 snprintf (buf, sizeof buf,
1194 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1196 add_cmdline (g, "-chardev");
1197 add_cmdline (g, buf);
1199 snprintf (buf, sizeof buf,
1200 "user,vlan=0,net=10.0.2.0/8,"
1201 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1202 "-chardev:guestfsvmc");
1204 add_cmdline (g, "-net");
1205 add_cmdline (g, buf);
1207 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1210 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1211 * syntax, or if not then we'll get a quick failure.
1214 snprintf (buf, sizeof buf,
1215 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1217 add_cmdline (g, "-net");
1218 add_cmdline (g, buf);
1219 add_cmdline (g, "-net");
1220 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1222 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1224 add_cmdline (g, "-net");
1225 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1227 #define LINUX_CMDLINE \
1228 "panic=1 " /* force kernel to panic if daemon exits */ \
1229 "console=ttyS0 " /* serial console */ \
1230 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1231 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1232 "acpi=off " /* we don't need ACPI, turn it off */ \
1233 "printk.time=1 " /* display timestamp before kernel messages */ \
1234 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1236 /* Linux kernel command line. */
1237 snprintf (buf, sizeof buf,
1239 "%s " /* (selinux) */
1240 "%s " /* (vmchannel) */
1241 "%s " /* (verbose) */
1242 "%s", /* (append) */
1243 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1244 vmchannel ? vmchannel : "",
1245 g->verbose ? "guestfs_verbose=1" : "",
1246 g->append ? g->append : "");
1248 add_cmdline (g, "-kernel");
1249 add_cmdline (g, (char *) kernel);
1250 add_cmdline (g, "-initrd");
1251 add_cmdline (g, (char *) initrd);
1252 add_cmdline (g, "-append");
1253 add_cmdline (g, buf);
1255 /* Finish off the command line. */
1256 incr_cmdline_size (g);
1257 g->cmdline[g->cmdline_size-1] = NULL;
1263 /* Set up stdin, stdout. */
1269 if (dup (wfd[0]) == -1) {
1271 perror ("dup failed");
1274 if (dup (rfd[1]) == -1)
1282 /* Set up a new process group, so we can signal this process
1283 * and all subprocesses (eg. if qemu is really a shell script).
1288 setenv ("LC_ALL", "C", 1);
1290 execv (g->qemu, g->cmdline); /* Run qemu. */
1295 /* Parent (library). */
1303 /* Fork the recovery process off which will kill qemu if the parent
1304 * process fails to do so (eg. if the parent segfaults).
1306 g->recoverypid = -1;
1307 if (g->recovery_proc) {
1310 pid_t qemu_pid = g->pid;
1311 pid_t parent_pid = getppid ();
1313 /* Writing to argv is hideously complicated and error prone. See:
1314 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1317 /* Loop around waiting for one or both of the other processes to
1318 * disappear. It's fair to say this is very hairy. The PIDs that
1319 * we are looking at might be reused by another process. We are
1320 * effectively polling. Is the cure worse than the disease?
1323 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1325 if (kill (parent_pid, 0) == -1) {
1326 /* Parent's gone away, qemu still around, so kill qemu. */
1334 /* Don't worry, if the fork failed, this will be -1. The recovery
1335 * process isn't essential.
1341 /* Close the other ends of the pipe. */
1345 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1346 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1347 perrorf (g, "fcntl");
1351 g->fd[0] = wfd[1]; /* stdin of child */
1352 g->fd[1] = rfd[0]; /* stdout of child */
1354 g->fd[0] = open ("/dev/null", O_RDWR);
1355 if (g->fd[0] == -1) {
1356 perrorf (g, "open /dev/null");
1359 g->fd[1] = dup (g->fd[0]);
1360 if (g->fd[1] == -1) {
1367 if (null_vmchannel_sock) {
1371 /* Null vmchannel implementation: We listen on g->sock for a
1372 * connection. The connection could come from any local process
1373 * so we must check it comes from the appliance (or at least
1374 * from our UID) for security reasons.
1376 while (sock == -1) {
1377 sock = accept_from_daemon (g);
1381 if (check_peer_euid (g, sock, &uid) == -1)
1383 if (uid != geteuid ()) {
1385 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1386 uid, null_vmchannel_sock);
1392 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1393 perrorf (g, "fcntl");
1400 /* Other vmchannel. Open the Unix socket.
1402 * The vmchannel implementation that got merged with qemu sucks in
1403 * a number of ways. Both ends do connect(2), which means that no
1404 * one knows what, if anything, is connected to the other end, or
1405 * if it becomes disconnected. Even worse, we have to wait some
1406 * indeterminate time for qemu to create the socket and connect to
1407 * it (which happens very early in qemu's start-up), so any code
1408 * that uses vmchannel is inherently racy. Hence this silly loop.
1410 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1411 if (g->sock == -1) {
1412 perrorf (g, "socket");
1416 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1417 perrorf (g, "fcntl");
1421 addr.sun_family = AF_UNIX;
1422 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1423 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1426 /* Always sleep at least once to give qemu a small chance to start up. */
1429 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1430 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1433 if (errno != ENOENT)
1434 perrorf (g, "connect");
1439 error (g, _("failed to connect to vmchannel socket"));
1445 g->state = LAUNCHING;
1447 /* Wait for qemu to start and to connect back to us via vmchannel and
1448 * send the GUESTFS_LAUNCH_FLAG message.
1452 r = recv_from_daemon (g, &size, &buf);
1455 if (r == -1) return -1;
1457 if (size != GUESTFS_LAUNCH_FLAG) {
1458 error (g, _("guestfs_launch failed, see earlier error messages"));
1463 print_timestamped_message (g, "appliance is up");
1465 /* This is possible in some really strange situations, such as
1466 * guestfsd starts up OK but then qemu immediately exits. Check for
1467 * it because the caller is probably expecting to be able to send
1468 * commands after this function returns.
1470 if (g->state != READY) {
1471 error (g, _("qemu launched and contacted daemon, but state != READY"));
1483 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1484 waitpid (g->pid, NULL, 0);
1485 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1490 memset (&g->launch_t, 0, sizeof g->launch_t);
1503 /* This function is used to print the qemu command line before it gets
1504 * executed, when in verbose mode.
1507 print_cmdline (guestfs_h *g)
1512 while (g->cmdline[i]) {
1513 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1514 fprintf (stderr, " \\\n ");
1516 if (i > 0) fputc (' ', stderr);
1518 /* Does it need shell quoting? This only deals with simple cases. */
1519 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1521 if (needs_quote) fputc ('\'', stderr);
1522 fprintf (stderr, "%s", g->cmdline[i]);
1523 if (needs_quote) fputc ('\'', stderr);
1527 fputc ('\n', stderr);
1530 /* This function does the hard work of building the supermin appliance
1531 * on the fly. 'path' is the directory containing the control files.
1532 * 'kernel' and 'initrd' are where we will return the names of the
1533 * kernel and initrd (only initrd is built). The work is done by
1534 * an external script. We just tell it where to put the result.
1537 build_supermin_appliance (guestfs_h *g, const char *path,
1538 char **kernel, char **initrd)
1544 print_timestamped_message (g, "begin building supermin appliance");
1546 len = strlen (g->tmpdir);
1547 *kernel = safe_malloc (g, len + 8);
1548 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1549 *initrd = safe_malloc (g, len + 8);
1550 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1552 snprintf (cmd, sizeof cmd,
1554 "libguestfs-supermin-helper%s '%s' " host_cpu " " REPO " %s %s",
1556 g->verbose ? " --verbose" : "",
1557 path, *kernel, *initrd);
1559 print_timestamped_message (g, "%s", cmd);
1562 if (r == -1 || WEXITSTATUS(r) != 0) {
1563 error (g, _("external command failed: %s"), cmd);
1566 *kernel = *initrd = NULL;
1571 print_timestamped_message (g, "finished building supermin appliance");
1576 /* Compute Y - X and return the result in milliseconds.
1577 * Approximately the same as this code:
1578 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1581 timeval_diff (const struct timeval *x, const struct timeval *y)
1585 msec = (y->tv_sec - x->tv_sec) * 1000;
1586 msec += (y->tv_usec - x->tv_usec) / 1000;
1591 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1598 va_start (args, fs);
1599 err = vasprintf (&msg, fs, args);
1602 if (err < 0) return;
1604 gettimeofday (&tv, NULL);
1606 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1607 timeval_diff (&g->launch_t, &tv), msg);
1612 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1614 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1615 * 'qemu -version' so we know what options this qemu supports and
1619 test_qemu (guestfs_h *g)
1624 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1626 fp = popen (cmd, "r");
1627 /* qemu -help should always work (qemu -version OTOH wasn't
1628 * supported by qemu 0.9). If this command doesn't work then it
1629 * probably indicates that the qemu binary is missing.
1632 /* XXX This error is never printed, even if the qemu binary
1633 * doesn't exist. Why?
1636 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1640 if (read_all (g, fp, &g->qemu_help) == -1)
1643 if (pclose (fp) == -1)
1646 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1649 fp = popen (cmd, "r");
1651 /* Intentionally ignore errors. */
1652 read_all (g, fp, &g->qemu_version);
1660 read_all (guestfs_h *g, FILE *fp, char **ret)
1667 *ret = safe_realloc (g, *ret, n + 1);
1672 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1674 r = fread (p, 1, BUFSIZ, fp);
1676 perrorf (g, "read");
1683 /* Test if option is supported by qemu command line (just by grepping
1686 * The first time this is used, it has to run the external qemu
1687 * binary. If that fails, it returns -1.
1689 * To just do the first-time run of the qemu binary, call this with
1690 * option == NULL, in which case it will return -1 if there was an
1694 qemu_supports (guestfs_h *g, const char *option)
1696 if (!g->qemu_help) {
1697 if (test_qemu (g) == -1)
1704 return strstr (g->qemu_help, option) != NULL;
1707 /* Check if a file can be opened. */
1709 is_openable (guestfs_h *g, const char *path, int flags)
1711 int fd = open (path, flags);
1721 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1722 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1723 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1726 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1728 struct sockaddr_in peer;
1729 socklen_t addrlen = sizeof peer;
1731 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1732 perrorf (g, "getpeername");
1736 if (peer.sin_family != AF_INET ||
1737 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1738 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1739 peer.sin_family, inet_ntoa (peer.sin_addr));
1743 struct sockaddr_in our;
1744 addrlen = sizeof our;
1745 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1746 perrorf (g, "getsockname");
1750 FILE *fp = fopen ("/proc/net/tcp", "r");
1752 perrorf (g, "/proc/net/tcp");
1757 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1758 error (g, "unexpected end of file in /proc/net/tcp");
1763 while (fgets (line, sizeof line, fp) != NULL) {
1764 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1765 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1768 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1770 &line_our_addr, &line_our_port,
1771 &line_peer_addr, &line_peer_port,
1772 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1774 /* Note about /proc/net/tcp: local_address and rem_address are
1775 * always in network byte order. However the port part is
1776 * always in host byte order.
1778 * The sockname and peername that we got above are in network
1779 * byte order. So we have to byte swap the port but not the
1782 if (line_our_addr == our.sin_addr.s_addr &&
1783 line_our_port == ntohs (our.sin_port) &&
1784 line_peer_addr == peer.sin_addr.s_addr &&
1785 line_peer_port == ntohs (peer.sin_port)) {
1793 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1798 /* You had to call this function after launch in versions <= 1.0.70,
1799 * but it is now a no-op.
1802 guestfs__wait_ready (guestfs_h *g)
1804 if (g->state != READY) {
1805 error (g, _("qemu has not been launched yet"));
1813 guestfs__kill_subprocess (guestfs_h *g)
1815 if (g->state == CONFIG) {
1816 error (g, _("no subprocess to kill"));
1821 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1823 kill (g->pid, SIGTERM);
1824 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1829 /* Access current state. */
1831 guestfs__is_config (guestfs_h *g)
1833 return g->state == CONFIG;
1837 guestfs__is_launching (guestfs_h *g)
1839 return g->state == LAUNCHING;
1843 guestfs__is_ready (guestfs_h *g)
1845 return g->state == READY;
1849 guestfs__is_busy (guestfs_h *g)
1851 return g->state == BUSY;
1855 guestfs__get_state (guestfs_h *g)
1861 guestfs_set_log_message_callback (guestfs_h *g,
1862 guestfs_log_message_cb cb, void *opaque)
1864 g->log_message_cb = cb;
1865 g->log_message_cb_data = opaque;
1869 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1870 guestfs_subprocess_quit_cb cb, void *opaque)
1872 g->subprocess_quit_cb = cb;
1873 g->subprocess_quit_cb_data = opaque;
1877 guestfs_set_launch_done_callback (guestfs_h *g,
1878 guestfs_launch_done_cb cb, void *opaque)
1880 g->launch_done_cb = cb;
1881 g->launch_done_cb_data = opaque;
1884 /*----------------------------------------------------------------------*/
1886 /* This is the code used to send and receive RPC messages and (for
1887 * certain types of message) to perform file transfers. This code is
1888 * driven from the generated actions (src/guestfs-actions.c). There
1889 * are five different cases to consider:
1891 * (1) A non-daemon function. There is no RPC involved at all, it's
1892 * all handled inside the library.
1894 * (2) A simple RPC (eg. "mount"). We write the request, then read
1895 * the reply. The sequence of calls is:
1897 * guestfs___set_busy
1900 * guestfs___end_busy
1902 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1903 * request, then write the file(s), then read the reply. The sequence
1906 * guestfs___set_busy
1908 * guestfs___send_file (possibly multiple times)
1910 * guestfs___end_busy
1912 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1913 * request, then read the reply, then read the file(s). The sequence
1916 * guestfs___set_busy
1919 * guestfs___recv_file (possibly multiple times)
1920 * guestfs___end_busy
1922 * (5) Both FileOut and FileIn parameters. There are no calls like
1923 * this in the current API, but they would be implemented as a
1924 * combination of cases (3) and (4).
1926 * During all writes and reads, we also select(2) on qemu stdout
1927 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1928 * anything received is passed up through the log_message_cb. This is
1929 * also the reason why all the sockets are non-blocking. We also have
1930 * to check for EOF (qemu died). All of this is handled by the
1931 * functions send_to_daemon and recv_from_daemon.
1935 guestfs___set_busy (guestfs_h *g)
1937 if (g->state != READY) {
1938 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1947 guestfs___end_busy (guestfs_h *g)
1961 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1967 /* This is called if we detect EOF, ie. qemu died. */
1969 child_cleanup (guestfs_h *g)
1972 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1974 /*kill (g->pid, SIGTERM);*/
1975 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1976 waitpid (g->pid, NULL, 0);
1977 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1986 memset (&g->launch_t, 0, sizeof g->launch_t);
1988 if (g->subprocess_quit_cb)
1989 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1993 read_log_message_or_eof (guestfs_h *g, int fd)
2001 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2005 /* QEMU's console emulates a 16550A serial port. The real 16550A
2006 * device has a small FIFO buffer (16 bytes) which means here we see
2007 * lots of small reads of 1-16 bytes in length, usually single
2010 n = read (fd, buf, sizeof buf);
2012 /* Hopefully this indicates the qemu child process has died. */
2018 if (errno == EINTR || errno == EAGAIN)
2021 perrorf (g, "read");
2025 /* In verbose mode, copy all log messages to stderr. */
2027 ignore_value (write (STDERR_FILENO, buf, n));
2029 /* It's an actual log message, send it upwards if anyone is listening. */
2030 if (g->log_message_cb)
2031 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2037 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2046 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2049 n = read (fd, buf, 4);
2051 /* Hopefully this indicates the qemu child process has died. */
2057 if (errno == EINTR || errno == EAGAIN)
2060 perrorf (g, "read");
2064 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2065 xdr_uint32_t (&xdr, &flag);
2068 if (flag != GUESTFS_CANCEL_FLAG) {
2069 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2070 flag, GUESTFS_CANCEL_FLAG);
2077 /* This writes the whole N bytes of BUF to the daemon socket.
2079 * If the whole write is successful, it returns 0.
2080 * If there was an error, it returns -1.
2081 * If the daemon sent a cancellation message, it returns -2.
2083 * It also checks qemu stdout for log messages and passes those up
2084 * through log_message_cb.
2086 * It also checks for EOF (qemu died) and passes that up through the
2087 * child_cleanup function above.
2090 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2092 const char *buf = v_buf;
2098 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2103 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2104 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2105 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2107 int max_fd = MAX (g->sock, g->fd[1]);
2112 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2114 if (errno == EINTR || errno == EAGAIN)
2116 perrorf (g, "select");
2120 if (FD_ISSET (g->fd[1], &rset2)) {
2121 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2124 if (FD_ISSET (g->sock, &rset2)) {
2125 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2129 if (FD_ISSET (g->sock, &wset2)) {
2130 r = write (g->sock, buf, n);
2132 if (errno == EINTR || errno == EAGAIN)
2134 perrorf (g, "write");
2135 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2147 /* This reads a single message, file chunk, launch flag or
2148 * cancellation flag from the daemon. If something was read, it
2149 * returns 0, otherwise -1.
2151 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2153 * *size_rtn returns the size of the returned message or it may be
2154 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2156 * *buf_rtn is returned containing the message (if any) or will be set
2157 * to NULL. *buf_rtn must be freed by the caller.
2159 * It also checks qemu stdout for log messages and passes those up
2160 * through log_message_cb.
2162 * It also checks for EOF (qemu died) and passes that up through the
2163 * child_cleanup function above.
2166 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2172 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2173 g, g->state, size_rtn, buf_rtn);
2177 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2178 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2180 int max_fd = MAX (g->sock, g->fd[1]);
2186 /* nr is the size of the message, but we prime it as -4 because we
2187 * have to read the message length word first.
2191 while (nr < (ssize_t) *size_rtn) {
2193 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2195 if (errno == EINTR || errno == EAGAIN)
2197 perrorf (g, "select");
2203 if (FD_ISSET (g->fd[1], &rset2)) {
2204 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2210 if (FD_ISSET (g->sock, &rset2)) {
2211 if (nr < 0) { /* Have we read the message length word yet? */
2212 r = read (g->sock, lenbuf+nr+4, -nr);
2214 if (errno == EINTR || errno == EAGAIN)
2217 perrorf (g, "read");
2218 /* Under some circumstances we see "Connection reset by peer"
2219 * here when the child dies suddenly. Catch this and call
2220 * the cleanup function, same as for EOF.
2222 if (err == ECONNRESET)
2227 error (g, _("unexpected end of file when reading from daemon"));
2233 if (nr < 0) /* Still not got the whole length word. */
2237 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2238 xdr_uint32_t (&xdr, size_rtn);
2241 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2242 if (g->state != LAUNCHING)
2243 error (g, _("received magic signature from guestfsd, but in state %d"),
2247 if (g->launch_done_cb)
2248 g->launch_done_cb (g, g->launch_done_cb_data);
2252 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2254 /* If this happens, it's pretty bad and we've probably lost
2257 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2258 error (g, _("message length (%u) > maximum possible size (%d)"),
2259 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2263 /* Allocate the complete buffer, size now known. */
2264 *buf_rtn = safe_malloc (g, *size_rtn);
2268 size_t sizetoread = *size_rtn - nr;
2269 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2271 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2273 if (errno == EINTR || errno == EAGAIN)
2275 perrorf (g, "read");
2281 error (g, _("unexpected end of file when reading from daemon"));
2291 /* Got the full message, caller can start processing it. */
2292 #ifdef ENABLE_PACKET_DUMP
2296 for (i = 0; i < nr; i += 16) {
2297 printf ("%04zx: ", i);
2298 for (j = i; j < MIN (i+16, nr); ++j)
2299 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2300 for (; j < i+16; ++j)
2303 for (j = i; j < MIN (i+16, nr); ++j)
2304 if (c_isprint ((*(char **)buf_rtn)[j]))
2305 printf ("%c", (*(char **)buf_rtn)[j]);
2308 for (; j < i+16; ++j)
2318 /* This is very much like recv_from_daemon above, but g->sock is
2319 * a listening socket and we are accepting a new connection on
2320 * that socket instead of reading anything. Returns the newly
2324 accept_from_daemon (guestfs_h *g)
2330 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2334 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2335 FD_SET (g->sock, &rset); /* Read socket for accept. */
2337 int max_fd = MAX (g->sock, g->fd[1]);
2340 while (sock == -1) {
2342 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2344 if (errno == EINTR || errno == EAGAIN)
2346 perrorf (g, "select");
2350 if (FD_ISSET (g->fd[1], &rset2)) {
2351 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2354 if (FD_ISSET (g->sock, &rset2)) {
2355 sock = accept (g->sock, NULL, NULL);
2357 if (errno == EINTR || errno == EAGAIN)
2359 perrorf (g, "accept");
2369 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2371 struct guestfs_message_header hdr;
2374 int serial = g->msg_next_serial++;
2377 size_t msg_out_size;
2379 if (g->state != BUSY) {
2380 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2384 /* We have to allocate this message buffer on the heap because
2385 * it is quite large (although will be mostly unused). We
2386 * can't allocate it on the stack because in some environments
2387 * we have quite limited stack space available, notably when
2388 * running in the JVM.
2390 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2391 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2393 /* Serialize the header. */
2394 hdr.prog = GUESTFS_PROGRAM;
2395 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2397 hdr.direction = GUESTFS_DIRECTION_CALL;
2398 hdr.serial = serial;
2399 hdr.status = GUESTFS_STATUS_OK;
2401 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2402 error (g, _("xdr_guestfs_message_header failed"));
2406 /* Serialize the args. If any, because some message types
2407 * have no parameters.
2410 if (!(*xdrp) (&xdr, args)) {
2411 error (g, _("dispatch failed to marshal args"));
2416 /* Get the actual length of the message, resize the buffer to match
2417 * the actual length, and write the length word at the beginning.
2419 len = xdr_getpos (&xdr);
2422 msg_out = safe_realloc (g, msg_out, len + 4);
2423 msg_out_size = len + 4;
2425 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2426 xdr_uint32_t (&xdr, &len);
2429 r = send_to_daemon (g, msg_out, msg_out_size);
2430 if (r == -2) /* Ignore stray daemon cancellations. */
2443 static int cancel = 0; /* XXX Implement file cancellation. */
2444 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2445 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2446 static int send_file_cancellation (guestfs_h *g);
2447 static int send_file_complete (guestfs_h *g);
2453 * -2 daemon cancelled (we must read the error message)
2456 guestfs___send_file (guestfs_h *g, const char *filename)
2458 char buf[GUESTFS_MAX_CHUNK_SIZE];
2461 fd = open (filename, O_RDONLY);
2463 perrorf (g, "open: %s", filename);
2464 send_file_cancellation (g);
2465 /* Daemon sees cancellation and won't reply, so caller can
2471 /* Send file in chunked encoding. */
2473 r = read (fd, buf, sizeof buf);
2474 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2477 err = send_file_data (g, buf, r);
2479 if (err == -2) /* daemon sent cancellation */
2480 send_file_cancellation (g);
2485 if (cancel) { /* cancel from either end */
2486 send_file_cancellation (g);
2491 perrorf (g, "read: %s", filename);
2492 send_file_cancellation (g);
2496 /* End of file, but before we send that, we need to close
2497 * the file and check for errors.
2499 if (close (fd) == -1) {
2500 perrorf (g, "close: %s", filename);
2501 send_file_cancellation (g);
2505 return send_file_complete (g);
2508 /* Send a chunk of file data. */
2510 send_file_data (guestfs_h *g, const char *buf, size_t len)
2512 return send_file_chunk (g, 0, buf, len);
2515 /* Send a cancellation message. */
2517 send_file_cancellation (guestfs_h *g)
2519 return send_file_chunk (g, 1, NULL, 0);
2522 /* Send a file complete chunk. */
2524 send_file_complete (guestfs_h *g)
2527 return send_file_chunk (g, 0, buf, 0);
2531 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2535 guestfs_chunk chunk;
2538 size_t msg_out_size;
2540 if (g->state != BUSY) {
2541 error (g, _("send_file_chunk: state %d != READY"), g->state);
2545 /* Allocate the chunk buffer. Don't use the stack to avoid
2546 * excessive stack usage and unnecessary copies.
2548 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2549 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2551 /* Serialize the chunk. */
2552 chunk.cancel = cancel;
2553 chunk.data.data_len = buflen;
2554 chunk.data.data_val = (char *) buf;
2556 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2557 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2563 len = xdr_getpos (&xdr);
2566 /* Reduce the size of the outgoing message buffer to the real length. */
2567 msg_out = safe_realloc (g, msg_out, len + 4);
2568 msg_out_size = len + 4;
2570 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2571 xdr_uint32_t (&xdr, &len);
2573 r = send_to_daemon (g, msg_out, msg_out_size);
2575 /* Did the daemon send a cancellation message? */
2578 fprintf (stderr, "got daemon cancellation\n");
2594 /* Receive a reply. */
2596 guestfs___recv (guestfs_h *g, const char *fn,
2597 guestfs_message_header *hdr,
2598 guestfs_message_error *err,
2599 xdrproc_t xdrp, char *ret)
2607 r = recv_from_daemon (g, &size, &buf);
2611 /* This can happen if a cancellation happens right at the end
2612 * of us sending a FileIn parameter to the daemon. Discard. The
2613 * daemon should send us an error message next.
2615 if (size == GUESTFS_CANCEL_FLAG)
2618 if (size == GUESTFS_LAUNCH_FLAG) {
2619 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2623 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2625 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2626 error (g, "%s: failed to parse reply header", fn);
2631 if (hdr->status == GUESTFS_STATUS_ERROR) {
2632 if (!xdr_guestfs_message_error (&xdr, err)) {
2633 error (g, "%s: failed to parse reply error", fn);
2639 if (xdrp && ret && !xdrp (&xdr, ret)) {
2640 error (g, "%s: failed to parse reply", fn);
2652 /* Receive a file. */
2654 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2655 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2658 guestfs___recv_file (guestfs_h *g, const char *filename)
2663 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2665 perrorf (g, "open: %s", filename);
2669 /* Receive the file in chunked encoding. */
2670 while ((r = receive_file_data (g, &buf)) > 0) {
2671 if (xwrite (fd, buf, r) == -1) {
2672 perrorf (g, "%s: write", filename);
2680 error (g, _("%s: error in chunked encoding"), filename);
2684 if (close (fd) == -1) {
2685 perrorf (g, "close: %s", filename);
2692 /* Send cancellation message to daemon, then wait until it
2693 * cancels (just throwing away data).
2697 uint32_t flag = GUESTFS_CANCEL_FLAG;
2700 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2703 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2704 xdr_uint32_t (&xdr, &flag);
2707 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2708 perrorf (g, _("write to daemon socket"));
2712 while (receive_file_data (g, NULL) > 0)
2713 ; /* just discard it */
2718 /* Receive a chunk of file data. */
2719 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2721 receive_file_data (guestfs_h *g, void **buf_r)
2727 guestfs_chunk chunk;
2729 r = recv_from_daemon (g, &len, &buf);
2731 error (g, _("receive_file_data: parse error in reply callback"));
2735 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2736 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2740 memset (&chunk, 0, sizeof chunk);
2742 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2743 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2744 error (g, _("failed to parse file chunk"));
2749 /* After decoding, the original buffer is no longer used. */
2753 error (g, _("file receive cancelled by daemon"));
2754 free (chunk.data.data_val);
2758 if (chunk.data.data_len == 0) { /* end of transfer */
2759 free (chunk.data.data_val);
2763 if (buf_r) *buf_r = chunk.data.data_val;
2764 else free (chunk.data.data_val); /* else caller frees */
2766 return chunk.data.data_len;