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
90 #define CAN_CHECK_PEER_EUID 1
92 #define CAN_CHECK_PEER_EUID 0
95 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
96 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
97 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
98 static int accept_from_daemon (guestfs_h *g);
99 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
100 static void close_handles (void);
101 static int qemu_supports (guestfs_h *g, const char *option);
103 #define UNIX_PATH_MAX 108
106 #define MAX(a,b) ((a)>(b)?(a):(b))
110 #define xdr_uint32_t xdr_u_int32_t
113 /* Network configuration of the appliance. Note these addresses are
114 * only meaningful within the context of the running appliance. QEMU
115 * translates network connections to these magic addresses into
116 * userspace calls on the host (eg. connect(2)). qemu-doc has a nice
117 * diagram which is also useful to refer to.
119 * NETWORK: The network.
121 * ROUTER: The address of the "host", ie. this library.
123 * [Note: If you change NETWORK and ROUTER then you also have to
124 * change the network configuration in appliance/init].
126 * GUESTFWD_ADDR, GUESTFWD_PORT: The guestfwd feature of qemu
127 * magically connects this pseudo-address to the guestfwd channel. In
128 * typical Linux configurations of libguestfs, guestfwd is not
129 * actually used any more.
131 #define NETWORK "169.254.0.0/16"
132 #define ROUTER "169.254.2.2"
133 #define GUESTFWD_ADDR "169.254.2.4"
134 #define GUESTFWD_PORT "6666"
136 /* GuestFS handle and connection. */
137 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
141 struct guestfs_h *next; /* Linked list of open handles. */
143 /* State: see the state machine diagram in the man page guestfs(3). */
146 int fd[2]; /* Stdin/stdout of qemu. */
147 int sock; /* Daemon communications socket. */
148 pid_t pid; /* Qemu PID. */
149 pid_t recoverypid; /* Recovery process PID. */
151 struct timeval launch_t; /* The time that we called guestfs_launch. */
153 char *tmpdir; /* Temporary directory containing socket. */
155 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
157 char **cmdline; /* Qemu command line. */
166 char *path; /* Path to kernel, initrd. */
167 char *qemu; /* Qemu binary. */
168 char *append; /* Append to kernel command line. */
170 int memsize; /* Size of RAM (megabytes). */
172 int selinux; /* selinux enabled? */
177 guestfs_abort_cb abort_cb;
178 guestfs_error_handler_cb error_cb;
179 void * error_cb_data;
180 guestfs_log_message_cb log_message_cb;
181 void * log_message_cb_data;
182 guestfs_subprocess_quit_cb subprocess_quit_cb;
183 void * subprocess_quit_cb_data;
184 guestfs_launch_done_cb launch_done_cb;
185 void * launch_done_cb_data;
190 gl_lock_define_initialized (static, handles_lock);
191 static guestfs_h *handles = NULL;
192 static int atexit_handler_set = 0;
195 guestfs_create (void)
200 g = malloc (sizeof (*g));
203 memset (g, 0, sizeof (*g));
212 g->error_cb = default_error_cb;
213 g->error_cb_data = NULL;
215 g->recovery_proc = 1;
217 str = getenv ("LIBGUESTFS_DEBUG");
218 g->verbose = str != NULL && STREQ (str, "1");
220 str = getenv ("LIBGUESTFS_TRACE");
221 g->trace = str != NULL && STREQ (str, "1");
223 str = getenv ("LIBGUESTFS_PATH");
224 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
225 if (!g->path) goto error;
227 str = getenv ("LIBGUESTFS_QEMU");
228 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
229 if (!g->qemu) goto error;
231 str = getenv ("LIBGUESTFS_APPEND");
233 g->append = strdup (str);
234 if (!g->append) goto error;
237 /* Choose a suitable memory size. Previously we tried to choose
238 * a minimal memory size, but this isn't really necessary since
239 * recent QEMU and KVM don't do anything nasty like locking
240 * memory into core any more. Thus we can safely choose a
241 * large, generous amount of memory, and it'll just get swapped
242 * on smaller systems.
244 str = getenv ("LIBGUESTFS_MEMSIZE");
246 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
247 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
253 /* Start with large serial numbers so they are easy to spot
254 * inside the protocol.
256 g->msg_next_serial = 0x00123400;
258 /* Link the handles onto a global list. */
259 gl_lock_lock (handles_lock);
262 if (!atexit_handler_set) {
263 atexit (close_handles);
264 atexit_handler_set = 1;
266 gl_lock_unlock (handles_lock);
269 fprintf (stderr, "new guestfs handle %p\n", g);
282 guestfs_close (guestfs_h *g)
288 if (g->state == NO_HANDLE) {
289 /* Not safe to call 'error' here, so ... */
290 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
295 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
297 /* Try to sync if autosync flag is set. */
298 if (g->autosync && g->state == READY) {
299 guestfs_umount_all (g);
303 /* Remove any handlers that might be called back before we kill the
306 g->log_message_cb = NULL;
308 if (g->state != CONFIG)
309 guestfs_kill_subprocess (g);
322 /* Wait for subprocess(es) to exit. */
323 waitpid (g->pid, NULL, 0);
324 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
326 /* Remove tmpfiles. */
328 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
331 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
334 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
343 for (i = 0; i < g->cmdline_size; ++i)
344 free (g->cmdline[i]);
348 /* Mark the handle as dead before freeing it. */
349 g->state = NO_HANDLE;
351 gl_lock_lock (handles_lock);
355 for (gg = handles; gg->next != g; gg = gg->next)
359 gl_lock_unlock (handles_lock);
361 free (g->last_error);
366 free (g->qemu_version);
370 /* Close all open handles (called from atexit(3)). */
374 while (handles) guestfs_close (handles);
378 guestfs_last_error (guestfs_h *g)
380 return g->last_error;
384 set_last_error (guestfs_h *g, const char *msg)
386 free (g->last_error);
387 g->last_error = strdup (msg);
391 default_error_cb (guestfs_h *g, void *data, const char *msg)
393 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
397 guestfs_error (guestfs_h *g, const char *fs, ...)
403 int err = vasprintf (&msg, fs, args);
408 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
409 set_last_error (g, msg);
415 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
422 int err = vasprintf (&msg, fs, args);
427 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
429 strerror_r (errnum, buf, sizeof buf);
433 buf = strerror_r (errnum, _buf, sizeof _buf);
436 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
440 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
441 set_last_error (g, msg);
447 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
449 void *ptr = malloc (nbytes);
450 if (nbytes > 0 && !ptr) g->abort_cb ();
454 /* Return 1 if an array of N objects, each of size S, cannot exist due
455 to size arithmetic overflow. S must be positive and N must be
456 nonnegative. This is a macro, not an inline function, so that it
457 works correctly even when SIZE_MAX < N.
459 By gnulib convention, SIZE_MAX represents overflow in size
460 calculations, so the conservative dividend to use here is
461 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
462 However, malloc (SIZE_MAX) fails on all known hosts where
463 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
464 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
465 branch when S is known to be 1. */
466 # define xalloc_oversized(n, s) \
467 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
469 /* Technically we should add an autoconf test for this, testing for the desired
470 functionality, like what's done in gnulib, but for now, this is fine. */
471 #if defined(__GLIBC__)
472 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
474 #define HAVE_GNU_CALLOC 0
477 /* Allocate zeroed memory for N elements of S bytes, with error
478 checking. S must be nonzero. */
480 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
482 /* From gnulib's calloc function in xmalloc.c. */
484 /* Test for overflow, since some calloc implementations don't have
485 proper overflow checks. But omit overflow and size-zero tests if
486 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
487 returns NULL if successful. */
488 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
489 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
495 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
497 void *p = realloc (ptr, nbytes);
498 if (nbytes > 0 && !p) g->abort_cb ();
503 guestfs_safe_strdup (guestfs_h *g, const char *str)
505 char *s = strdup (str);
506 if (!s) g->abort_cb ();
511 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
513 void *p = malloc (size);
514 if (!p) g->abort_cb ();
515 memcpy (p, ptr, size);
520 xwrite (int fd, const void *v_buf, size_t len)
522 const char *buf = v_buf;
526 r = write (fd, buf, len);
538 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
544 guestfs_get_out_of_memory_handler (guestfs_h *g)
550 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
553 g->error_cb_data = data;
556 guestfs_error_handler_cb
557 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
559 if (data_rtn) *data_rtn = g->error_cb_data;
564 guestfs__set_verbose (guestfs_h *g, int v)
571 guestfs__get_verbose (guestfs_h *g)
577 guestfs__set_autosync (guestfs_h *g, int a)
584 guestfs__get_autosync (guestfs_h *g)
590 guestfs__set_path (guestfs_h *g, const char *path)
597 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
602 guestfs__get_path (guestfs_h *g)
608 guestfs__set_qemu (guestfs_h *g, const char *qemu)
613 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
618 guestfs__get_qemu (guestfs_h *g)
624 guestfs__set_append (guestfs_h *g, const char *append)
629 g->append = append ? safe_strdup (g, append) : NULL;
634 guestfs__get_append (guestfs_h *g)
640 guestfs__set_memsize (guestfs_h *g, int memsize)
642 g->memsize = memsize;
647 guestfs__get_memsize (guestfs_h *g)
653 guestfs__set_selinux (guestfs_h *g, int selinux)
655 g->selinux = selinux;
660 guestfs__get_selinux (guestfs_h *g)
666 guestfs__get_pid (guestfs_h *g)
671 error (g, "get_pid: no qemu subprocess");
676 struct guestfs_version *
677 guestfs__version (guestfs_h *g)
679 struct guestfs_version *r;
681 r = safe_malloc (g, sizeof *r);
682 r->major = PACKAGE_VERSION_MAJOR;
683 r->minor = PACKAGE_VERSION_MINOR;
684 r->release = PACKAGE_VERSION_RELEASE;
685 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
690 guestfs__set_trace (guestfs_h *g, int t)
697 guestfs__get_trace (guestfs_h *g)
703 guestfs__set_direct (guestfs_h *g, int d)
710 guestfs__get_direct (guestfs_h *g)
716 guestfs__set_recovery_proc (guestfs_h *g, int f)
718 g->recovery_proc = !!f;
723 guestfs__get_recovery_proc (guestfs_h *g)
725 return g->recovery_proc;
728 /* Add a string to the current command line. */
730 incr_cmdline_size (guestfs_h *g)
732 if (g->cmdline == NULL) {
733 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
735 g->cmdline = safe_malloc (g, sizeof (char *));
736 g->cmdline[0] = NULL;
740 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
744 add_cmdline (guestfs_h *g, const char *str)
746 if (g->state != CONFIG) {
748 _("command line cannot be altered after qemu subprocess launched"));
752 incr_cmdline_size (g);
753 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
758 guestfs__config (guestfs_h *g,
759 const char *qemu_param, const char *qemu_value)
761 if (qemu_param[0] != '-') {
762 error (g, _("guestfs_config: parameter must begin with '-' character"));
766 /* A bit fascist, but the user will probably break the extra
767 * parameters that we add if they try to set any of these.
769 if (STREQ (qemu_param, "-kernel") ||
770 STREQ (qemu_param, "-initrd") ||
771 STREQ (qemu_param, "-nographic") ||
772 STREQ (qemu_param, "-serial") ||
773 STREQ (qemu_param, "-full-screen") ||
774 STREQ (qemu_param, "-std-vga") ||
775 STREQ (qemu_param, "-vnc")) {
776 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
780 if (add_cmdline (g, qemu_param) != 0) return -1;
782 if (qemu_value != NULL) {
783 if (add_cmdline (g, qemu_value) != 0) return -1;
790 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
791 const char *drive_if)
793 size_t len = strlen (filename) + 64;
796 if (strchr (filename, ',') != NULL) {
797 error (g, _("filename cannot contain ',' (comma) character"));
801 /* cache=off improves reliability in the event of a host crash.
803 * However this option causes qemu to try to open the file with
804 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
805 * So we check if we can open the file with or without O_DIRECT,
806 * and use cache=off (or not) accordingly.
808 * This test also checks for the presence of the file, which
809 * is a documented semantic of this interface.
811 int fd = open (filename, O_RDONLY|O_DIRECT);
814 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
816 fd = open (filename, O_RDONLY);
819 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
821 perrorf (g, "%s", filename);
826 return guestfs__config (g, "-drive", buf);
830 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
831 const char *drive_if)
833 if (strchr (filename, ',') != NULL) {
834 error (g, _("filename cannot contain ',' (comma) character"));
838 if (access (filename, F_OK) == -1) {
839 perrorf (g, "%s", filename);
843 if (qemu_supports (g, NULL) == -1)
846 /* Only SCSI and virtio drivers support readonly mode.
847 * This is only supported as a QEMU feature since 2010/01.
850 if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
851 qemu_supports (g, "readonly=on"))
854 size_t len = strlen (filename) + 100;
857 snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
859 supports_ro ? "readonly=on," : "",
862 return guestfs__config (g, "-drive", buf);
866 guestfs__add_drive (guestfs_h *g, const char *filename)
868 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
872 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
874 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
878 guestfs__add_cdrom (guestfs_h *g, const char *filename)
880 if (strchr (filename, ',') != NULL) {
881 error (g, _("filename cannot contain ',' (comma) character"));
885 if (access (filename, F_OK) == -1) {
886 perrorf (g, "%s", filename);
890 return guestfs__config (g, "-cdrom", filename);
893 /* Returns true iff file is contained in dir. */
895 dir_contains_file (const char *dir, const char *file)
897 int dirlen = strlen (dir);
898 int filelen = strlen (file);
899 int len = dirlen+filelen+2;
902 snprintf (path, len, "%s/%s", dir, file);
903 return access (path, F_OK) == 0;
906 /* Returns true iff every listed file is contained in 'dir'. */
908 dir_contains_files (const char *dir, ...)
913 va_start (args, dir);
914 while ((file = va_arg (args, const char *)) != NULL) {
915 if (!dir_contains_file (dir, file)) {
924 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
925 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
926 static int is_openable (guestfs_h *g, const char *path, int flags);
927 static void print_cmdline (guestfs_h *g);
929 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
930 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
933 guestfs__launch (guestfs_h *g)
936 char dir_template[PATH_MAX];
941 char *path, *pelem, *pend;
942 char *kernel = NULL, *initrd = NULL;
943 int null_vmchannel_sock;
945 struct sockaddr_un addr;
949 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
953 if (g->state != CONFIG) {
954 error (g, _("the libguestfs handle has already been launched"));
958 /* Start the clock ... */
959 gettimeofday (&g->launch_t, NULL);
961 /* Make the temporary directory. */
968 tmpdir = getenv ("TMPDIR") ? : tmpdir;
969 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
972 g->tmpdir = safe_strdup (g, dir_template);
973 if (mkdtemp (g->tmpdir) == NULL) {
974 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
979 /* First search g->path for the supermin appliance, and try to
980 * synthesize a kernel and initrd from that. If it fails, we
981 * try the path search again looking for a backup ordinary
984 pelem = path = safe_strdup (g, g->path);
986 pend = strchrnul (pelem, ':');
987 pmore = *pend == ':';
991 /* Empty element of "." means cwd. */
992 if (len == 0 || (len == 1 && *pelem == '.')) {
995 "looking for supermin appliance in current directory\n");
996 if (dir_contains_files (".",
997 "supermin.d", "kmod.whitelist", NULL)) {
998 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
1003 /* Look at <path>/supermin* etc. */
1006 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
1008 if (dir_contains_files (pelem,
1009 "supermin.d", "kmod.whitelist", NULL)) {
1010 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1021 if (kernel == NULL || initrd == NULL) {
1022 /* Search g->path for the kernel and initrd. */
1023 pelem = path = safe_strdup (g, g->path);
1025 pend = strchrnul (pelem, ':');
1026 pmore = *pend == ':';
1030 /* Empty element or "." means cwd. */
1031 if (len == 0 || (len == 1 && *pelem == '.')) {
1034 "looking for appliance in current directory\n");
1035 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1036 kernel = safe_strdup (g, kernel_name);
1037 initrd = safe_strdup (g, initrd_name);
1041 /* Look at <path>/kernel etc. */
1044 fprintf (stderr, "looking for appliance in %s\n", pelem);
1046 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1047 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1048 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1049 sprintf (kernel, "%s/%s", pelem, kernel_name);
1050 sprintf (initrd, "%s/%s", pelem, initrd_name);
1061 if (kernel == NULL || initrd == NULL) {
1062 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1063 kernel_name, initrd_name, g->path);
1068 print_timestamped_message (g, "begin testing qemu features");
1070 /* Get qemu help text and version. */
1071 if (qemu_supports (g, NULL) == -1)
1074 /* Choose which vmchannel implementation to use. */
1075 if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
1076 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1077 * networking in qemu) but no other vmchannel support. The daemon
1078 * will connect back to a random port number on localhost.
1080 struct sockaddr_in addr;
1081 socklen_t addrlen = sizeof addr;
1083 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1084 if (g->sock == -1) {
1085 perrorf (g, "socket");
1088 addr.sin_family = AF_INET;
1089 addr.sin_port = htons (0);
1090 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1091 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1092 perrorf (g, "bind");
1096 if (listen (g->sock, 256) == -1) {
1097 perrorf (g, "listen");
1101 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1102 perrorf (g, "getsockname");
1106 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1107 perrorf (g, "fcntl");
1111 null_vmchannel_sock = ntohs (addr.sin_port);
1113 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1115 /* Using some vmchannel impl. We need to create a local Unix
1116 * domain socket for qemu to use.
1118 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1120 null_vmchannel_sock = 0;
1124 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1125 perrorf (g, "pipe");
1131 print_timestamped_message (g, "finished testing qemu features");
1135 perrorf (g, "fork");
1145 if (r == 0) { /* Child (qemu). */
1147 const char *vmchannel = NULL;
1149 /* Set up the full command line. Do this in the subprocess so we
1150 * don't need to worry about cleaning up.
1152 g->cmdline[0] = g->qemu;
1154 /* qemu sometimes needs this option to enable hardware
1155 * virtualization, but some versions of 'qemu-kvm' will use KVM
1156 * regardless (even where this option appears in the help text).
1157 * It is rumoured that there are versions of qemu where supplying
1158 * this option when hardware virtualization is not available will
1159 * cause qemu to fail, so we we have to check at least that
1160 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1161 * might be openable by qemu but not by us (think: SELinux) in
1162 * which case the user would not get hardware virtualization,
1163 * although at least shouldn't fail. A giant clusterfuck with the
1164 * qemu command line, again.
1166 if (qemu_supports (g, "-enable-kvm") &&
1167 is_openable (g, "/dev/kvm", O_RDWR))
1168 add_cmdline (g, "-enable-kvm");
1170 /* Newer versions of qemu (from around 2009/12) changed the
1171 * behaviour of monitors so that an implicit '-monitor stdio' is
1172 * assumed if we are in -nographic mode and there is no other
1173 * -monitor option. Only a single stdio device is allowed, so
1174 * this broke the '-serial stdio' option. There is a new flag
1175 * called -nodefaults which gets rid of all this default crud, so
1176 * let's use that to avoid this and any future surprises.
1178 if (qemu_supports (g, "-nodefaults"))
1179 add_cmdline (g, "-nodefaults");
1181 add_cmdline (g, "-nographic");
1182 add_cmdline (g, "-serial");
1183 add_cmdline (g, "stdio");
1185 snprintf (buf, sizeof buf, "%d", g->memsize);
1186 add_cmdline (g, "-m");
1187 add_cmdline (g, buf);
1189 /* Force exit instead of reboot on panic */
1190 add_cmdline (g, "-no-reboot");
1192 /* These options recommended by KVM developers to improve reliability. */
1193 if (qemu_supports (g, "-no-hpet"))
1194 add_cmdline (g, "-no-hpet");
1196 if (qemu_supports (g, "-rtc-td-hack"))
1197 add_cmdline (g, "-rtc-td-hack");
1199 /* If qemu has SLIRP (user mode network) enabled then we can get
1200 * away with "no vmchannel", where we just connect back to a random
1203 if (null_vmchannel_sock) {
1204 add_cmdline (g, "-net");
1205 add_cmdline (g, "user,vlan=0,net=" NETWORK);
1207 snprintf (buf, sizeof buf,
1208 "guestfs_vmchannel=tcp:" ROUTER ":%d",
1209 null_vmchannel_sock);
1210 vmchannel = strdup (buf);
1213 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1215 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1217 * The original suggested format doesn't work, see:
1219 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1221 * However Gerd Hoffman privately suggested to me using -chardev
1222 * instead, which does work.
1224 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1225 snprintf (buf, sizeof buf,
1226 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1228 add_cmdline (g, "-chardev");
1229 add_cmdline (g, buf);
1231 snprintf (buf, sizeof buf,
1232 "user,vlan=0,net=" NETWORK ","
1233 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1234 "-chardev:guestfsvmc");
1236 add_cmdline (g, "-net");
1237 add_cmdline (g, buf);
1239 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1242 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1243 * syntax, or if not then we'll get a quick failure.
1246 snprintf (buf, sizeof buf,
1247 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1249 add_cmdline (g, "-net");
1250 add_cmdline (g, buf);
1251 add_cmdline (g, "-net");
1252 add_cmdline (g, "user,vlan=0,net=" NETWORK);
1254 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1256 add_cmdline (g, "-net");
1257 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1259 #define LINUX_CMDLINE \
1260 "panic=1 " /* force kernel to panic if daemon exits */ \
1261 "console=ttyS0 " /* serial console */ \
1262 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1263 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1264 "acpi=off " /* we don't need ACPI, turn it off */ \
1265 "printk.time=1 " /* display timestamp before kernel messages */ \
1266 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1268 /* Linux kernel command line. */
1269 snprintf (buf, sizeof buf,
1271 "%s " /* (selinux) */
1272 "%s " /* (vmchannel) */
1273 "%s " /* (verbose) */
1274 "TERM=%s " /* (TERM environment variable) */
1275 "%s", /* (append) */
1276 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1277 vmchannel ? vmchannel : "",
1278 g->verbose ? "guestfs_verbose=1" : "",
1279 getenv ("TERM") ? : "linux",
1280 g->append ? g->append : "");
1282 add_cmdline (g, "-kernel");
1283 add_cmdline (g, (char *) kernel);
1284 add_cmdline (g, "-initrd");
1285 add_cmdline (g, (char *) initrd);
1286 add_cmdline (g, "-append");
1287 add_cmdline (g, buf);
1289 /* Finish off the command line. */
1290 incr_cmdline_size (g);
1291 g->cmdline[g->cmdline_size-1] = NULL;
1297 /* Set up stdin, stdout. */
1303 if (dup (wfd[0]) == -1) {
1305 perror ("dup failed");
1306 _exit (EXIT_FAILURE);
1308 if (dup (rfd[1]) == -1)
1316 /* Set up a new process group, so we can signal this process
1317 * and all subprocesses (eg. if qemu is really a shell script).
1322 setenv ("LC_ALL", "C", 1);
1324 execv (g->qemu, g->cmdline); /* Run qemu. */
1326 _exit (EXIT_FAILURE);
1329 /* Parent (library). */
1337 /* Fork the recovery process off which will kill qemu if the parent
1338 * process fails to do so (eg. if the parent segfaults).
1340 g->recoverypid = -1;
1341 if (g->recovery_proc) {
1344 pid_t qemu_pid = g->pid;
1345 pid_t parent_pid = getppid ();
1347 /* Writing to argv is hideously complicated and error prone. See:
1348 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1351 /* Loop around waiting for one or both of the other processes to
1352 * disappear. It's fair to say this is very hairy. The PIDs that
1353 * we are looking at might be reused by another process. We are
1354 * effectively polling. Is the cure worse than the disease?
1357 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1358 _exit (EXIT_SUCCESS);
1359 if (kill (parent_pid, 0) == -1) {
1360 /* Parent's gone away, qemu still around, so kill qemu. */
1362 _exit (EXIT_SUCCESS);
1368 /* Don't worry, if the fork failed, this will be -1. The recovery
1369 * process isn't essential.
1375 /* Close the other ends of the pipe. */
1379 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1380 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1381 perrorf (g, "fcntl");
1385 g->fd[0] = wfd[1]; /* stdin of child */
1386 g->fd[1] = rfd[0]; /* stdout of child */
1388 g->fd[0] = open ("/dev/null", O_RDWR);
1389 if (g->fd[0] == -1) {
1390 perrorf (g, "open /dev/null");
1393 g->fd[1] = dup (g->fd[0]);
1394 if (g->fd[1] == -1) {
1401 if (null_vmchannel_sock) {
1405 /* Null vmchannel implementation: We listen on g->sock for a
1406 * connection. The connection could come from any local process
1407 * so we must check it comes from the appliance (or at least
1408 * from our UID) for security reasons.
1410 while (sock == -1) {
1411 sock = accept_from_daemon (g);
1415 if (check_peer_euid (g, sock, &uid) == -1)
1417 if (uid != geteuid ()) {
1419 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1420 uid, null_vmchannel_sock);
1427 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1428 perrorf (g, "fcntl");
1435 /* Other vmchannel. Open the Unix socket.
1437 * The vmchannel implementation that got merged with qemu sucks in
1438 * a number of ways. Both ends do connect(2), which means that no
1439 * one knows what, if anything, is connected to the other end, or
1440 * if it becomes disconnected. Even worse, we have to wait some
1441 * indeterminate time for qemu to create the socket and connect to
1442 * it (which happens very early in qemu's start-up), so any code
1443 * that uses vmchannel is inherently racy. Hence this silly loop.
1445 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1446 if (g->sock == -1) {
1447 perrorf (g, "socket");
1451 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1452 perrorf (g, "fcntl");
1456 addr.sun_family = AF_UNIX;
1457 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1458 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1461 /* Always sleep at least once to give qemu a small chance to start up. */
1464 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1465 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1468 if (errno != ENOENT)
1469 perrorf (g, "connect");
1474 error (g, _("failed to connect to vmchannel socket"));
1480 g->state = LAUNCHING;
1482 /* Wait for qemu to start and to connect back to us via vmchannel and
1483 * send the GUESTFS_LAUNCH_FLAG message.
1487 r = recv_from_daemon (g, &size, &buf);
1490 if (r == -1) return -1;
1492 if (size != GUESTFS_LAUNCH_FLAG) {
1493 error (g, _("guestfs_launch failed, see earlier error messages"));
1498 print_timestamped_message (g, "appliance is up");
1500 /* This is possible in some really strange situations, such as
1501 * guestfsd starts up OK but then qemu immediately exits. Check for
1502 * it because the caller is probably expecting to be able to send
1503 * commands after this function returns.
1505 if (g->state != READY) {
1506 error (g, _("qemu launched and contacted daemon, but state != READY"));
1517 if (g->pid > 0) kill (g->pid, 9);
1518 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1519 waitpid (g->pid, NULL, 0);
1520 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1525 memset (&g->launch_t, 0, sizeof g->launch_t);
1538 /* This function is used to print the qemu command line before it gets
1539 * executed, when in verbose mode.
1542 print_cmdline (guestfs_h *g)
1547 while (g->cmdline[i]) {
1548 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1549 fprintf (stderr, " \\\n ");
1551 if (i > 0) fputc (' ', stderr);
1553 /* Does it need shell quoting? This only deals with simple cases. */
1554 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1556 if (needs_quote) fputc ('\'', stderr);
1557 fprintf (stderr, "%s", g->cmdline[i]);
1558 if (needs_quote) fputc ('\'', stderr);
1562 fputc ('\n', stderr);
1565 /* This function does the hard work of building the supermin appliance
1566 * on the fly. 'path' is the directory containing the control files.
1567 * 'kernel' and 'initrd' are where we will return the names of the
1568 * kernel and initrd (only initrd is built). The work is done by
1569 * an external script. We just tell it where to put the result.
1572 build_supermin_appliance (guestfs_h *g, const char *path,
1573 char **kernel, char **initrd)
1579 print_timestamped_message (g, "begin building supermin appliance");
1581 len = strlen (g->tmpdir);
1582 *kernel = safe_malloc (g, len + 8);
1583 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1584 *initrd = safe_malloc (g, len + 8);
1585 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1587 snprintf (cmd, sizeof cmd,
1588 "febootstrap-supermin-helper%s "
1589 "-k '%s/kmod.whitelist' "
1593 g->verbose ? " --verbose" : "",
1598 print_timestamped_message (g, "%s", cmd);
1601 if (r == -1 || WEXITSTATUS(r) != 0) {
1602 error (g, _("external command failed: %s"), cmd);
1605 *kernel = *initrd = NULL;
1610 print_timestamped_message (g, "finished building supermin appliance");
1615 /* Compute Y - X and return the result in milliseconds.
1616 * Approximately the same as this code:
1617 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1620 timeval_diff (const struct timeval *x, const struct timeval *y)
1624 msec = (y->tv_sec - x->tv_sec) * 1000;
1625 msec += (y->tv_usec - x->tv_usec) / 1000;
1630 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1637 va_start (args, fs);
1638 err = vasprintf (&msg, fs, args);
1641 if (err < 0) return;
1643 gettimeofday (&tv, NULL);
1645 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1646 timeval_diff (&g->launch_t, &tv), msg);
1651 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1653 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1654 * 'qemu -version' so we know what options this qemu supports and
1658 test_qemu (guestfs_h *g)
1663 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1665 fp = popen (cmd, "r");
1666 /* qemu -help should always work (qemu -version OTOH wasn't
1667 * supported by qemu 0.9). If this command doesn't work then it
1668 * probably indicates that the qemu binary is missing.
1671 /* XXX This error is never printed, even if the qemu binary
1672 * doesn't exist. Why?
1675 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1679 if (read_all (g, fp, &g->qemu_help) == -1)
1682 if (pclose (fp) == -1)
1685 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1688 fp = popen (cmd, "r");
1690 /* Intentionally ignore errors. */
1691 read_all (g, fp, &g->qemu_version);
1699 read_all (guestfs_h *g, FILE *fp, char **ret)
1706 *ret = safe_realloc (g, *ret, n + 1);
1711 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1713 r = fread (p, 1, BUFSIZ, fp);
1715 perrorf (g, "read");
1722 /* Test if option is supported by qemu command line (just by grepping
1725 * The first time this is used, it has to run the external qemu
1726 * binary. If that fails, it returns -1.
1728 * To just do the first-time run of the qemu binary, call this with
1729 * option == NULL, in which case it will return -1 if there was an
1733 qemu_supports (guestfs_h *g, const char *option)
1735 if (!g->qemu_help) {
1736 if (test_qemu (g) == -1)
1743 return strstr (g->qemu_help, option) != NULL;
1746 /* Check if a file can be opened. */
1748 is_openable (guestfs_h *g, const char *path, int flags)
1750 int fd = open (path, flags);
1760 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1761 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1762 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1765 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1767 #if CAN_CHECK_PEER_EUID
1768 struct sockaddr_in peer;
1769 socklen_t addrlen = sizeof peer;
1771 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1772 perrorf (g, "getpeername");
1776 if (peer.sin_family != AF_INET ||
1777 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1778 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1779 peer.sin_family, inet_ntoa (peer.sin_addr));
1783 struct sockaddr_in our;
1784 addrlen = sizeof our;
1785 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1786 perrorf (g, "getsockname");
1790 FILE *fp = fopen ("/proc/net/tcp", "r");
1792 perrorf (g, "/proc/net/tcp");
1797 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1798 error (g, "unexpected end of file in /proc/net/tcp");
1803 while (fgets (line, sizeof line, fp) != NULL) {
1804 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1805 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1808 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1810 &line_our_addr, &line_our_port,
1811 &line_peer_addr, &line_peer_port,
1812 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1814 /* Note about /proc/net/tcp: local_address and rem_address are
1815 * always in network byte order. However the port part is
1816 * always in host byte order.
1818 * The sockname and peername that we got above are in network
1819 * byte order. So we have to byte swap the port but not the
1822 if (line_our_addr == our.sin_addr.s_addr &&
1823 line_our_port == ntohs (our.sin_port) &&
1824 line_peer_addr == peer.sin_addr.s_addr &&
1825 line_peer_port == ntohs (peer.sin_port)) {
1833 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1836 #else /* !CAN_CHECK_PEER_EUID */
1837 /* This function exists but should never be called in this
1841 #endif /* !CAN_CHECK_PEER_EUID */
1844 /* You had to call this function after launch in versions <= 1.0.70,
1845 * but it is now a no-op.
1848 guestfs__wait_ready (guestfs_h *g)
1850 if (g->state != READY) {
1851 error (g, _("qemu has not been launched yet"));
1859 guestfs__kill_subprocess (guestfs_h *g)
1861 if (g->state == CONFIG) {
1862 error (g, _("no subprocess to kill"));
1867 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1869 if (g->pid > 0) kill (g->pid, SIGTERM);
1870 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1875 /* Access current state. */
1877 guestfs__is_config (guestfs_h *g)
1879 return g->state == CONFIG;
1883 guestfs__is_launching (guestfs_h *g)
1885 return g->state == LAUNCHING;
1889 guestfs__is_ready (guestfs_h *g)
1891 return g->state == READY;
1895 guestfs__is_busy (guestfs_h *g)
1897 return g->state == BUSY;
1901 guestfs__get_state (guestfs_h *g)
1907 guestfs_set_log_message_callback (guestfs_h *g,
1908 guestfs_log_message_cb cb, void *opaque)
1910 g->log_message_cb = cb;
1911 g->log_message_cb_data = opaque;
1915 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1916 guestfs_subprocess_quit_cb cb, void *opaque)
1918 g->subprocess_quit_cb = cb;
1919 g->subprocess_quit_cb_data = opaque;
1923 guestfs_set_launch_done_callback (guestfs_h *g,
1924 guestfs_launch_done_cb cb, void *opaque)
1926 g->launch_done_cb = cb;
1927 g->launch_done_cb_data = opaque;
1930 /*----------------------------------------------------------------------*/
1932 /* This is the code used to send and receive RPC messages and (for
1933 * certain types of message) to perform file transfers. This code is
1934 * driven from the generated actions (src/guestfs-actions.c). There
1935 * are five different cases to consider:
1937 * (1) A non-daemon function. There is no RPC involved at all, it's
1938 * all handled inside the library.
1940 * (2) A simple RPC (eg. "mount"). We write the request, then read
1941 * the reply. The sequence of calls is:
1943 * guestfs___set_busy
1946 * guestfs___end_busy
1948 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1949 * request, then write the file(s), then read the reply. The sequence
1952 * guestfs___set_busy
1954 * guestfs___send_file (possibly multiple times)
1956 * guestfs___end_busy
1958 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1959 * request, then read the reply, then read the file(s). The sequence
1962 * guestfs___set_busy
1965 * guestfs___recv_file (possibly multiple times)
1966 * guestfs___end_busy
1968 * (5) Both FileOut and FileIn parameters. There are no calls like
1969 * this in the current API, but they would be implemented as a
1970 * combination of cases (3) and (4).
1972 * During all writes and reads, we also select(2) on qemu stdout
1973 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1974 * anything received is passed up through the log_message_cb. This is
1975 * also the reason why all the sockets are non-blocking. We also have
1976 * to check for EOF (qemu died). All of this is handled by the
1977 * functions send_to_daemon and recv_from_daemon.
1981 guestfs___set_busy (guestfs_h *g)
1983 if (g->state != READY) {
1984 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1993 guestfs___end_busy (guestfs_h *g)
2007 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
2013 /* This is called if we detect EOF, ie. qemu died. */
2015 child_cleanup (guestfs_h *g)
2018 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
2020 /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
2021 if (g->recoverypid > 0) kill (g->recoverypid, 9);
2022 waitpid (g->pid, NULL, 0);
2023 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
2032 memset (&g->launch_t, 0, sizeof g->launch_t);
2034 if (g->subprocess_quit_cb)
2035 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
2039 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
2047 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2051 /* QEMU's console emulates a 16550A serial port. The real 16550A
2052 * device has a small FIFO buffer (16 bytes) which means here we see
2053 * lots of small reads of 1-16 bytes in length, usually single
2056 n = read (fd, buf, sizeof buf);
2058 /* Hopefully this indicates the qemu child process has died. */
2062 /* We weren't expecting eof here (called from launch) so place
2063 * something in the error buffer. RHBZ#588851.
2065 error (g, "child process died unexpectedly");
2071 if (errno == EINTR || errno == EAGAIN)
2074 perrorf (g, "read");
2078 /* In verbose mode, copy all log messages to stderr. */
2080 ignore_value (write (STDERR_FILENO, buf, n));
2082 /* It's an actual log message, send it upwards if anyone is listening. */
2083 if (g->log_message_cb)
2084 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2090 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2099 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2102 n = read (fd, buf, 4);
2104 /* Hopefully this indicates the qemu child process has died. */
2110 if (errno == EINTR || errno == EAGAIN)
2113 perrorf (g, "read");
2117 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2118 xdr_uint32_t (&xdr, &flag);
2121 if (flag != GUESTFS_CANCEL_FLAG) {
2122 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2123 flag, GUESTFS_CANCEL_FLAG);
2130 /* This writes the whole N bytes of BUF to the daemon socket.
2132 * If the whole write is successful, it returns 0.
2133 * If there was an error, it returns -1.
2134 * If the daemon sent a cancellation message, it returns -2.
2136 * It also checks qemu stdout for log messages and passes those up
2137 * through log_message_cb.
2139 * It also checks for EOF (qemu died) and passes that up through the
2140 * child_cleanup function above.
2143 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2145 const char *buf = v_buf;
2151 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2156 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2157 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2158 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2160 int max_fd = MAX (g->sock, g->fd[1]);
2165 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2167 if (errno == EINTR || errno == EAGAIN)
2169 perrorf (g, "select");
2173 if (FD_ISSET (g->fd[1], &rset2)) {
2174 if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
2177 if (FD_ISSET (g->sock, &rset2)) {
2178 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2182 if (FD_ISSET (g->sock, &wset2)) {
2183 r = write (g->sock, buf, n);
2185 if (errno == EINTR || errno == EAGAIN)
2187 perrorf (g, "write");
2188 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2200 /* This reads a single message, file chunk, launch flag or
2201 * cancellation flag from the daemon. If something was read, it
2202 * returns 0, otherwise -1.
2204 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2206 * *size_rtn returns the size of the returned message or it may be
2207 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2209 * *buf_rtn is returned containing the message (if any) or will be set
2210 * to NULL. *buf_rtn must be freed by the caller.
2212 * It also checks qemu stdout for log messages and passes those up
2213 * through log_message_cb.
2215 * It also checks for EOF (qemu died) and passes that up through the
2216 * child_cleanup function above.
2219 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2225 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2226 g, g->state, size_rtn, buf_rtn);
2230 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2231 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2233 int max_fd = MAX (g->sock, g->fd[1]);
2239 /* nr is the size of the message, but we prime it as -4 because we
2240 * have to read the message length word first.
2244 while (nr < (ssize_t) *size_rtn) {
2246 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2248 if (errno == EINTR || errno == EAGAIN)
2250 perrorf (g, "select");
2256 if (FD_ISSET (g->fd[1], &rset2)) {
2257 if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
2263 if (FD_ISSET (g->sock, &rset2)) {
2264 if (nr < 0) { /* Have we read the message length word yet? */
2265 r = read (g->sock, lenbuf+nr+4, -nr);
2267 if (errno == EINTR || errno == EAGAIN)
2270 perrorf (g, "read");
2271 /* Under some circumstances we see "Connection reset by peer"
2272 * here when the child dies suddenly. Catch this and call
2273 * the cleanup function, same as for EOF.
2275 if (err == ECONNRESET)
2280 error (g, _("unexpected end of file when reading from daemon"));
2286 if (nr < 0) /* Still not got the whole length word. */
2290 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2291 xdr_uint32_t (&xdr, size_rtn);
2294 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2295 if (g->state != LAUNCHING)
2296 error (g, _("received magic signature from guestfsd, but in state %d"),
2300 if (g->launch_done_cb)
2301 g->launch_done_cb (g, g->launch_done_cb_data);
2305 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2307 /* If this happens, it's pretty bad and we've probably lost
2310 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2311 error (g, _("message length (%u) > maximum possible size (%d)"),
2312 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2316 /* Allocate the complete buffer, size now known. */
2317 *buf_rtn = safe_malloc (g, *size_rtn);
2321 size_t sizetoread = *size_rtn - nr;
2322 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2324 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2326 if (errno == EINTR || errno == EAGAIN)
2328 perrorf (g, "read");
2334 error (g, _("unexpected end of file when reading from daemon"));
2344 /* Got the full message, caller can start processing it. */
2345 #ifdef ENABLE_PACKET_DUMP
2349 for (i = 0; i < nr; i += 16) {
2350 printf ("%04zx: ", i);
2351 for (j = i; j < MIN (i+16, nr); ++j)
2352 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2353 for (; j < i+16; ++j)
2356 for (j = i; j < MIN (i+16, nr); ++j)
2357 if (c_isprint ((*(char **)buf_rtn)[j]))
2358 printf ("%c", (*(char **)buf_rtn)[j]);
2361 for (; j < i+16; ++j)
2371 /* This is very much like recv_from_daemon above, but g->sock is
2372 * a listening socket and we are accepting a new connection on
2373 * that socket instead of reading anything. Returns the newly
2377 accept_from_daemon (guestfs_h *g)
2383 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2387 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2388 FD_SET (g->sock, &rset); /* Read socket for accept. */
2390 int max_fd = MAX (g->sock, g->fd[1]);
2393 while (sock == -1) {
2394 /* If the qemu process has died, clean up the zombie (RHBZ#579155).
2395 * By partially polling in the select below we ensure that this
2396 * function will be called eventually.
2398 waitpid (g->pid, NULL, WNOHANG);
2402 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
2403 int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
2405 if (errno == EINTR || errno == EAGAIN)
2407 perrorf (g, "select");
2411 if (FD_ISSET (g->fd[1], &rset2)) {
2412 if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
2415 if (FD_ISSET (g->sock, &rset2)) {
2416 sock = accept (g->sock, NULL, NULL);
2418 if (errno == EINTR || errno == EAGAIN)
2420 perrorf (g, "accept");
2430 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2432 struct guestfs_message_header hdr;
2435 int serial = g->msg_next_serial++;
2438 size_t msg_out_size;
2440 if (g->state != BUSY) {
2441 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2445 /* We have to allocate this message buffer on the heap because
2446 * it is quite large (although will be mostly unused). We
2447 * can't allocate it on the stack because in some environments
2448 * we have quite limited stack space available, notably when
2449 * running in the JVM.
2451 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2452 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2454 /* Serialize the header. */
2455 hdr.prog = GUESTFS_PROGRAM;
2456 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2458 hdr.direction = GUESTFS_DIRECTION_CALL;
2459 hdr.serial = serial;
2460 hdr.status = GUESTFS_STATUS_OK;
2462 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2463 error (g, _("xdr_guestfs_message_header failed"));
2467 /* Serialize the args. If any, because some message types
2468 * have no parameters.
2471 if (!(*xdrp) (&xdr, args)) {
2472 error (g, _("dispatch failed to marshal args"));
2477 /* Get the actual length of the message, resize the buffer to match
2478 * the actual length, and write the length word at the beginning.
2480 len = xdr_getpos (&xdr);
2483 msg_out = safe_realloc (g, msg_out, len + 4);
2484 msg_out_size = len + 4;
2486 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2487 xdr_uint32_t (&xdr, &len);
2490 r = send_to_daemon (g, msg_out, msg_out_size);
2491 if (r == -2) /* Ignore stray daemon cancellations. */
2504 static int cancel = 0; /* XXX Implement file cancellation. */
2505 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2506 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2507 static int send_file_cancellation (guestfs_h *g);
2508 static int send_file_complete (guestfs_h *g);
2514 * -2 daemon cancelled (we must read the error message)
2517 guestfs___send_file (guestfs_h *g, const char *filename)
2519 char buf[GUESTFS_MAX_CHUNK_SIZE];
2522 fd = open (filename, O_RDONLY);
2524 perrorf (g, "open: %s", filename);
2525 send_file_cancellation (g);
2526 /* Daemon sees cancellation and won't reply, so caller can
2532 /* Send file in chunked encoding. */
2534 r = read (fd, buf, sizeof buf);
2535 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2538 err = send_file_data (g, buf, r);
2540 if (err == -2) /* daemon sent cancellation */
2541 send_file_cancellation (g);
2546 if (cancel) { /* cancel from either end */
2547 send_file_cancellation (g);
2552 perrorf (g, "read: %s", filename);
2553 send_file_cancellation (g);
2557 /* End of file, but before we send that, we need to close
2558 * the file and check for errors.
2560 if (close (fd) == -1) {
2561 perrorf (g, "close: %s", filename);
2562 send_file_cancellation (g);
2566 return send_file_complete (g);
2569 /* Send a chunk of file data. */
2571 send_file_data (guestfs_h *g, const char *buf, size_t len)
2573 return send_file_chunk (g, 0, buf, len);
2576 /* Send a cancellation message. */
2578 send_file_cancellation (guestfs_h *g)
2580 return send_file_chunk (g, 1, NULL, 0);
2583 /* Send a file complete chunk. */
2585 send_file_complete (guestfs_h *g)
2588 return send_file_chunk (g, 0, buf, 0);
2592 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2596 guestfs_chunk chunk;
2599 size_t msg_out_size;
2601 if (g->state != BUSY) {
2602 error (g, _("send_file_chunk: state %d != READY"), g->state);
2606 /* Allocate the chunk buffer. Don't use the stack to avoid
2607 * excessive stack usage and unnecessary copies.
2609 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2610 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2612 /* Serialize the chunk. */
2613 chunk.cancel = cancel;
2614 chunk.data.data_len = buflen;
2615 chunk.data.data_val = (char *) buf;
2617 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2618 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2624 len = xdr_getpos (&xdr);
2627 /* Reduce the size of the outgoing message buffer to the real length. */
2628 msg_out = safe_realloc (g, msg_out, len + 4);
2629 msg_out_size = len + 4;
2631 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2632 xdr_uint32_t (&xdr, &len);
2634 r = send_to_daemon (g, msg_out, msg_out_size);
2636 /* Did the daemon send a cancellation message? */
2639 fprintf (stderr, "got daemon cancellation\n");
2655 /* Receive a reply. */
2657 guestfs___recv (guestfs_h *g, const char *fn,
2658 guestfs_message_header *hdr,
2659 guestfs_message_error *err,
2660 xdrproc_t xdrp, char *ret)
2668 r = recv_from_daemon (g, &size, &buf);
2672 /* This can happen if a cancellation happens right at the end
2673 * of us sending a FileIn parameter to the daemon. Discard. The
2674 * daemon should send us an error message next.
2676 if (size == GUESTFS_CANCEL_FLAG)
2679 if (size == GUESTFS_LAUNCH_FLAG) {
2680 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2684 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2686 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2687 error (g, "%s: failed to parse reply header", fn);
2692 if (hdr->status == GUESTFS_STATUS_ERROR) {
2693 if (!xdr_guestfs_message_error (&xdr, err)) {
2694 error (g, "%s: failed to parse reply error", fn);
2700 if (xdrp && ret && !xdrp (&xdr, ret)) {
2701 error (g, "%s: failed to parse reply", fn);
2713 /* Receive a file. */
2715 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2716 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2719 guestfs___recv_file (guestfs_h *g, const char *filename)
2724 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2726 perrorf (g, "open: %s", filename);
2730 /* Receive the file in chunked encoding. */
2731 while ((r = receive_file_data (g, &buf)) > 0) {
2732 if (xwrite (fd, buf, r) == -1) {
2733 perrorf (g, "%s: write", filename);
2741 error (g, _("%s: error in chunked encoding"), filename);
2745 if (close (fd) == -1) {
2746 perrorf (g, "close: %s", filename);
2753 /* Send cancellation message to daemon, then wait until it
2754 * cancels (just throwing away data).
2758 uint32_t flag = GUESTFS_CANCEL_FLAG;
2761 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2764 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2765 xdr_uint32_t (&xdr, &flag);
2768 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2769 perrorf (g, _("write to daemon socket"));
2773 while (receive_file_data (g, NULL) > 0)
2774 ; /* just discard it */
2779 /* Receive a chunk of file data. */
2780 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2782 receive_file_data (guestfs_h *g, void **buf_r)
2788 guestfs_chunk chunk;
2790 r = recv_from_daemon (g, &len, &buf);
2792 error (g, _("receive_file_data: parse error in reply callback"));
2796 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2797 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2801 memset (&chunk, 0, sizeof chunk);
2803 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2804 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2805 error (g, _("failed to parse file chunk"));
2810 /* After decoding, the original buffer is no longer used. */
2814 error (g, _("file receive cancelled by daemon"));
2815 free (chunk.data.data_val);
2819 if (chunk.data.data_len == 0) { /* end of transfer */
2820 free (chunk.data.data_val);
2824 if (buf_r) *buf_r = chunk.data.data_val;
2825 else free (chunk.data.data_val); /* else caller frees */
2827 return chunk.data.data_len;