+/* Returns -1 = error, 0 = EOF, 1 = more data */
+static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
+
+int
+guestfs__receive_file_sync (guestfs_h *g, const char *filename)
+{
+ void *buf;
+ int fd, r;
+ size_t len;
+
+ fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
+ if (fd == -1) {
+ perrorf (g, "open: %s", filename);
+ goto cancel;
+ }
+
+ /* Receive the file in chunked encoding. */
+ while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
+ if (xwrite (fd, buf, len) == -1) {
+ perrorf (g, "%s: write", filename);
+ free (buf);
+ goto cancel;
+ }
+ free (buf);
+ if (r == 0) break; /* End of file. */
+ }
+
+ if (r == -1) {
+ error (g, _("%s: error in chunked encoding"), filename);
+ return -1;
+ }
+
+ if (close (fd) == -1) {
+ perrorf (g, "close: %s", filename);
+ return -1;
+ }
+
+ return 0;
+
+ cancel: ;
+ /* Send cancellation message to daemon, then wait until it
+ * cancels (just throwing away data).
+ */
+ XDR xdr;
+ char fbuf[4];
+ uint32_t flag = GUESTFS_CANCEL_FLAG;
+
+ xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
+ xdr_uint32_t (&xdr, &flag);
+ xdr_destroy (&xdr);
+
+ if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
+ perrorf (g, _("write to daemon socket"));
+ return -1;
+ }
+
+ while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
+ ; /* just discard it */
+
+ return -1;
+}
+
+/* Note that the reply callback can be called multiple times before
+ * the main loop quits and we get back to the synchronous code. So
+ * we have to be prepared to save multiple chunks on a list here.
+ */
+struct receive_file_ctx {
+ int count; /* 0 if receive_file_cb not called, or
+ * else count number of chunks.
+ */
+ guestfs_chunk *chunks; /* Array of chunks. */