2 * Copyright (C) 2009-2011 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"
73 /* Size of guestfs_progress message on the wire. */
74 #define PROGRESS_MESSAGE_SIZE 24
76 /* This is the code used to send and receive RPC messages and (for
77 * certain types of message) to perform file transfers. This code is
78 * driven from the generated actions (src/actions.c). There
79 * are five different cases to consider:
81 * (1) A non-daemon function. There is no RPC involved at all, it's
82 * all handled inside the library.
84 * (2) A simple RPC (eg. "mount"). We write the request, then read
85 * the reply. The sequence of calls is:
92 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
93 * request, then write the file(s), then read the reply. The sequence
98 * guestfs___send_file (possibly multiple times)
102 * (4) An RPC with FileIn parameters (eg. "download"). We write the
103 * request, then read the reply, then read the file(s). The sequence
109 * guestfs___recv_file (possibly multiple times)
112 * (5) Both FileOut and FileIn parameters. There are no calls like
113 * this in the current API, but they would be implemented as a
114 * combination of cases (3) and (4).
116 * During all writes and reads, we also select(2) on qemu stdout
117 * looking for messages (guestfsd stderr and guest kernel dmesg), and
118 * anything received is passed up through the log_message_cb. This is
119 * also the reason why all the sockets are non-blocking. We also have
120 * to check for EOF (qemu died). All of this is handled by the
121 * functions send_to_daemon and recv_from_daemon.
124 /* This is only used on the debug path, to generate a one-line
125 * printable summary of a protocol message. 'workspace' is scratch
126 * space used to format the message, and it must be at least
127 * MAX_MESSAGE_SUMMARY bytes in size.
129 #define MAX_MESSAGE_SUMMARY 200 /* >= 5 * (4 * 3 + 2) + a few bytes overhead */
132 xwrite (int fd, const void *v_buf, size_t len)
134 const char *buf = v_buf;
138 r = write (fd, buf, len);
150 message_summary (const void *buf, size_t n, char *workspace)
152 const unsigned char *cbuf = buf;
157 /* Print only up to 5 x 32 bits of the message. That is enough to
158 * cover the message length, and the first four fields of the
159 * message header (prog, vers, proc, direction).
167 sprintf (p, "%02x ", cbuf[i]);
185 guestfs___set_busy (guestfs_h *g)
187 if (g->state != READY) {
188 error (g, _("guestfs_set_busy: called when in state %d != READY"),
197 guestfs___end_busy (guestfs_h *g)
211 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
217 /* This is called if we detect EOF, ie. qemu died. */
219 child_cleanup (guestfs_h *g)
221 debug (g, "child_cleanup: %p: child process died", g);
223 /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
224 if (g->recoverypid > 0) kill (g->recoverypid, 9);
225 waitpid (g->pid, NULL, 0);
226 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
227 if (g->fd[0] >= 0) close (g->fd[0]);
228 if (g->fd[1] >= 0) close (g->fd[1]);
235 memset (&g->launch_t, 0, sizeof g->launch_t);
237 guestfs___call_callbacks_void (g, GUESTFS_EVENT_SUBPROCESS_QUIT);
241 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
247 debug (g, "read_log_message_or_eof: %p g->state = %d, fd = %d",
251 /* QEMU's console emulates a 16550A serial port. The real 16550A
252 * device has a small FIFO buffer (16 bytes) which means here we see
253 * lots of small reads of 1-16 bytes in length, usually single
254 * bytes. Sleeping here for a very brief period groups reads
255 * together (so we usually get a few lines of output at once) and
256 * improves overall throughput, as well as making the event
257 * interface a bit more sane for callers. With a virtio-serial
258 * based console (not yet implemented) we may be able to remove
263 n = read (fd, buf, sizeof buf);
265 /* Hopefully this indicates the qemu child process has died. */
269 /* We weren't expecting eof here (called from launch) so place
270 * something in the error buffer. RHBZ#588851.
272 error (g, "child process died unexpectedly");
278 if (errno == EINTR || errno == EAGAIN)
285 /* It's an actual log message, send it upwards if anyone is listening. */
286 guestfs___call_callbacks_message (g, GUESTFS_EVENT_APPLIANCE, buf, n);
288 /* This is a gross hack. See the comment above
289 * guestfs___launch_send_progress.
291 if (g->state == LAUNCHING) {
292 const char *sentinel;
295 sentinel = "Linux version"; /* kernel up */
296 len = strlen (sentinel);
297 if (memmem (buf, n, sentinel, len) != NULL)
298 guestfs___launch_send_progress (g, 6);
300 sentinel = "Starting /init script"; /* /init running */
301 len = strlen (sentinel);
302 if (memmem (buf, n, sentinel, len) != NULL)
303 guestfs___launch_send_progress (g, 9);
309 /* Read 'n' bytes, setting the socket to blocking temporarily so
310 * that we really read the number of bytes requested.
311 * Returns: 0 == EOF while reading
312 * -1 == error, error() function has been called
313 * n == read 'n' bytes in full
316 really_read_from_socket (guestfs_h *g, int sock, char *buf, size_t n)
322 /* Set socket to blocking. */
323 flags = fcntl (sock, F_GETFL);
325 perrorf (g, "fcntl");
328 if (fcntl (sock, F_SETFL, flags & ~O_NONBLOCK) == -1) {
329 perrorf (g, "fcntl");
335 r = read (sock, &buf[got], n-got);
345 /* Restore original socket flags. */
346 if (fcntl (sock, F_SETFL, flags) == -1) {
347 perrorf (g, "fcntl");
351 return (ssize_t) got;
354 /* Convenient wrapper to generate a progress message callback. */
356 guestfs___progress_message_callback (guestfs_h *g,
357 const guestfs_progress *message)
361 array[0] = message->proc;
362 array[1] = message->serial;
363 array[2] = message->position;
364 array[3] = message->total;
366 guestfs___call_callbacks_array (g, GUESTFS_EVENT_PROGRESS,
367 array, sizeof array / sizeof array[0]);
371 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
373 char summary[MAX_MESSAGE_SUMMARY];
379 n = really_read_from_socket (g, fd, buf, 4);
383 /* Hopefully this indicates the qemu child process has died. */
388 debug (g, "check_for_daemon_cancellation_or_eof: %s",
389 message_summary (buf, 4, summary));
391 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
392 xdr_uint32_t (&xdr, &flag);
395 /* Read and process progress messages that happen during FileIn. */
396 if (flag == GUESTFS_PROGRESS_FLAG) {
397 char buf[PROGRESS_MESSAGE_SIZE];
399 n = really_read_from_socket (g, fd, buf, PROGRESS_MESSAGE_SIZE);
407 if (g->state == BUSY) {
408 guestfs_progress message;
410 xdrmem_create (&xdr, buf, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
411 xdr_guestfs_progress (&xdr, &message);
414 guestfs___progress_message_callback (g, &message);
420 if (flag != GUESTFS_CANCEL_FLAG) {
421 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
422 flag, GUESTFS_CANCEL_FLAG);
429 /* This writes the whole N bytes of BUF to the daemon socket.
431 * If the whole write is successful, it returns 0.
432 * If there was an error, it returns -1.
433 * If the daemon sent a cancellation message, it returns -2.
435 * It also checks qemu stdout for log messages and passes those up
436 * through log_message_cb.
438 * It also checks for EOF (qemu died) and passes that up through the
439 * child_cleanup function above.
442 guestfs___send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
444 const char *buf = v_buf;
447 char summary[MAX_MESSAGE_SUMMARY];
449 debug (g, "send_to_daemon: %zu bytes: %s", n,
450 message_summary (v_buf, n, summary));
455 if (g->fd[1] >= 0) /* Read qemu stdout for log messages & EOF. */
456 FD_SET (g->fd[1], &rset);
457 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
458 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
460 int max_fd = MAX (g->sock, g->fd[1]);
465 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
467 if (errno == EINTR || errno == EAGAIN)
469 perrorf (g, "select");
473 if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
474 if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
477 if (FD_ISSET (g->sock, &rset2)) {
478 r = check_for_daemon_cancellation_or_eof (g, g->sock);
482 /* Daemon sent cancel message. But to maintain
483 * synchronization we must write out the remainder of the
484 * write buffer before we return (RHBZ#576879).
486 if (xwrite (g->sock, buf, n) == -1) {
487 perrorf (g, "write");
490 return -2; /* cancelled */
493 if (FD_ISSET (g->sock, &wset2)) {
494 r = write (g->sock, buf, n);
496 if (errno == EINTR || errno == EAGAIN)
498 perrorf (g, "write");
499 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
511 /* This reads a single message, file chunk, launch flag or
512 * cancellation flag from the daemon. If something was read, it
513 * returns 0, otherwise -1.
515 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
517 * *size_rtn returns the size of the returned message or it may be
518 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
520 * *buf_rtn is returned containing the message (if any) or will be set
521 * to NULL. *buf_rtn must be freed by the caller.
523 * It also checks qemu stdout for log messages and passes those up
524 * through log_message_cb.
526 * It also checks for EOF (qemu died) and passes that up through the
527 * child_cleanup function above.
529 * Progress notifications are handled transparently by this function.
530 * If the callback exists, it is called. The caller of this function
531 * will not see GUESTFS_PROGRESS_FLAG.
535 guestfs___recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
537 char summary[MAX_MESSAGE_SUMMARY];
542 if (g->fd[1] >= 0) /* Read qemu stdout for log messages & EOF. */
543 FD_SET (g->fd[1], &rset);
544 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
546 int max_fd = MAX (g->sock, g->fd[1]);
552 /* nr is the size of the message, but we prime it as -4 because we
553 * have to read the message length word first.
558 ssize_t message_size =
559 *size_rtn != GUESTFS_PROGRESS_FLAG ?
560 *size_rtn : PROGRESS_MESSAGE_SIZE;
561 if (nr >= message_size)
565 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
567 if (errno == EINTR || errno == EAGAIN)
569 perrorf (g, "select");
575 if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
576 if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
582 if (FD_ISSET (g->sock, &rset2)) {
583 if (nr < 0) { /* Have we read the message length word yet? */
584 r = read (g->sock, lenbuf+nr+4, -nr);
586 if (errno == EINTR || errno == EAGAIN)
590 /* Under some circumstances we see "Connection reset by peer"
591 * here when the child dies suddenly. Catch this and call
592 * the cleanup function, same as for EOF.
594 if (err == ECONNRESET)
599 error (g, _("unexpected end of file when reading from daemon"));
605 if (nr < 0) /* Still not got the whole length word. */
609 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
610 xdr_uint32_t (&xdr, size_rtn);
613 /* *size_rtn changed, recalculate message_size */
615 *size_rtn != GUESTFS_PROGRESS_FLAG ?
616 *size_rtn : PROGRESS_MESSAGE_SIZE;
618 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
619 if (g->state != LAUNCHING)
620 error (g, _("received magic signature from guestfsd, but in state %d"),
624 guestfs___call_callbacks_void (g, GUESTFS_EVENT_LAUNCH_DONE);
626 debug (g, "recv_from_daemon: received GUESTFS_LAUNCH_FLAG");
629 else if (*size_rtn == GUESTFS_CANCEL_FLAG) {
630 debug (g, "recv_from_daemon: received GUESTFS_CANCEL_FLAG");
633 else if (*size_rtn == GUESTFS_PROGRESS_FLAG)
635 /* If this happens, it's pretty bad and we've probably lost
638 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
639 error (g, _("message length (%u) > maximum possible size (%d)"),
640 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
644 /* Allocate the complete buffer, size now known. */
645 *buf_rtn = safe_malloc (g, message_size);
649 size_t sizetoread = message_size - nr;
650 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
652 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
654 if (errno == EINTR || errno == EAGAIN)
662 error (g, _("unexpected end of file when reading from daemon"));
672 /* Got the full message, caller can start processing it. */
673 #ifdef ENABLE_PACKET_DUMP
677 for (i = 0; i < nr; i += 16) {
678 printf ("%04zx: ", i);
679 for (j = i; j < MIN (i+16, nr); ++j)
680 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
681 for (; j < i+16; ++j)
684 for (j = i; j < MIN (i+16, nr); ++j)
685 if (c_isprint ((*(char **)buf_rtn)[j]))
686 printf ("%c", (*(char **)buf_rtn)[j]);
689 for (; j < i+16; ++j)
696 if (*size_rtn == GUESTFS_PROGRESS_FLAG) {
697 if (g->state == BUSY) {
698 guestfs_progress message;
700 xdrmem_create (&xdr, *buf_rtn, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
701 xdr_guestfs_progress (&xdr, &message);
704 guestfs___progress_message_callback (g, &message);
710 /* Process next message. */
711 return guestfs___recv_from_daemon (g, size_rtn, buf_rtn);
714 debug (g, "recv_from_daemon: %" PRIu32 " bytes: %s", *size_rtn,
715 message_summary (*buf_rtn, *size_rtn, summary));
720 /* This is very much like recv_from_daemon above, but g->sock is
721 * a listening socket and we are accepting a new connection on
722 * that socket instead of reading anything. Returns the newly
726 guestfs___accept_from_daemon (guestfs_h *g)
730 debug (g, "accept_from_daemon: %p g->state = %d", g, g->state);
734 if (g->fd[1] >= 0) /* Read qemu stdout for log messages & EOF. */
735 FD_SET (g->fd[1], &rset);
736 FD_SET (g->sock, &rset); /* Read socket for accept. */
738 int max_fd = MAX (g->sock, g->fd[1]);
742 /* If the qemu process has died, clean up the zombie (RHBZ#579155).
743 * By partially polling in the select below we ensure that this
744 * function will be called eventually.
746 waitpid (g->pid, NULL, WNOHANG);
750 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
751 int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
753 if (errno == EINTR || errno == EAGAIN)
755 perrorf (g, "select");
759 if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
760 if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
763 if (FD_ISSET (g->sock, &rset2)) {
764 sock = accept (g->sock, NULL, NULL);
766 if (errno == EINTR || errno == EAGAIN)
768 perrorf (g, "accept");
778 guestfs___send (guestfs_h *g, int proc_nr,
779 uint64_t progress_hint, uint64_t optargs_bitmask,
780 xdrproc_t xdrp, char *args)
782 struct guestfs_message_header hdr;
785 int serial = g->msg_next_serial++;
790 if (g->state != BUSY) {
791 error (g, _("guestfs___send: state %d != BUSY"), g->state);
795 /* We have to allocate this message buffer on the heap because
796 * it is quite large (although will be mostly unused). We
797 * can't allocate it on the stack because in some environments
798 * we have quite limited stack space available, notably when
799 * running in the JVM.
801 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
802 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
804 /* Serialize the header. */
805 hdr.prog = GUESTFS_PROGRAM;
806 hdr.vers = GUESTFS_PROTOCOL_VERSION;
808 hdr.direction = GUESTFS_DIRECTION_CALL;
810 hdr.status = GUESTFS_STATUS_OK;
811 hdr.progress_hint = progress_hint;
812 hdr.optargs_bitmask = optargs_bitmask;
814 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
815 error (g, _("xdr_guestfs_message_header failed"));
819 /* Serialize the args. If any, because some message types
820 * have no parameters.
823 if (!(*xdrp) (&xdr, args)) {
824 error (g, _("dispatch failed to marshal args"));
829 /* Get the actual length of the message, resize the buffer to match
830 * the actual length, and write the length word at the beginning.
832 len = xdr_getpos (&xdr);
835 msg_out = safe_realloc (g, msg_out, len + 4);
836 msg_out_size = len + 4;
838 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
839 xdr_uint32_t (&xdr, &len);
842 r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
843 if (r == -2) /* Ignore stray daemon cancellations. */
856 static int cancel = 0; /* XXX Implement file cancellation. */
857 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
858 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
859 static int send_file_cancellation (guestfs_h *g);
860 static int send_file_complete (guestfs_h *g);
866 * -2 daemon cancelled (we must read the error message)
869 guestfs___send_file (guestfs_h *g, const char *filename)
871 char buf[GUESTFS_MAX_CHUNK_SIZE];
874 fd = open (filename, O_RDONLY);
876 perrorf (g, "open: %s", filename);
877 send_file_cancellation (g);
881 /* Send file in chunked encoding. */
883 r = read (fd, buf, sizeof buf);
884 if (r == -1 && (errno == EINTR || errno == EAGAIN))
887 err = send_file_data (g, buf, r);
889 if (err == -2) /* daemon sent cancellation */
890 send_file_cancellation (g);
895 if (cancel) { /* cancel from either end */
896 send_file_cancellation (g);
901 perrorf (g, "read: %s", filename);
902 send_file_cancellation (g);
906 /* End of file, but before we send that, we need to close
907 * the file and check for errors.
909 if (close (fd) == -1) {
910 perrorf (g, "close: %s", filename);
911 send_file_cancellation (g);
915 return send_file_complete (g);
918 /* Send a chunk of file data. */
920 send_file_data (guestfs_h *g, const char *buf, size_t len)
922 return send_file_chunk (g, 0, buf, len);
925 /* Send a cancellation message. */
927 send_file_cancellation (guestfs_h *g)
929 return send_file_chunk (g, 1, NULL, 0);
932 /* Send a file complete chunk. */
934 send_file_complete (guestfs_h *g)
937 return send_file_chunk (g, 0, buf, 0);
941 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
950 if (g->state != BUSY) {
951 error (g, _("send_file_chunk: state %d != READY"), g->state);
955 /* Allocate the chunk buffer. Don't use the stack to avoid
956 * excessive stack usage and unnecessary copies.
958 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
959 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
961 /* Serialize the chunk. */
962 chunk.cancel = cancel;
963 chunk.data.data_len = buflen;
964 chunk.data.data_val = (char *) buf;
966 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
967 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
973 len = xdr_getpos (&xdr);
976 /* Reduce the size of the outgoing message buffer to the real length. */
977 msg_out = safe_realloc (g, msg_out, len + 4);
978 msg_out_size = len + 4;
980 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
981 xdr_uint32_t (&xdr, &len);
983 r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
985 /* Did the daemon send a cancellation message? */
987 debug (g, "got daemon cancellation");
1003 /* Receive a reply. */
1005 guestfs___recv (guestfs_h *g, const char *fn,
1006 guestfs_message_header *hdr,
1007 guestfs_message_error *err,
1008 xdrproc_t xdrp, char *ret)
1016 r = guestfs___recv_from_daemon (g, &size, &buf);
1020 /* This can happen if a cancellation happens right at the end
1021 * of us sending a FileIn parameter to the daemon. Discard. The
1022 * daemon should send us an error message next.
1024 if (size == GUESTFS_CANCEL_FLAG)
1027 if (size == GUESTFS_LAUNCH_FLAG) {
1028 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
1032 xdrmem_create (&xdr, buf, size, XDR_DECODE);
1034 if (!xdr_guestfs_message_header (&xdr, hdr)) {
1035 error (g, "%s: failed to parse reply header", fn);
1040 if (hdr->status == GUESTFS_STATUS_ERROR) {
1041 if (!xdr_guestfs_message_error (&xdr, err)) {
1042 error (g, "%s: failed to parse reply error", fn);
1048 if (xdrp && ret && !xdrp (&xdr, ret)) {
1049 error (g, "%s: failed to parse reply", fn);
1061 /* Same as guestfs___recv, but it discards the reply message. */
1063 guestfs___recv_discard (guestfs_h *g, const char *fn)
1070 r = guestfs___recv_from_daemon (g, &size, &buf);
1074 /* This can happen if a cancellation happens right at the end
1075 * of us sending a FileIn parameter to the daemon. Discard. The
1076 * daemon should send us an error message next.
1078 if (size == GUESTFS_CANCEL_FLAG)
1081 if (size == GUESTFS_LAUNCH_FLAG) {
1082 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
1089 /* Receive a file. */
1091 /* Returns -1 = error, 0 = EOF, > 0 = more data */
1092 static ssize_t receive_file_data (guestfs_h *g, void **buf);
1095 guestfs___recv_file (guestfs_h *g, const char *filename)
1100 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1102 perrorf (g, "open: %s", filename);
1106 /* Receive the file in chunked encoding. */
1107 while ((r = receive_file_data (g, &buf)) > 0) {
1108 if (xwrite (fd, buf, r) == -1) {
1109 perrorf (g, "%s: write", filename);
1117 error (g, _("%s: error in chunked encoding"), filename);
1121 if (close (fd) == -1) {
1122 perrorf (g, "close: %s", filename);
1129 /* Send cancellation message to daemon, then wait until it
1130 * cancels (just throwing away data).
1134 uint32_t flag = GUESTFS_CANCEL_FLAG;
1136 debug (g, "%s: waiting for daemon to acknowledge cancellation",
1139 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1140 xdr_uint32_t (&xdr, &flag);
1143 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1144 perrorf (g, _("write to daemon socket"));
1148 while (receive_file_data (g, NULL) > 0)
1149 ; /* just discard it */
1154 /* Receive a chunk of file data. */
1155 /* Returns -1 = error, 0 = EOF, > 0 = more data */
1157 receive_file_data (guestfs_h *g, void **buf_r)
1163 guestfs_chunk chunk;
1165 r = guestfs___recv_from_daemon (g, &len, &buf);
1167 error (g, _("receive_file_data: parse error in reply callback"));
1171 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
1172 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
1176 memset (&chunk, 0, sizeof chunk);
1178 xdrmem_create (&xdr, buf, len, XDR_DECODE);
1179 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1180 error (g, _("failed to parse file chunk"));
1185 /* After decoding, the original buffer is no longer used. */
1189 error (g, _("file receive cancelled by daemon"));
1190 free (chunk.data.data_val);
1194 if (chunk.data.data_len == 0) { /* end of transfer */
1195 free (chunk.data.data_val);
1199 if (buf_r) *buf_r = chunk.data.data_val;
1200 else free (chunk.data.data_val); /* else caller frees */
1202 return chunk.data.data_len;