2 * Copyright (C) 2009 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
33 #include <sys/select.h>
36 #include <rpc/types.h>
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
47 #ifdef HAVE_SYS_WAIT_H
51 #ifdef HAVE_SYS_SOCKET_H
52 #include <sys/socket.h>
59 #include <arpa/inet.h>
60 #include <netinet/in.h>
63 #include "guestfs-internal-actions.h"
64 #include "guestfs_protocol.h"
65 #include "ignore-value.h"
69 #define _(str) dgettext(PACKAGE, (str))
70 //#define N_(str) dgettext(PACKAGE, (str))
76 #define error guestfs_error
77 #define perrorf guestfs_perrorf
78 #define safe_malloc guestfs_safe_malloc
79 #define safe_realloc guestfs_safe_realloc
80 #define safe_strdup guestfs_safe_strdup
81 //#define safe_memdup guestfs_safe_memdup
83 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
84 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
85 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
86 static int accept_from_daemon (guestfs_h *g);
87 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
88 static void close_handles (void);
90 #define UNIX_PATH_MAX 108
92 /* Also in guestfsd.c */
93 #define GUESTFWD_ADDR "10.0.2.4"
94 #define GUESTFWD_PORT "6666"
96 /* GuestFS handle and connection. */
97 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
101 struct guestfs_h *next; /* Linked list of open handles. */
103 /* State: see the state machine diagram in the man page guestfs(3). */
106 int fd[2]; /* Stdin/stdout of qemu. */
107 int sock; /* Daemon communications socket. */
108 pid_t pid; /* Qemu PID. */
109 pid_t recoverypid; /* Recovery process PID. */
110 time_t start_t; /* The time when we started qemu. */
112 char *tmpdir; /* Temporary directory containing socket. */
114 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
116 char **cmdline; /* Qemu command line. */
123 char *path; /* Path to kernel, initrd. */
124 char *qemu; /* Qemu binary. */
125 char *append; /* Append to kernel command line. */
127 int memsize; /* Size of RAM (megabytes). */
129 int selinux; /* selinux enabled? */
134 guestfs_abort_cb abort_cb;
135 guestfs_error_handler_cb error_cb;
136 void * error_cb_data;
137 guestfs_log_message_cb log_message_cb;
138 void * log_message_cb_data;
139 guestfs_subprocess_quit_cb subprocess_quit_cb;
140 void * subprocess_quit_cb_data;
141 guestfs_launch_done_cb launch_done_cb;
142 void * launch_done_cb_data;
147 static guestfs_h *handles = NULL;
148 static int atexit_handler_set = 0;
151 guestfs_create (void)
156 g = malloc (sizeof (*g));
159 memset (g, 0, sizeof (*g));
168 g->error_cb = default_error_cb;
169 g->error_cb_data = NULL;
171 str = getenv ("LIBGUESTFS_DEBUG");
172 g->verbose = str != NULL && strcmp (str, "1") == 0;
174 str = getenv ("LIBGUESTFS_TRACE");
175 g->trace = str != NULL && strcmp (str, "1") == 0;
177 str = getenv ("LIBGUESTFS_PATH");
178 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
179 if (!g->path) goto error;
181 str = getenv ("LIBGUESTFS_QEMU");
182 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
183 if (!g->qemu) goto error;
185 str = getenv ("LIBGUESTFS_APPEND");
187 g->append = strdup (str);
188 if (!g->append) goto error;
191 /* Choose a suitable memory size. Previously we tried to choose
192 * a minimal memory size, but this isn't really necessary since
193 * recent QEMU and KVM don't do anything nasty like locking
194 * memory into core any more. Thus we can safely choose a
195 * large, generous amount of memory, and it'll just get swapped
196 * on smaller systems.
198 str = getenv ("LIBGUESTFS_MEMSIZE");
200 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
201 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
207 /* Start with large serial numbers so they are easy to spot
208 * inside the protocol.
210 g->msg_next_serial = 0x00123400;
212 /* Link the handles onto a global list. This is the one area
213 * where the library needs to be made thread-safe. (XXX)
215 /* acquire mutex (XXX) */
218 if (!atexit_handler_set) {
219 atexit (close_handles);
220 atexit_handler_set = 1;
222 /* release mutex (XXX) */
225 fprintf (stderr, "new guestfs handle %p\n", g);
238 guestfs_close (guestfs_h *g)
244 if (g->state == NO_HANDLE) {
245 /* Not safe to call 'error' here, so ... */
246 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
251 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
253 /* Try to sync if autosync flag is set. */
254 if (g->autosync && g->state == READY) {
255 guestfs_umount_all (g);
259 /* Remove any handlers that might be called back before we kill the
262 g->log_message_cb = NULL;
264 if (g->state != CONFIG)
265 guestfs_kill_subprocess (g);
278 /* Wait for subprocess(es) to exit. */
279 waitpid (g->pid, NULL, 0);
280 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
282 /* Remove tmpfiles. */
284 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
287 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
290 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
299 for (i = 0; i < g->cmdline_size; ++i)
300 free (g->cmdline[i]);
304 /* Mark the handle as dead before freeing it. */
305 g->state = NO_HANDLE;
307 /* acquire mutex (XXX) */
311 for (gg = handles; gg->next != g; gg = gg->next)
315 /* release mutex (XXX) */
317 free (g->last_error);
322 free (g->qemu_version);
326 /* Close all open handles (called from atexit(3)). */
330 while (handles) guestfs_close (handles);
334 guestfs_last_error (guestfs_h *g)
336 return g->last_error;
340 set_last_error (guestfs_h *g, const char *msg)
342 free (g->last_error);
343 g->last_error = strdup (msg);
347 default_error_cb (guestfs_h *g, void *data, const char *msg)
349 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
353 guestfs_error (guestfs_h *g, const char *fs, ...)
359 int err = vasprintf (&msg, fs, args);
364 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
365 set_last_error (g, msg);
371 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
378 int err = vasprintf (&msg, fs, args);
385 strerror_r (errnum, buf, sizeof buf);
389 buf = strerror_r (errnum, _buf, sizeof _buf);
392 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
396 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
397 set_last_error (g, msg);
403 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
405 void *ptr = malloc (nbytes);
406 if (nbytes > 0 && !ptr) g->abort_cb ();
410 /* Return 1 if an array of N objects, each of size S, cannot exist due
411 to size arithmetic overflow. S must be positive and N must be
412 nonnegative. This is a macro, not an inline function, so that it
413 works correctly even when SIZE_MAX < N.
415 By gnulib convention, SIZE_MAX represents overflow in size
416 calculations, so the conservative dividend to use here is
417 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
418 However, malloc (SIZE_MAX) fails on all known hosts where
419 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
420 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
421 branch when S is known to be 1. */
422 # define xalloc_oversized(n, s) \
423 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
425 /* Technically we should add an autoconf test for this, testing for the desired
426 functionality, like what's done in gnulib, but for now, this is fine. */
427 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
429 /* Allocate zeroed memory for N elements of S bytes, with error
430 checking. S must be nonzero. */
432 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
434 /* From gnulib's calloc function in xmalloc.c. */
436 /* Test for overflow, since some calloc implementations don't have
437 proper overflow checks. But omit overflow and size-zero tests if
438 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
439 returns NULL if successful. */
440 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
441 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
447 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
449 void *p = realloc (ptr, nbytes);
450 if (nbytes > 0 && !p) g->abort_cb ();
455 guestfs_safe_strdup (guestfs_h *g, const char *str)
457 char *s = strdup (str);
458 if (!s) g->abort_cb ();
463 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
465 void *p = malloc (size);
466 if (!p) g->abort_cb ();
467 memcpy (p, ptr, size);
472 xwrite (int fd, const void *v_buf, size_t len)
474 const char *buf = v_buf;
478 r = write (fd, buf, len);
490 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
496 guestfs_get_out_of_memory_handler (guestfs_h *g)
502 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
505 g->error_cb_data = data;
508 guestfs_error_handler_cb
509 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
511 if (data_rtn) *data_rtn = g->error_cb_data;
516 guestfs__set_verbose (guestfs_h *g, int v)
523 guestfs__get_verbose (guestfs_h *g)
529 guestfs__set_autosync (guestfs_h *g, int a)
536 guestfs__get_autosync (guestfs_h *g)
542 guestfs__set_path (guestfs_h *g, const char *path)
549 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
554 guestfs__get_path (guestfs_h *g)
560 guestfs__set_qemu (guestfs_h *g, const char *qemu)
565 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
570 guestfs__get_qemu (guestfs_h *g)
576 guestfs__set_append (guestfs_h *g, const char *append)
581 g->append = append ? safe_strdup (g, append) : NULL;
586 guestfs__get_append (guestfs_h *g)
592 guestfs__set_memsize (guestfs_h *g, int memsize)
594 g->memsize = memsize;
599 guestfs__get_memsize (guestfs_h *g)
605 guestfs__set_selinux (guestfs_h *g, int selinux)
607 g->selinux = selinux;
612 guestfs__get_selinux (guestfs_h *g)
618 guestfs__get_pid (guestfs_h *g)
623 error (g, "get_pid: no qemu subprocess");
628 struct guestfs_version *
629 guestfs__version (guestfs_h *g)
631 struct guestfs_version *r;
633 r = safe_malloc (g, sizeof *r);
634 r->major = PACKAGE_VERSION_MAJOR;
635 r->minor = PACKAGE_VERSION_MINOR;
636 r->release = PACKAGE_VERSION_RELEASE;
637 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
642 guestfs__set_trace (guestfs_h *g, int t)
649 guestfs__get_trace (guestfs_h *g)
654 /* Add a string to the current command line. */
656 incr_cmdline_size (guestfs_h *g)
658 if (g->cmdline == NULL) {
659 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
661 g->cmdline = safe_malloc (g, sizeof (char *));
662 g->cmdline[0] = NULL;
666 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
670 add_cmdline (guestfs_h *g, const char *str)
672 if (g->state != CONFIG) {
674 _("command line cannot be altered after qemu subprocess launched"));
678 incr_cmdline_size (g);
679 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
684 guestfs__config (guestfs_h *g,
685 const char *qemu_param, const char *qemu_value)
687 if (qemu_param[0] != '-') {
688 error (g, _("guestfs_config: parameter must begin with '-' character"));
692 /* A bit fascist, but the user will probably break the extra
693 * parameters that we add if they try to set any of these.
695 if (strcmp (qemu_param, "-kernel") == 0 ||
696 strcmp (qemu_param, "-initrd") == 0 ||
697 strcmp (qemu_param, "-nographic") == 0 ||
698 strcmp (qemu_param, "-serial") == 0 ||
699 strcmp (qemu_param, "-full-screen") == 0 ||
700 strcmp (qemu_param, "-std-vga") == 0 ||
701 strcmp (qemu_param, "-vnc") == 0) {
702 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
706 if (add_cmdline (g, qemu_param) != 0) return -1;
708 if (qemu_value != NULL) {
709 if (add_cmdline (g, qemu_value) != 0) return -1;
716 guestfs__add_drive (guestfs_h *g, const char *filename)
718 size_t len = strlen (filename) + 64;
721 if (strchr (filename, ',') != NULL) {
722 error (g, _("filename cannot contain ',' (comma) character"));
726 /* cache=off improves reliability in the event of a host crash.
728 * However this option causes qemu to try to open the file with
729 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
730 * So we check if we can open the file with or without O_DIRECT,
731 * and use cache=off (or not) accordingly.
733 * This test also checks for the presence of the file, which
734 * is a documented semantic of this interface.
736 int fd = open (filename, O_RDONLY|O_DIRECT);
739 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
741 fd = open (filename, O_RDONLY);
744 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
746 perrorf (g, "%s", filename);
751 return guestfs__config (g, "-drive", buf);
755 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
757 size_t len = strlen (filename) + 64;
760 if (strchr (filename, ',') != NULL) {
761 error (g, _("filename cannot contain ',' (comma) character"));
765 if (access (filename, F_OK) == -1) {
766 perrorf (g, "%s", filename);
770 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
772 return guestfs__config (g, "-drive", buf);
776 guestfs__add_cdrom (guestfs_h *g, const char *filename)
778 if (strchr (filename, ',') != NULL) {
779 error (g, _("filename cannot contain ',' (comma) character"));
783 if (access (filename, F_OK) == -1) {
784 perrorf (g, "%s", filename);
788 return guestfs__config (g, "-cdrom", filename);
791 /* Returns true iff file is contained in dir. */
793 dir_contains_file (const char *dir, const char *file)
795 int dirlen = strlen (dir);
796 int filelen = strlen (file);
797 int len = dirlen+filelen+2;
800 snprintf (path, len, "%s/%s", dir, file);
801 return access (path, F_OK) == 0;
804 /* Returns true iff every listed file is contained in 'dir'. */
806 dir_contains_files (const char *dir, ...)
811 va_start (args, dir);
812 while ((file = va_arg (args, const char *)) != NULL) {
813 if (!dir_contains_file (dir, file)) {
822 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
823 static int test_qemu (guestfs_h *g);
824 static int qemu_supports (guestfs_h *g, const char *option);
825 static void print_cmdline (guestfs_h *g);
827 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
828 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
829 static const char *supermin_name =
830 "initramfs." REPO "." host_cpu ".supermin.img";
831 static const char *supermin_hostfiles_name =
832 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
835 guestfs__launch (guestfs_h *g)
838 char dir_template[PATH_MAX];
843 char *path, *pelem, *pend;
844 char *kernel = NULL, *initrd = NULL;
845 int null_vmchannel_sock;
847 struct sockaddr_un addr;
855 tmpdir = getenv ("TMPDIR") ? : tmpdir;
856 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
860 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
864 if (g->state != CONFIG) {
865 error (g, _("qemu has already been launched"));
869 /* Make the temporary directory. */
871 g->tmpdir = safe_strdup (g, dir_template);
872 if (mkdtemp (g->tmpdir) == NULL) {
873 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
878 /* First search g->path for the supermin appliance, and try to
879 * synthesize a kernel and initrd from that. If it fails, we
880 * try the path search again looking for a backup ordinary
883 pelem = path = safe_strdup (g, g->path);
885 pend = strchrnul (pelem, ':');
886 pmore = *pend == ':';
890 /* Empty element of "." means cwd. */
891 if (len == 0 || (len == 1 && *pelem == '.')) {
894 "looking for supermin appliance in current directory\n");
895 if (dir_contains_files (".",
896 supermin_name, supermin_hostfiles_name,
897 "kmod.whitelist", NULL)) {
898 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
903 /* Look at <path>/supermin* etc. */
906 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
908 if (dir_contains_files (pelem,
909 supermin_name, supermin_hostfiles_name,
910 "kmod.whitelist", NULL)) {
911 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
922 if (kernel == NULL || initrd == NULL) {
923 /* Search g->path for the kernel and initrd. */
924 pelem = path = safe_strdup (g, g->path);
926 pend = strchrnul (pelem, ':');
927 pmore = *pend == ':';
931 /* Empty element or "." means cwd. */
932 if (len == 0 || (len == 1 && *pelem == '.')) {
935 "looking for appliance in current directory\n");
936 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
937 kernel = safe_strdup (g, kernel_name);
938 initrd = safe_strdup (g, initrd_name);
942 /* Look at <path>/kernel etc. */
945 fprintf (stderr, "looking for appliance in %s\n", pelem);
947 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
948 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
949 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
950 sprintf (kernel, "%s/%s", pelem, kernel_name);
951 sprintf (initrd, "%s/%s", pelem, initrd_name);
962 if (kernel == NULL || initrd == NULL) {
963 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
964 kernel_name, initrd_name, g->path);
968 /* Get qemu help text and version. */
969 if (test_qemu (g) == -1)
972 /* Choose which vmchannel implementation to use. */
973 if (qemu_supports (g, "-net user")) {
974 /* The "null vmchannel" implementation. Requires SLIRP (user mode
975 * networking in qemu) but no other vmchannel support. The daemon
976 * will connect back to a random port number on localhost.
978 struct sockaddr_in addr;
979 socklen_t addrlen = sizeof addr;
981 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
983 perrorf (g, "socket");
986 addr.sin_family = AF_INET;
987 addr.sin_port = htons (0);
988 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
989 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
994 if (listen (g->sock, 256) == -1) {
995 perrorf (g, "listen");
999 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1000 perrorf (g, "getsockname");
1004 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1005 perrorf (g, "fcntl");
1009 null_vmchannel_sock = ntohs (addr.sin_port);
1011 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1013 /* Using some vmchannel impl. We need to create a local Unix
1014 * domain socket for qemu to use.
1016 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1018 null_vmchannel_sock = 0;
1021 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1022 perrorf (g, "pipe");
1028 perrorf (g, "fork");
1036 if (r == 0) { /* Child (qemu). */
1038 const char *vmchannel = NULL;
1040 /* Set up the full command line. Do this in the subprocess so we
1041 * don't need to worry about cleaning up.
1043 g->cmdline[0] = g->qemu;
1045 snprintf (buf, sizeof buf, "%d", g->memsize);
1046 add_cmdline (g, "-m");
1047 add_cmdline (g, buf);
1049 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1050 add_cmdline (g, "-nographic");
1051 add_cmdline (g, "-serial");
1052 add_cmdline (g, "stdio");
1054 /* These options recommended by KVM developers to improve reliability. */
1055 if (qemu_supports (g, "-no-hpet"))
1056 add_cmdline (g, "-no-hpet");
1058 if (qemu_supports (g, "-rtc-td-hack"))
1059 add_cmdline (g, "-rtc-td-hack");
1061 /* If qemu has SLIRP (user mode network) enabled then we can get
1062 * away with "no vmchannel", where we just connect back to a random
1065 if (null_vmchannel_sock) {
1066 add_cmdline (g, "-net");
1067 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1069 snprintf (buf, sizeof buf,
1070 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1071 vmchannel = strdup (buf);
1074 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1076 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1078 * The original suggested format doesn't work, see:
1080 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1082 * However Gerd Hoffman privately suggested to me using -chardev
1083 * instead, which does work.
1085 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1086 snprintf (buf, sizeof buf,
1087 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1089 add_cmdline (g, "-chardev");
1090 add_cmdline (g, buf);
1092 snprintf (buf, sizeof buf,
1093 "user,vlan=0,net=10.0.2.0/8,"
1094 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1095 "-chardev:guestfsvmc");
1097 add_cmdline (g, "-net");
1098 add_cmdline (g, buf);
1100 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1103 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1104 * syntax, or if not then we'll get a quick failure.
1107 snprintf (buf, sizeof buf,
1108 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1110 add_cmdline (g, "-net");
1111 add_cmdline (g, buf);
1112 add_cmdline (g, "-net");
1113 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1115 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1117 add_cmdline (g, "-net");
1118 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1120 #define LINUX_CMDLINE \
1121 "panic=1 " /* force kernel to panic if daemon exits */ \
1122 "console=ttyS0 " /* serial console */ \
1123 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1124 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1125 "acpi=off " /* we don't need ACPI, turn it off */ \
1126 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1128 /* Linux kernel command line. */
1129 snprintf (buf, sizeof buf,
1131 "%s " /* (selinux) */
1132 "%s " /* (vmchannel) */
1133 "%s " /* (verbose) */
1134 "%s", /* (append) */
1135 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1136 vmchannel ? vmchannel : "",
1137 g->verbose ? "guestfs_verbose=1" : "",
1138 g->append ? g->append : "");
1140 add_cmdline (g, "-kernel");
1141 add_cmdline (g, (char *) kernel);
1142 add_cmdline (g, "-initrd");
1143 add_cmdline (g, (char *) initrd);
1144 add_cmdline (g, "-append");
1145 add_cmdline (g, buf);
1147 /* Finish off the command line. */
1148 incr_cmdline_size (g);
1149 g->cmdline[g->cmdline_size-1] = NULL;
1154 /* Set up stdin, stdout. */
1160 if (dup (wfd[0]) == -1) {
1162 perror ("dup failed");
1165 if (dup (rfd[1]) == -1)
1172 /* Set up a new process group, so we can signal this process
1173 * and all subprocesses (eg. if qemu is really a shell script).
1178 execv (g->qemu, g->cmdline); /* Run qemu. */
1183 /* Parent (library). */
1191 /* Fork the recovery process off which will kill qemu if the parent
1192 * process fails to do so (eg. if the parent segfaults).
1196 pid_t qemu_pid = g->pid;
1197 pid_t parent_pid = getppid ();
1199 /* Writing to argv is hideously complicated and error prone. See:
1200 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1203 /* Loop around waiting for one or both of the other processes to
1204 * disappear. It's fair to say this is very hairy. The PIDs that
1205 * we are looking at might be reused by another process. We are
1206 * effectively polling. Is the cure worse than the disease?
1209 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1211 if (kill (parent_pid, 0) == -1) {
1212 /* Parent's gone away, qemu still around, so kill qemu. */
1220 /* Don't worry, if the fork failed, this will be -1. The recovery
1221 * process isn't essential.
1225 /* Start the clock ... */
1228 /* Close the other ends of the pipe. */
1232 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1233 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1234 perrorf (g, "fcntl");
1238 g->fd[0] = wfd[1]; /* stdin of child */
1239 g->fd[1] = rfd[0]; /* stdout of child */
1241 if (null_vmchannel_sock) {
1245 /* Null vmchannel implementation: We listen on g->sock for a
1246 * connection. The connection could come from any local process
1247 * so we must check it comes from the appliance (or at least
1248 * from our UID) for security reasons.
1250 while (sock == -1) {
1251 sock = accept_from_daemon (g);
1255 if (check_peer_euid (g, sock, &uid) == -1)
1257 if (uid != geteuid ()) {
1259 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1260 uid, null_vmchannel_sock);
1266 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1267 perrorf (g, "fcntl");
1274 /* Other vmchannel. Open the Unix socket.
1276 * The vmchannel implementation that got merged with qemu sucks in
1277 * a number of ways. Both ends do connect(2), which means that no
1278 * one knows what, if anything, is connected to the other end, or
1279 * if it becomes disconnected. Even worse, we have to wait some
1280 * indeterminate time for qemu to create the socket and connect to
1281 * it (which happens very early in qemu's start-up), so any code
1282 * that uses vmchannel is inherently racy. Hence this silly loop.
1284 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1285 if (g->sock == -1) {
1286 perrorf (g, "socket");
1290 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1291 perrorf (g, "fcntl");
1295 addr.sun_family = AF_UNIX;
1296 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1297 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1300 /* Always sleep at least once to give qemu a small chance to start up. */
1303 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1304 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1307 if (errno != ENOENT)
1308 perrorf (g, "connect");
1313 error (g, _("failed to connect to vmchannel socket"));
1319 g->state = LAUNCHING;
1321 /* Wait for qemu to start and to connect back to us via vmchannel and
1322 * send the GUESTFS_LAUNCH_FLAG message.
1326 r = recv_from_daemon (g, &size, &buf);
1329 if (r == -1) return -1;
1331 if (size != GUESTFS_LAUNCH_FLAG) {
1332 error (g, _("guestfs_launch failed, see earlier error messages"));
1336 /* This is possible in some really strange situations, such as
1337 * guestfsd starts up OK but then qemu immediately exits. Check for
1338 * it because the caller is probably expecting to be able to send
1339 * commands after this function returns.
1341 if (g->state != READY) {
1342 error (g, _("qemu launched and contacted daemon, but state != READY"));
1352 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1353 waitpid (g->pid, NULL, 0);
1354 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1372 /* This function is used to print the qemu command line before it gets
1373 * executed, when in verbose mode.
1376 print_cmdline (guestfs_h *g)
1381 while (g->cmdline[i]) {
1382 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1383 fprintf (stderr, " \\\n ");
1385 if (i > 0) fputc (' ', stderr);
1387 /* Does it need shell quoting? This only deals with simple cases. */
1388 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1390 if (needs_quote) fputc ('\'', stderr);
1391 fprintf (stderr, "%s", g->cmdline[i]);
1392 if (needs_quote) fputc ('\'', stderr);
1396 fputc ('\n', stderr);
1399 /* This function does the hard work of building the supermin appliance
1400 * on the fly. 'path' is the directory containing the control files.
1401 * 'kernel' and 'initrd' are where we will return the names of the
1402 * kernel and initrd (only initrd is built). The work is done by
1403 * an external script. We just tell it where to put the result.
1406 build_supermin_appliance (guestfs_h *g, const char *path,
1407 char **kernel, char **initrd)
1412 len = strlen (g->tmpdir);
1413 *kernel = safe_malloc (g, len + 8);
1414 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1415 *initrd = safe_malloc (g, len + 8);
1416 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1418 snprintf (cmd, sizeof cmd,
1420 "libguestfs-supermin-helper '%s' %s %s",
1422 path, *kernel, *initrd);
1425 if (r == -1 || WEXITSTATUS(r) != 0) {
1426 error (g, _("external command failed: %s"), cmd);
1429 *kernel = *initrd = NULL;
1436 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1438 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1439 * 'qemu -version' so we know what options this qemu supports and
1443 test_qemu (guestfs_h *g)
1448 free (g->qemu_help);
1449 free (g->qemu_version);
1450 g->qemu_help = NULL;
1451 g->qemu_version = NULL;
1453 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1455 fp = popen (cmd, "r");
1456 /* qemu -help should always work (qemu -version OTOH wasn't
1457 * supported by qemu 0.9). If this command doesn't work then it
1458 * probably indicates that the qemu binary is missing.
1461 /* XXX This error is never printed, even if the qemu binary
1462 * doesn't exist. Why?
1465 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1469 if (read_all (g, fp, &g->qemu_help) == -1)
1472 if (pclose (fp) == -1)
1475 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1477 fp = popen (cmd, "r");
1479 /* Intentionally ignore errors. */
1480 read_all (g, fp, &g->qemu_version);
1488 read_all (guestfs_h *g, FILE *fp, char **ret)
1495 *ret = safe_realloc (g, *ret, n + 1);
1500 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1502 r = fread (p, 1, BUFSIZ, fp);
1504 perrorf (g, "read");
1511 /* Test if option is supported by qemu command line (just by grepping
1515 qemu_supports (guestfs_h *g, const char *option)
1517 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1520 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1521 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1522 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1525 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1527 struct sockaddr_in peer;
1528 socklen_t addrlen = sizeof peer;
1530 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1531 perrorf (g, "getpeername");
1535 if (peer.sin_family != AF_INET ||
1536 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1537 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1538 peer.sin_family, inet_ntoa (peer.sin_addr));
1542 struct sockaddr_in our;
1543 addrlen = sizeof our;
1544 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1545 perrorf (g, "getsockname");
1549 FILE *fp = fopen ("/proc/net/tcp", "r");
1551 perrorf (g, "/proc/net/tcp");
1556 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1557 error (g, "unexpected end of file in /proc/net/tcp");
1562 while (fgets (line, sizeof line, fp) != NULL) {
1563 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1564 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1567 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1569 &line_our_addr, &line_our_port,
1570 &line_peer_addr, &line_peer_port,
1571 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1573 /* Note about /proc/net/tcp: local_address and rem_address are
1574 * always in network byte order. However the port part is
1575 * always in host byte order.
1577 * The sockname and peername that we got above are in network
1578 * byte order. So we have to byte swap the port but not the
1581 if (line_our_addr == our.sin_addr.s_addr &&
1582 line_our_port == ntohs (our.sin_port) &&
1583 line_peer_addr == peer.sin_addr.s_addr &&
1584 line_peer_port == ntohs (peer.sin_port)) {
1592 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1597 /* You had to call this function after launch in versions <= 1.0.70,
1598 * but it is now a no-op.
1601 guestfs__wait_ready (guestfs_h *g)
1603 if (g->state != READY) {
1604 error (g, _("qemu has not been launched yet"));
1612 guestfs__kill_subprocess (guestfs_h *g)
1614 if (g->state == CONFIG) {
1615 error (g, _("no subprocess to kill"));
1620 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1622 kill (g->pid, SIGTERM);
1623 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1628 /* Access current state. */
1630 guestfs__is_config (guestfs_h *g)
1632 return g->state == CONFIG;
1636 guestfs__is_launching (guestfs_h *g)
1638 return g->state == LAUNCHING;
1642 guestfs__is_ready (guestfs_h *g)
1644 return g->state == READY;
1648 guestfs__is_busy (guestfs_h *g)
1650 return g->state == BUSY;
1654 guestfs__get_state (guestfs_h *g)
1660 guestfs_set_log_message_callback (guestfs_h *g,
1661 guestfs_log_message_cb cb, void *opaque)
1663 g->log_message_cb = cb;
1664 g->log_message_cb_data = opaque;
1668 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1669 guestfs_subprocess_quit_cb cb, void *opaque)
1671 g->subprocess_quit_cb = cb;
1672 g->subprocess_quit_cb_data = opaque;
1676 guestfs_set_launch_done_callback (guestfs_h *g,
1677 guestfs_launch_done_cb cb, void *opaque)
1679 g->launch_done_cb = cb;
1680 g->launch_done_cb_data = opaque;
1683 /*----------------------------------------------------------------------*/
1685 /* This is the code used to send and receive RPC messages and (for
1686 * certain types of message) to perform file transfers. This code is
1687 * driven from the generated actions (src/guestfs-actions.c). There
1688 * are five different cases to consider:
1690 * (1) A non-daemon function. There is no RPC involved at all, it's
1691 * all handled inside the library.
1693 * (2) A simple RPC (eg. "mount"). We write the request, then read
1694 * the reply. The sequence of calls is:
1696 * guestfs___set_busy
1699 * guestfs___end_busy
1701 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1702 * request, then write the file(s), then read the reply. The sequence
1705 * guestfs___set_busy
1707 * guestfs___send_file (possibly multiple times)
1709 * guestfs___end_busy
1711 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1712 * request, then read the reply, then read the file(s). The sequence
1715 * guestfs___set_busy
1718 * guestfs___recv_file (possibly multiple times)
1719 * guestfs___end_busy
1721 * (5) Both FileOut and FileIn parameters. There are no calls like
1722 * this in the current API, but they would be implemented as a
1723 * combination of cases (3) and (4).
1725 * During all writes and reads, we also select(2) on qemu stdout
1726 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1727 * anything received is passed up through the log_message_cb. This is
1728 * also the reason why all the sockets are non-blocking. We also have
1729 * to check for EOF (qemu died). All of this is handled by the
1730 * functions send_to_daemon and recv_from_daemon.
1734 guestfs___set_busy (guestfs_h *g)
1736 if (g->state != READY) {
1737 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1746 guestfs___end_busy (guestfs_h *g)
1760 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1766 /* This is called if we detect EOF, ie. qemu died. */
1768 child_cleanup (guestfs_h *g)
1771 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1773 /*kill (g->pid, SIGTERM);*/
1774 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1775 waitpid (g->pid, NULL, 0);
1776 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1787 if (g->subprocess_quit_cb)
1788 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1792 read_log_message_or_eof (guestfs_h *g, int fd)
1800 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1804 /* QEMU's console emulates a 16550A serial port. The real 16550A
1805 * device has a small FIFO buffer (16 bytes) which means here we see
1806 * lots of small reads of 1-16 bytes in length, usually single
1809 n = read (fd, buf, sizeof buf);
1811 /* Hopefully this indicates the qemu child process has died. */
1817 if (errno == EINTR || errno == EAGAIN)
1820 perrorf (g, "read");
1824 /* In verbose mode, copy all log messages to stderr. */
1826 ignore_value (write (STDERR_FILENO, buf, n));
1828 /* It's an actual log message, send it upwards if anyone is listening. */
1829 if (g->log_message_cb)
1830 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1836 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1845 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1848 n = read (fd, buf, 4);
1850 /* Hopefully this indicates the qemu child process has died. */
1856 if (errno == EINTR || errno == EAGAIN)
1859 perrorf (g, "read");
1863 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1864 xdr_uint32_t (&xdr, &flag);
1867 if (flag != GUESTFS_CANCEL_FLAG) {
1868 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1869 flag, GUESTFS_CANCEL_FLAG);
1876 /* This writes the whole N bytes of BUF to the daemon socket.
1878 * If the whole write is successful, it returns 0.
1879 * If there was an error, it returns -1.
1880 * If the daemon sent a cancellation message, it returns -2.
1882 * It also checks qemu stdout for log messages and passes those up
1883 * through log_message_cb.
1885 * It also checks for EOF (qemu died) and passes that up through the
1886 * child_cleanup function above.
1889 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1891 const char *buf = v_buf;
1897 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1902 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1903 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
1904 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
1906 int max_fd = MAX (g->sock, g->fd[1]);
1911 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1913 if (errno == EINTR || errno == EAGAIN)
1915 perrorf (g, "select");
1919 if (FD_ISSET (g->fd[1], &rset2)) {
1920 if (read_log_message_or_eof (g, g->fd[1]) == -1)
1923 if (FD_ISSET (g->sock, &rset2)) {
1924 r = check_for_daemon_cancellation_or_eof (g, g->sock);
1928 if (FD_ISSET (g->sock, &wset2)) {
1929 r = write (g->sock, buf, n);
1931 if (errno == EINTR || errno == EAGAIN)
1933 perrorf (g, "write");
1934 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1946 /* This reads a single message, file chunk, launch flag or
1947 * cancellation flag from the daemon. If something was read, it
1948 * returns 0, otherwise -1.
1950 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
1952 * *size_rtn returns the size of the returned message or it may be
1953 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
1955 * *buf_rtn is returned containing the message (if any) or will be set
1956 * to NULL. *buf_rtn must be freed by the caller.
1958 * It also checks qemu stdout for log messages and passes those up
1959 * through log_message_cb.
1961 * It also checks for EOF (qemu died) and passes that up through the
1962 * child_cleanup function above.
1965 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
1971 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
1972 g, g->state, size_rtn, buf_rtn);
1976 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1977 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
1979 int max_fd = MAX (g->sock, g->fd[1]);
1985 /* nr is the size of the message, but we prime it as -4 because we
1986 * have to read the message length word first.
1990 while (nr < (ssize_t) *size_rtn) {
1992 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
1994 if (errno == EINTR || errno == EAGAIN)
1996 perrorf (g, "select");
2002 if (FD_ISSET (g->fd[1], &rset2)) {
2003 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2009 if (FD_ISSET (g->sock, &rset2)) {
2010 if (nr < 0) { /* Have we read the message length word yet? */
2011 r = read (g->sock, lenbuf+nr+4, -nr);
2013 if (errno == EINTR || errno == EAGAIN)
2016 perrorf (g, "read");
2017 /* Under some circumstances we see "Connection reset by peer"
2018 * here when the child dies suddenly. Catch this and call
2019 * the cleanup function, same as for EOF.
2021 if (err == ECONNRESET)
2026 error (g, _("unexpected end of file when reading from daemon"));
2032 if (nr < 0) /* Still not got the whole length word. */
2036 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2037 xdr_uint32_t (&xdr, size_rtn);
2040 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2041 if (g->state != LAUNCHING)
2042 error (g, _("received magic signature from guestfsd, but in state %d"),
2046 if (g->launch_done_cb)
2047 g->launch_done_cb (g, g->launch_done_cb_data);
2051 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2053 /* If this happens, it's pretty bad and we've probably lost
2056 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2057 error (g, _("message length (%u) > maximum possible size (%d)"),
2058 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2062 /* Allocate the complete buffer, size now known. */
2063 *buf_rtn = safe_malloc (g, *size_rtn);
2067 size_t sizetoread = *size_rtn - nr;
2068 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2070 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2072 if (errno == EINTR || errno == EAGAIN)
2074 perrorf (g, "read");
2080 error (g, _("unexpected end of file when reading from daemon"));
2090 /* Got the full message, caller can start processing it. */
2091 #ifdef ENABLE_PACKET_DUMP
2095 for (i = 0; i < nr; i += 16) {
2096 printf ("%04zx: ", i);
2097 for (j = i; j < MIN (i+16, nr); ++j)
2098 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2099 for (; j < i+16; ++j)
2102 for (j = i; j < MIN (i+16, nr); ++j)
2103 if (isprint ((*(char **)buf_rtn)[j]))
2104 printf ("%c", (*(char **)buf_rtn)[j]);
2107 for (; j < i+16; ++j)
2117 /* This is very much like recv_from_daemon above, but g->sock is
2118 * a listening socket and we are accepting a new connection on
2119 * that socket instead of reading anything. Returns the newly
2123 accept_from_daemon (guestfs_h *g)
2129 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2133 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2134 FD_SET (g->sock, &rset); /* Read socket for accept. */
2136 int max_fd = MAX (g->sock, g->fd[1]);
2139 while (sock == -1) {
2141 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2143 if (errno == EINTR || errno == EAGAIN)
2145 perrorf (g, "select");
2149 if (FD_ISSET (g->fd[1], &rset2)) {
2150 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2153 if (FD_ISSET (g->sock, &rset2)) {
2154 sock = accept (g->sock, NULL, NULL);
2156 if (errno == EINTR || errno == EAGAIN)
2158 perrorf (g, "accept");
2168 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2170 struct guestfs_message_header hdr;
2173 int serial = g->msg_next_serial++;
2176 size_t msg_out_size;
2178 if (g->state != BUSY) {
2179 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2183 /* We have to allocate this message buffer on the heap because
2184 * it is quite large (although will be mostly unused). We
2185 * can't allocate it on the stack because in some environments
2186 * we have quite limited stack space available, notably when
2187 * running in the JVM.
2189 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2190 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2192 /* Serialize the header. */
2193 hdr.prog = GUESTFS_PROGRAM;
2194 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2196 hdr.direction = GUESTFS_DIRECTION_CALL;
2197 hdr.serial = serial;
2198 hdr.status = GUESTFS_STATUS_OK;
2200 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2201 error (g, _("xdr_guestfs_message_header failed"));
2205 /* Serialize the args. If any, because some message types
2206 * have no parameters.
2209 if (!(*xdrp) (&xdr, args)) {
2210 error (g, _("dispatch failed to marshal args"));
2215 /* Get the actual length of the message, resize the buffer to match
2216 * the actual length, and write the length word at the beginning.
2218 len = xdr_getpos (&xdr);
2221 msg_out = safe_realloc (g, msg_out, len + 4);
2222 msg_out_size = len + 4;
2224 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2225 xdr_uint32_t (&xdr, &len);
2228 r = send_to_daemon (g, msg_out, msg_out_size);
2229 if (r == -2) /* Ignore stray daemon cancellations. */
2242 static int cancel = 0; /* XXX Implement file cancellation. */
2243 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2244 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2245 static int send_file_cancellation (guestfs_h *g);
2246 static int send_file_complete (guestfs_h *g);
2252 * -2 daemon cancelled (we must read the error message)
2255 guestfs___send_file (guestfs_h *g, const char *filename)
2257 char buf[GUESTFS_MAX_CHUNK_SIZE];
2260 fd = open (filename, O_RDONLY);
2262 perrorf (g, "open: %s", filename);
2263 send_file_cancellation (g);
2264 /* Daemon sees cancellation and won't reply, so caller can
2270 /* Send file in chunked encoding. */
2272 r = read (fd, buf, sizeof buf);
2273 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2276 err = send_file_data (g, buf, r);
2278 if (err == -2) /* daemon sent cancellation */
2279 send_file_cancellation (g);
2284 if (cancel) { /* cancel from either end */
2285 send_file_cancellation (g);
2290 perrorf (g, "read: %s", filename);
2291 send_file_cancellation (g);
2295 /* End of file, but before we send that, we need to close
2296 * the file and check for errors.
2298 if (close (fd) == -1) {
2299 perrorf (g, "close: %s", filename);
2300 send_file_cancellation (g);
2304 return send_file_complete (g);
2307 /* Send a chunk of file data. */
2309 send_file_data (guestfs_h *g, const char *buf, size_t len)
2311 return send_file_chunk (g, 0, buf, len);
2314 /* Send a cancellation message. */
2316 send_file_cancellation (guestfs_h *g)
2318 return send_file_chunk (g, 1, NULL, 0);
2321 /* Send a file complete chunk. */
2323 send_file_complete (guestfs_h *g)
2326 return send_file_chunk (g, 0, buf, 0);
2330 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2334 guestfs_chunk chunk;
2337 size_t msg_out_size;
2339 if (g->state != BUSY) {
2340 error (g, _("send_file_chunk: state %d != READY"), g->state);
2344 /* Allocate the chunk buffer. Don't use the stack to avoid
2345 * excessive stack usage and unnecessary copies.
2347 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2348 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2350 /* Serialize the chunk. */
2351 chunk.cancel = cancel;
2352 chunk.data.data_len = buflen;
2353 chunk.data.data_val = (char *) buf;
2355 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2356 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2362 len = xdr_getpos (&xdr);
2365 /* Reduce the size of the outgoing message buffer to the real length. */
2366 msg_out = safe_realloc (g, msg_out, len + 4);
2367 msg_out_size = len + 4;
2369 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2370 xdr_uint32_t (&xdr, &len);
2372 r = send_to_daemon (g, msg_out, msg_out_size);
2374 /* Did the daemon send a cancellation message? */
2377 fprintf (stderr, "got daemon cancellation\n");
2393 /* Receive a reply. */
2395 guestfs___recv (guestfs_h *g, const char *fn,
2396 guestfs_message_header *hdr,
2397 guestfs_message_error *err,
2398 xdrproc_t xdrp, char *ret)
2406 r = recv_from_daemon (g, &size, &buf);
2410 /* This can happen if a cancellation happens right at the end
2411 * of us sending a FileIn parameter to the daemon. Discard. The
2412 * daemon should send us an error message next.
2414 if (size == GUESTFS_CANCEL_FLAG)
2417 if (size == GUESTFS_LAUNCH_FLAG) {
2418 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2422 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2424 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2425 error (g, "%s: failed to parse reply header", fn);
2430 if (hdr->status == GUESTFS_STATUS_ERROR) {
2431 if (!xdr_guestfs_message_error (&xdr, err)) {
2432 error (g, "%s: failed to parse reply error", fn);
2438 if (xdrp && ret && !xdrp (&xdr, ret)) {
2439 error (g, "%s: failed to parse reply", fn);
2451 /* Receive a file. */
2453 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2454 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2457 guestfs___recv_file (guestfs_h *g, const char *filename)
2463 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2465 perrorf (g, "open: %s", filename);
2469 /* Receive the file in chunked encoding. */
2470 while ((r = receive_file_data (g, &buf)) > 0) {
2471 if (xwrite (fd, buf, r) == -1) {
2472 perrorf (g, "%s: write", filename);
2480 error (g, _("%s: error in chunked encoding"), filename);
2484 if (close (fd) == -1) {
2485 perrorf (g, "close: %s", filename);
2492 /* Send cancellation message to daemon, then wait until it
2493 * cancels (just throwing away data).
2497 uint32_t flag = GUESTFS_CANCEL_FLAG;
2500 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2503 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2504 xdr_uint32_t (&xdr, &flag);
2507 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2508 perrorf (g, _("write to daemon socket"));
2512 while (receive_file_data (g, NULL) > 0)
2513 ; /* just discard it */
2518 /* Receive a chunk of file data. */
2519 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2521 receive_file_data (guestfs_h *g, void **buf_r)
2527 guestfs_chunk chunk;
2529 r = recv_from_daemon (g, &len, &buf);
2531 error (g, _("receive_file_data: parse error in reply callback"));
2535 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2536 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2540 memset (&chunk, 0, sizeof chunk);
2542 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2543 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2544 error (g, _("failed to parse file chunk"));
2549 /* After decoding, the original buffer is no longer used. */
2553 error (g, _("file receive cancelled by daemon"));
2554 free (chunk.data.data_val);
2558 if (chunk.data.data_len == 0) { /* end of transfer */
2559 free (chunk.data.data_val);
2563 if (buf_r) *buf_r = chunk.data.data_val;
2564 else free (chunk.data.data_val); /* else caller frees */
2566 return chunk.data.data_len;