protocol: Send progress_hint in header.
[libguestfs.git] / src / proto.c
1 /* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #include <sys/select.h>
35 #include <dirent.h>
36 #include <signal.h>
37
38 #include <rpc/types.h>
39 #include <rpc/xdr.h>
40
41 #ifdef HAVE_ERRNO_H
42 #include <errno.h>
43 #endif
44
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
47 #endif
48
49 #ifdef HAVE_SYS_WAIT_H
50 #include <sys/wait.h>
51 #endif
52
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
55 #endif
56
57 #ifdef HAVE_SYS_UN_H
58 #include <sys/un.h>
59 #endif
60
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
63
64 #include "c-ctype.h"
65 #include "glthread/lock.h"
66 #include "ignore-value.h"
67
68 #include "guestfs.h"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
72
73 /* This is the code used to send and receive RPC messages and (for
74  * certain types of message) to perform file transfers.  This code is
75  * driven from the generated actions (src/actions.c).  There
76  * are five different cases to consider:
77  *
78  * (1) A non-daemon function.  There is no RPC involved at all, it's
79  * all handled inside the library.
80  *
81  * (2) A simple RPC (eg. "mount").  We write the request, then read
82  * the reply.  The sequence of calls is:
83  *
84  *   guestfs___set_busy
85  *   guestfs___send
86  *   guestfs___recv
87  *   guestfs___end_busy
88  *
89  * (3) An RPC with FileOut parameters (eg. "upload").  We write the
90  * request, then write the file(s), then read the reply.  The sequence
91  * of calls is:
92  *
93  *   guestfs___set_busy
94  *   guestfs___send
95  *   guestfs___send_file  (possibly multiple times)
96  *   guestfs___recv
97  *   guestfs___end_busy
98  *
99  * (4) An RPC with FileIn parameters (eg. "download").  We write the
100  * request, then read the reply, then read the file(s).  The sequence
101  * of calls is:
102  *
103  *   guestfs___set_busy
104  *   guestfs___send
105  *   guestfs___recv
106  *   guestfs___recv_file  (possibly multiple times)
107  *   guestfs___end_busy
108  *
109  * (5) Both FileOut and FileIn parameters.  There are no calls like
110  * this in the current API, but they would be implemented as a
111  * combination of cases (3) and (4).
112  *
113  * During all writes and reads, we also select(2) on qemu stdout
114  * looking for messages (guestfsd stderr and guest kernel dmesg), and
115  * anything received is passed up through the log_message_cb.  This is
116  * also the reason why all the sockets are non-blocking.  We also have
117  * to check for EOF (qemu died).  All of this is handled by the
118  * functions send_to_daemon and recv_from_daemon.
119  */
120
121 static int
122 xwrite (int fd, const void *v_buf, size_t len)
123 {
124   const char *buf = v_buf;
125   int r;
126
127   while (len > 0) {
128     r = write (fd, buf, len);
129     if (r == -1)
130       return -1;
131
132     buf += r;
133     len -= r;
134   }
135
136   return 0;
137 }
138
139 int
140 guestfs___set_busy (guestfs_h *g)
141 {
142   if (g->state != READY) {
143     error (g, _("guestfs_set_busy: called when in state %d != READY"),
144            g->state);
145     return -1;
146   }
147   g->state = BUSY;
148   return 0;
149 }
150
151 int
152 guestfs___end_busy (guestfs_h *g)
153 {
154   switch (g->state)
155     {
156     case BUSY:
157       g->state = READY;
158       break;
159     case CONFIG:
160     case READY:
161       break;
162
163     case LAUNCHING:
164     case NO_HANDLE:
165     default:
166       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
167       return -1;
168     }
169   return 0;
170 }
171
172 /* This is called if we detect EOF, ie. qemu died. */
173 static void
174 child_cleanup (guestfs_h *g)
175 {
176   if (g->verbose)
177     fprintf (stderr, "child_cleanup: %p: child process died\n", g);
178
179   /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
180   if (g->recoverypid > 0) kill (g->recoverypid, 9);
181   waitpid (g->pid, NULL, 0);
182   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
183   close (g->fd[0]);
184   close (g->fd[1]);
185   close (g->sock);
186   g->fd[0] = -1;
187   g->fd[1] = -1;
188   g->sock = -1;
189   g->pid = 0;
190   g->recoverypid = 0;
191   memset (&g->launch_t, 0, sizeof g->launch_t);
192   g->state = CONFIG;
193   if (g->subprocess_quit_cb)
194     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
195 }
196
197 static int
198 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
199 {
200   char buf[BUFSIZ];
201   int n;
202
203 #if 0
204   if (g->verbose)
205     fprintf (stderr,
206              "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
207              g, g->state, fd);
208 #endif
209
210   /* QEMU's console emulates a 16550A serial port.  The real 16550A
211    * device has a small FIFO buffer (16 bytes) which means here we see
212    * lots of small reads of 1-16 bytes in length, usually single
213    * bytes.
214    */
215   n = read (fd, buf, sizeof buf);
216   if (n == 0) {
217     /* Hopefully this indicates the qemu child process has died. */
218     child_cleanup (g);
219
220     if (error_if_eof) {
221       /* We weren't expecting eof here (called from launch) so place
222        * something in the error buffer.  RHBZ#588851.
223        */
224       error (g, "child process died unexpectedly");
225     }
226     return -1;
227   }
228
229   if (n == -1) {
230     if (errno == EINTR || errno == EAGAIN)
231       return 0;
232
233     perrorf (g, "read");
234     return -1;
235   }
236
237   /* In verbose mode, copy all log messages to stderr. */
238   if (g->verbose)
239     ignore_value (write (STDERR_FILENO, buf, n));
240
241   /* It's an actual log message, send it upwards if anyone is listening. */
242   if (g->log_message_cb)
243     g->log_message_cb (g, g->log_message_cb_data, buf, n);
244
245   return 0;
246 }
247
248 static int
249 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
250 {
251   char buf[4];
252   int n;
253   uint32_t flag;
254   XDR xdr;
255
256   if (g->verbose)
257     fprintf (stderr,
258              "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
259              g, g->state, fd);
260
261   n = read (fd, buf, 4);
262   if (n == 0) {
263     /* Hopefully this indicates the qemu child process has died. */
264     child_cleanup (g);
265     return -1;
266   }
267
268   if (n == -1) {
269     if (errno == EINTR || errno == EAGAIN)
270       return 0;
271
272     perrorf (g, "read");
273     return -1;
274   }
275
276   xdrmem_create (&xdr, buf, 4, XDR_DECODE);
277   xdr_uint32_t (&xdr, &flag);
278   xdr_destroy (&xdr);
279
280   if (flag != GUESTFS_CANCEL_FLAG) {
281     error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
282            flag, GUESTFS_CANCEL_FLAG);
283     return -1;
284   }
285
286   return -2;
287 }
288
289 /* This writes the whole N bytes of BUF to the daemon socket.
290  *
291  * If the whole write is successful, it returns 0.
292  * If there was an error, it returns -1.
293  * If the daemon sent a cancellation message, it returns -2.
294  *
295  * It also checks qemu stdout for log messages and passes those up
296  * through log_message_cb.
297  *
298  * It also checks for EOF (qemu died) and passes that up through the
299  * child_cleanup function above.
300  */
301 int
302 guestfs___send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
303 {
304   const char *buf = v_buf;
305   fd_set rset, rset2;
306   fd_set wset, wset2;
307
308   if (g->verbose)
309     fprintf (stderr,
310              "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
311
312   FD_ZERO (&rset);
313   FD_ZERO (&wset);
314
315   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
316   FD_SET (g->sock, &rset);      /* Read socket for cancellation & EOF. */
317   FD_SET (g->sock, &wset);      /* Write to socket to send the data. */
318
319   int max_fd = MAX (g->sock, g->fd[1]);
320
321   while (n > 0) {
322     rset2 = rset;
323     wset2 = wset;
324     int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
325     if (r == -1) {
326       if (errno == EINTR || errno == EAGAIN)
327         continue;
328       perrorf (g, "select");
329       return -1;
330     }
331
332     if (FD_ISSET (g->fd[1], &rset2)) {
333       if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
334         return -1;
335     }
336     if (FD_ISSET (g->sock, &rset2)) {
337       r = check_for_daemon_cancellation_or_eof (g, g->sock);
338       if (r < 0)
339         return r;
340     }
341     if (FD_ISSET (g->sock, &wset2)) {
342       r = write (g->sock, buf, n);
343       if (r == -1) {
344         if (errno == EINTR || errno == EAGAIN)
345           continue;
346         perrorf (g, "write");
347         if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
348           child_cleanup (g);
349         return -1;
350       }
351       buf += r;
352       n -= r;
353     }
354   }
355
356   return 0;
357 }
358
359 /* This reads a single message, file chunk, launch flag or
360  * cancellation flag from the daemon.  If something was read, it
361  * returns 0, otherwise -1.
362  *
363  * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
364  *
365  * *size_rtn returns the size of the returned message or it may be
366  * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
367  *
368  * *buf_rtn is returned containing the message (if any) or will be set
369  * to NULL.  *buf_rtn must be freed by the caller.
370  *
371  * It also checks qemu stdout for log messages and passes those up
372  * through log_message_cb.
373  *
374  * It also checks for EOF (qemu died) and passes that up through the
375  * child_cleanup function above.
376  *
377  * Progress notifications are handled transparently by this function.
378  * If the callback exists, it is called.  The caller of this function
379  * will not see GUESTFS_PROGRESS_FLAG.
380  */
381
382 /* Size of guestfs_progress message on the wire. */
383 #define PROGRESS_MESSAGE_SIZE 24
384
385 int
386 guestfs___recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
387 {
388   fd_set rset, rset2;
389
390   if (g->verbose)
391     fprintf (stderr,
392              "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
393              g, g->state, size_rtn, buf_rtn);
394
395   FD_ZERO (&rset);
396
397   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
398   FD_SET (g->sock, &rset);      /* Read socket for data & EOF. */
399
400   int max_fd = MAX (g->sock, g->fd[1]);
401
402   *size_rtn = 0;
403   *buf_rtn = NULL;
404
405   char lenbuf[4];
406   /* nr is the size of the message, but we prime it as -4 because we
407    * have to read the message length word first.
408    */
409   ssize_t nr = -4;
410
411   for (;;) {
412     ssize_t message_size =
413       *size_rtn != GUESTFS_PROGRESS_FLAG ?
414       *size_rtn : PROGRESS_MESSAGE_SIZE;
415     if (nr >= message_size)
416       break;
417
418     rset2 = rset;
419     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
420     if (r == -1) {
421       if (errno == EINTR || errno == EAGAIN)
422         continue;
423       perrorf (g, "select");
424       free (*buf_rtn);
425       *buf_rtn = NULL;
426       return -1;
427     }
428
429     if (FD_ISSET (g->fd[1], &rset2)) {
430       if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
431         free (*buf_rtn);
432         *buf_rtn = NULL;
433         return -1;
434       }
435     }
436     if (FD_ISSET (g->sock, &rset2)) {
437       if (nr < 0) {    /* Have we read the message length word yet? */
438         r = read (g->sock, lenbuf+nr+4, -nr);
439         if (r == -1) {
440           if (errno == EINTR || errno == EAGAIN)
441             continue;
442           int err = errno;
443           perrorf (g, "read");
444           /* Under some circumstances we see "Connection reset by peer"
445            * here when the child dies suddenly.  Catch this and call
446            * the cleanup function, same as for EOF.
447            */
448           if (err == ECONNRESET)
449             child_cleanup (g);
450           return -1;
451         }
452         if (r == 0) {
453           error (g, _("unexpected end of file when reading from daemon"));
454           child_cleanup (g);
455           return -1;
456         }
457         nr += r;
458
459         if (nr < 0)         /* Still not got the whole length word. */
460           continue;
461
462         XDR xdr;
463         xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
464         xdr_uint32_t (&xdr, size_rtn);
465         xdr_destroy (&xdr);
466
467         /* *size_rtn changed, recalculate message_size */
468         message_size =
469           *size_rtn != GUESTFS_PROGRESS_FLAG ?
470           *size_rtn : PROGRESS_MESSAGE_SIZE;
471
472         if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
473           if (g->state != LAUNCHING)
474             error (g, _("received magic signature from guestfsd, but in state %d"),
475                    g->state);
476           else {
477             g->state = READY;
478             if (g->launch_done_cb)
479               g->launch_done_cb (g, g->launch_done_cb_data);
480           }
481           return 0;
482         }
483         else if (*size_rtn == GUESTFS_CANCEL_FLAG)
484           return 0;
485         else if (*size_rtn == GUESTFS_PROGRESS_FLAG)
486           /*FALLTHROUGH*/;
487         /* If this happens, it's pretty bad and we've probably lost
488          * synchronization.
489          */
490         else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
491           error (g, _("message length (%u) > maximum possible size (%d)"),
492                  (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
493           return -1;
494         }
495
496         /* Allocate the complete buffer, size now known. */
497         *buf_rtn = safe_malloc (g, message_size);
498         /*FALLTHROUGH*/
499       }
500
501       size_t sizetoread = message_size - nr;
502       if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
503
504       r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
505       if (r == -1) {
506         if (errno == EINTR || errno == EAGAIN)
507           continue;
508         perrorf (g, "read");
509         free (*buf_rtn);
510         *buf_rtn = NULL;
511         return -1;
512       }
513       if (r == 0) {
514         error (g, _("unexpected end of file when reading from daemon"));
515         child_cleanup (g);
516         free (*buf_rtn);
517         *buf_rtn = NULL;
518         return -1;
519       }
520       nr += r;
521     }
522   }
523
524   /* Got the full message, caller can start processing it. */
525 #ifdef ENABLE_PACKET_DUMP
526   if (g->verbose) {
527     ssize_t i, j;
528
529     for (i = 0; i < nr; i += 16) {
530       printf ("%04zx: ", i);
531       for (j = i; j < MIN (i+16, nr); ++j)
532         printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
533       for (; j < i+16; ++j)
534         printf ("   ");
535       printf ("|");
536       for (j = i; j < MIN (i+16, nr); ++j)
537         if (c_isprint ((*(char **)buf_rtn)[j]))
538           printf ("%c", (*(char **)buf_rtn)[j]);
539         else
540           printf (".");
541       for (; j < i+16; ++j)
542         printf (" ");
543       printf ("|\n");
544     }
545   }
546 #endif
547
548   if (*size_rtn == GUESTFS_PROGRESS_FLAG) {
549     if (g->state == BUSY && g->progress_cb) {
550       guestfs_progress message;
551       XDR xdr;
552       xdrmem_create (&xdr, *buf_rtn, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
553       xdr_guestfs_progress (&xdr, &message);
554       xdr_destroy (&xdr);
555
556       g->progress_cb (g, g->progress_cb_data,
557                       message.proc, message.serial,
558                       message.position, message.total);
559     }
560
561     free (*buf_rtn);
562     *buf_rtn = NULL;
563
564     /* Process next message. */
565     return guestfs___recv_from_daemon (g, size_rtn, buf_rtn);
566   }
567
568   return 0;
569 }
570
571 /* This is very much like recv_from_daemon above, but g->sock is
572  * a listening socket and we are accepting a new connection on
573  * that socket instead of reading anything.  Returns the newly
574  * accepted socket.
575  */
576 int
577 guestfs___accept_from_daemon (guestfs_h *g)
578 {
579   fd_set rset, rset2;
580
581   if (g->verbose)
582     fprintf (stderr,
583              "accept_from_daemon: %p g->state = %d\n", g, g->state);
584
585   FD_ZERO (&rset);
586
587   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
588   FD_SET (g->sock, &rset);      /* Read socket for accept. */
589
590   int max_fd = MAX (g->sock, g->fd[1]);
591   int sock = -1;
592
593   while (sock == -1) {
594     /* If the qemu process has died, clean up the zombie (RHBZ#579155).
595      * By partially polling in the select below we ensure that this
596      * function will be called eventually.
597      */
598     waitpid (g->pid, NULL, WNOHANG);
599
600     rset2 = rset;
601
602     struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
603     int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
604     if (r == -1) {
605       if (errno == EINTR || errno == EAGAIN)
606         continue;
607       perrorf (g, "select");
608       return -1;
609     }
610
611     if (FD_ISSET (g->fd[1], &rset2)) {
612       if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
613         return -1;
614     }
615     if (FD_ISSET (g->sock, &rset2)) {
616       sock = accept (g->sock, NULL, NULL);
617       if (sock == -1) {
618         if (errno == EINTR || errno == EAGAIN)
619           continue;
620         perrorf (g, "accept");
621         return -1;
622       }
623     }
624   }
625
626   return sock;
627 }
628
629 int
630 guestfs___send (guestfs_h *g, int proc_nr, uint64_t progress_hint,
631                 xdrproc_t xdrp, char *args)
632 {
633   struct guestfs_message_header hdr;
634   XDR xdr;
635   u_int32_t len;
636   int serial = g->msg_next_serial++;
637   int r;
638   char *msg_out;
639   size_t msg_out_size;
640
641   if (g->state != BUSY) {
642     error (g, _("guestfs___send: state %d != BUSY"), g->state);
643     return -1;
644   }
645
646   /* We have to allocate this message buffer on the heap because
647    * it is quite large (although will be mostly unused).  We
648    * can't allocate it on the stack because in some environments
649    * we have quite limited stack space available, notably when
650    * running in the JVM.
651    */
652   msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
653   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
654
655   /* Serialize the header. */
656   hdr.prog = GUESTFS_PROGRAM;
657   hdr.vers = GUESTFS_PROTOCOL_VERSION;
658   hdr.proc = proc_nr;
659   hdr.direction = GUESTFS_DIRECTION_CALL;
660   hdr.serial = serial;
661   hdr.status = GUESTFS_STATUS_OK;
662   hdr.progress_hint = progress_hint;
663   hdr.optargs_bitmask = 0;
664
665   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
666     error (g, _("xdr_guestfs_message_header failed"));
667     goto cleanup1;
668   }
669
670   /* Serialize the args.  If any, because some message types
671    * have no parameters.
672    */
673   if (xdrp) {
674     if (!(*xdrp) (&xdr, args)) {
675       error (g, _("dispatch failed to marshal args"));
676       goto cleanup1;
677     }
678   }
679
680   /* Get the actual length of the message, resize the buffer to match
681    * the actual length, and write the length word at the beginning.
682    */
683   len = xdr_getpos (&xdr);
684   xdr_destroy (&xdr);
685
686   msg_out = safe_realloc (g, msg_out, len + 4);
687   msg_out_size = len + 4;
688
689   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
690   xdr_uint32_t (&xdr, &len);
691
692  again:
693   r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
694   if (r == -2)                  /* Ignore stray daemon cancellations. */
695     goto again;
696   if (r == -1)
697     goto cleanup1;
698   free (msg_out);
699
700   return serial;
701
702  cleanup1:
703   free (msg_out);
704   return -1;
705 }
706
707 static int cancel = 0; /* XXX Implement file cancellation. */
708 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
709 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
710 static int send_file_cancellation (guestfs_h *g);
711 static int send_file_complete (guestfs_h *g);
712
713 /* Send a file.
714  * Returns:
715  *   0 OK
716  *   -1 error
717  *   -2 daemon cancelled (we must read the error message)
718  */
719 int
720 guestfs___send_file (guestfs_h *g, const char *filename)
721 {
722   char buf[GUESTFS_MAX_CHUNK_SIZE];
723   int fd, r, err;
724
725   fd = open (filename, O_RDONLY);
726   if (fd == -1) {
727     perrorf (g, "open: %s", filename);
728     send_file_cancellation (g);
729     /* Daemon sees cancellation and won't reply, so caller can
730      * just return here.
731      */
732     return -1;
733   }
734
735   /* Send file in chunked encoding. */
736   while (!cancel) {
737     r = read (fd, buf, sizeof buf);
738     if (r == -1 && (errno == EINTR || errno == EAGAIN))
739       continue;
740     if (r <= 0) break;
741     err = send_file_data (g, buf, r);
742     if (err < 0) {
743       if (err == -2)            /* daemon sent cancellation */
744         send_file_cancellation (g);
745       return err;
746     }
747   }
748
749   if (cancel) {                 /* cancel from either end */
750     send_file_cancellation (g);
751     return -1;
752   }
753
754   if (r == -1) {
755     perrorf (g, "read: %s", filename);
756     send_file_cancellation (g);
757     return -1;
758   }
759
760   /* End of file, but before we send that, we need to close
761    * the file and check for errors.
762    */
763   if (close (fd) == -1) {
764     perrorf (g, "close: %s", filename);
765     send_file_cancellation (g);
766     return -1;
767   }
768
769   return send_file_complete (g);
770 }
771
772 /* Send a chunk of file data. */
773 static int
774 send_file_data (guestfs_h *g, const char *buf, size_t len)
775 {
776   return send_file_chunk (g, 0, buf, len);
777 }
778
779 /* Send a cancellation message. */
780 static int
781 send_file_cancellation (guestfs_h *g)
782 {
783   return send_file_chunk (g, 1, NULL, 0);
784 }
785
786 /* Send a file complete chunk. */
787 static int
788 send_file_complete (guestfs_h *g)
789 {
790   char buf[1];
791   return send_file_chunk (g, 0, buf, 0);
792 }
793
794 static int
795 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
796 {
797   u_int32_t len;
798   int r;
799   guestfs_chunk chunk;
800   XDR xdr;
801   char *msg_out;
802   size_t msg_out_size;
803
804   if (g->state != BUSY) {
805     error (g, _("send_file_chunk: state %d != READY"), g->state);
806     return -1;
807   }
808
809   /* Allocate the chunk buffer.  Don't use the stack to avoid
810    * excessive stack usage and unnecessary copies.
811    */
812   msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
813   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
814
815   /* Serialize the chunk. */
816   chunk.cancel = cancel;
817   chunk.data.data_len = buflen;
818   chunk.data.data_val = (char *) buf;
819
820   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
821     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
822            buf, buflen);
823     xdr_destroy (&xdr);
824     goto cleanup1;
825   }
826
827   len = xdr_getpos (&xdr);
828   xdr_destroy (&xdr);
829
830   /* Reduce the size of the outgoing message buffer to the real length. */
831   msg_out = safe_realloc (g, msg_out, len + 4);
832   msg_out_size = len + 4;
833
834   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
835   xdr_uint32_t (&xdr, &len);
836
837   r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
838
839   /* Did the daemon send a cancellation message? */
840   if (r == -2) {
841     if (g->verbose)
842       fprintf (stderr, "got daemon cancellation\n");
843     return -2;
844   }
845
846   if (r == -1)
847     goto cleanup1;
848
849   free (msg_out);
850
851   return 0;
852
853  cleanup1:
854   free (msg_out);
855   return -1;
856 }
857
858 /* Receive a reply. */
859 int
860 guestfs___recv (guestfs_h *g, const char *fn,
861                 guestfs_message_header *hdr,
862                 guestfs_message_error *err,
863                 xdrproc_t xdrp, char *ret)
864 {
865   XDR xdr;
866   void *buf;
867   uint32_t size;
868   int r;
869
870  again:
871   r = guestfs___recv_from_daemon (g, &size, &buf);
872   if (r == -1)
873     return -1;
874
875   /* This can happen if a cancellation happens right at the end
876    * of us sending a FileIn parameter to the daemon.  Discard.  The
877    * daemon should send us an error message next.
878    */
879   if (size == GUESTFS_CANCEL_FLAG)
880     goto again;
881
882   if (size == GUESTFS_LAUNCH_FLAG) {
883     error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
884     return -1;
885   }
886
887   xdrmem_create (&xdr, buf, size, XDR_DECODE);
888
889   if (!xdr_guestfs_message_header (&xdr, hdr)) {
890     error (g, "%s: failed to parse reply header", fn);
891     xdr_destroy (&xdr);
892     free (buf);
893     return -1;
894   }
895   if (hdr->status == GUESTFS_STATUS_ERROR) {
896     if (!xdr_guestfs_message_error (&xdr, err)) {
897       error (g, "%s: failed to parse reply error", fn);
898       xdr_destroy (&xdr);
899       free (buf);
900       return -1;
901     }
902   } else {
903     if (xdrp && ret && !xdrp (&xdr, ret)) {
904       error (g, "%s: failed to parse reply", fn);
905       xdr_destroy (&xdr);
906       free (buf);
907       return -1;
908     }
909   }
910   xdr_destroy (&xdr);
911   free (buf);
912
913   return 0;
914 }
915
916 /* Receive a file. */
917
918 /* Returns -1 = error, 0 = EOF, > 0 = more data */
919 static ssize_t receive_file_data (guestfs_h *g, void **buf);
920
921 int
922 guestfs___recv_file (guestfs_h *g, const char *filename)
923 {
924   void *buf;
925   int fd, r;
926
927   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
928   if (fd == -1) {
929     perrorf (g, "open: %s", filename);
930     goto cancel;
931   }
932
933   /* Receive the file in chunked encoding. */
934   while ((r = receive_file_data (g, &buf)) > 0) {
935     if (xwrite (fd, buf, r) == -1) {
936       perrorf (g, "%s: write", filename);
937       free (buf);
938       goto cancel;
939     }
940     free (buf);
941   }
942
943   if (r == -1) {
944     error (g, _("%s: error in chunked encoding"), filename);
945     return -1;
946   }
947
948   if (close (fd) == -1) {
949     perrorf (g, "close: %s", filename);
950     return -1;
951   }
952
953   return 0;
954
955  cancel: ;
956   /* Send cancellation message to daemon, then wait until it
957    * cancels (just throwing away data).
958    */
959   XDR xdr;
960   char fbuf[4];
961   uint32_t flag = GUESTFS_CANCEL_FLAG;
962
963   if (g->verbose)
964     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
965              __func__);
966
967   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
968   xdr_uint32_t (&xdr, &flag);
969   xdr_destroy (&xdr);
970
971   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
972     perrorf (g, _("write to daemon socket"));
973     return -1;
974   }
975
976   while (receive_file_data (g, NULL) > 0)
977     ;                           /* just discard it */
978
979   return -1;
980 }
981
982 /* Receive a chunk of file data. */
983 /* Returns -1 = error, 0 = EOF, > 0 = more data */
984 static ssize_t
985 receive_file_data (guestfs_h *g, void **buf_r)
986 {
987   int r;
988   void *buf;
989   uint32_t len;
990   XDR xdr;
991   guestfs_chunk chunk;
992
993   r = guestfs___recv_from_daemon (g, &len, &buf);
994   if (r == -1) {
995     error (g, _("receive_file_data: parse error in reply callback"));
996     return -1;
997   }
998
999   if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
1000     error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
1001     return -1;
1002   }
1003
1004   memset (&chunk, 0, sizeof chunk);
1005
1006   xdrmem_create (&xdr, buf, len, XDR_DECODE);
1007   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1008     error (g, _("failed to parse file chunk"));
1009     free (buf);
1010     return -1;
1011   }
1012   xdr_destroy (&xdr);
1013   /* After decoding, the original buffer is no longer used. */
1014   free (buf);
1015
1016   if (chunk.cancel) {
1017     error (g, _("file receive cancelled by daemon"));
1018     free (chunk.data.data_val);
1019     return -1;
1020   }
1021
1022   if (chunk.data.data_len == 0) { /* end of transfer */
1023     free (chunk.data.data_val);
1024     return 0;
1025   }
1026
1027   if (buf_r) *buf_r = chunk.data.data_val;
1028   else free (chunk.data.data_val); /* else caller frees */
1029
1030   return chunk.data.data_len;
1031 }