Factor out code for locating the temporary directory.
[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 int
378 guestfs___recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
379 {
380   fd_set rset, rset2;
381
382   if (g->verbose)
383     fprintf (stderr,
384              "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
385              g, g->state, size_rtn, buf_rtn);
386
387   FD_ZERO (&rset);
388
389   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
390   FD_SET (g->sock, &rset);      /* Read socket for data & EOF. */
391
392   int max_fd = MAX (g->sock, g->fd[1]);
393
394   *size_rtn = 0;
395   *buf_rtn = NULL;
396
397   char lenbuf[4];
398   /* nr is the size of the message, but we prime it as -4 because we
399    * have to read the message length word first.
400    */
401   ssize_t nr = -4;
402
403   while (nr < (ssize_t) *size_rtn) {
404     rset2 = rset;
405     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
406     if (r == -1) {
407       if (errno == EINTR || errno == EAGAIN)
408         continue;
409       perrorf (g, "select");
410       free (*buf_rtn);
411       *buf_rtn = NULL;
412       return -1;
413     }
414
415     if (FD_ISSET (g->fd[1], &rset2)) {
416       if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
417         free (*buf_rtn);
418         *buf_rtn = NULL;
419         return -1;
420       }
421     }
422     if (FD_ISSET (g->sock, &rset2)) {
423       if (nr < 0) {    /* Have we read the message length word yet? */
424         r = read (g->sock, lenbuf+nr+4, -nr);
425         if (r == -1) {
426           if (errno == EINTR || errno == EAGAIN)
427             continue;
428           int err = errno;
429           perrorf (g, "read");
430           /* Under some circumstances we see "Connection reset by peer"
431            * here when the child dies suddenly.  Catch this and call
432            * the cleanup function, same as for EOF.
433            */
434           if (err == ECONNRESET)
435             child_cleanup (g);
436           return -1;
437         }
438         if (r == 0) {
439           error (g, _("unexpected end of file when reading from daemon"));
440           child_cleanup (g);
441           return -1;
442         }
443         nr += r;
444
445         if (nr < 0)         /* Still not got the whole length word. */
446           continue;
447
448         XDR xdr;
449         xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
450         xdr_uint32_t (&xdr, size_rtn);
451         xdr_destroy (&xdr);
452
453         if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
454           if (g->state != LAUNCHING)
455             error (g, _("received magic signature from guestfsd, but in state %d"),
456                    g->state);
457           else {
458             g->state = READY;
459             if (g->launch_done_cb)
460               g->launch_done_cb (g, g->launch_done_cb_data);
461           }
462           return 0;
463         }
464         else if (*size_rtn == GUESTFS_CANCEL_FLAG)
465           return 0;
466         /* If this happens, it's pretty bad and we've probably lost
467          * synchronization.
468          */
469         else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
470           error (g, _("message length (%u) > maximum possible size (%d)"),
471                  (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
472           return -1;
473         }
474
475         /* Allocate the complete buffer, size now known. */
476         *buf_rtn = safe_malloc (g, *size_rtn);
477         /*FALLTHROUGH*/
478       }
479
480       size_t sizetoread = *size_rtn - nr;
481       if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
482
483       r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
484       if (r == -1) {
485         if (errno == EINTR || errno == EAGAIN)
486           continue;
487         perrorf (g, "read");
488         free (*buf_rtn);
489         *buf_rtn = NULL;
490         return -1;
491       }
492       if (r == 0) {
493         error (g, _("unexpected end of file when reading from daemon"));
494         child_cleanup (g);
495         free (*buf_rtn);
496         *buf_rtn = NULL;
497         return -1;
498       }
499       nr += r;
500     }
501   }
502
503   /* Got the full message, caller can start processing it. */
504 #ifdef ENABLE_PACKET_DUMP
505   if (g->verbose) {
506     ssize_t i, j;
507
508     for (i = 0; i < nr; i += 16) {
509       printf ("%04zx: ", i);
510       for (j = i; j < MIN (i+16, nr); ++j)
511         printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
512       for (; j < i+16; ++j)
513         printf ("   ");
514       printf ("|");
515       for (j = i; j < MIN (i+16, nr); ++j)
516         if (c_isprint ((*(char **)buf_rtn)[j]))
517           printf ("%c", (*(char **)buf_rtn)[j]);
518         else
519           printf (".");
520       for (; j < i+16; ++j)
521         printf (" ");
522       printf ("|\n");
523     }
524   }
525 #endif
526
527   return 0;
528 }
529
530 /* This is very much like recv_from_daemon above, but g->sock is
531  * a listening socket and we are accepting a new connection on
532  * that socket instead of reading anything.  Returns the newly
533  * accepted socket.
534  */
535 int
536 guestfs___accept_from_daemon (guestfs_h *g)
537 {
538   fd_set rset, rset2;
539
540   if (g->verbose)
541     fprintf (stderr,
542              "accept_from_daemon: %p g->state = %d\n", g, g->state);
543
544   FD_ZERO (&rset);
545
546   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
547   FD_SET (g->sock, &rset);      /* Read socket for accept. */
548
549   int max_fd = MAX (g->sock, g->fd[1]);
550   int sock = -1;
551
552   while (sock == -1) {
553     /* If the qemu process has died, clean up the zombie (RHBZ#579155).
554      * By partially polling in the select below we ensure that this
555      * function will be called eventually.
556      */
557     waitpid (g->pid, NULL, WNOHANG);
558
559     rset2 = rset;
560
561     struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
562     int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
563     if (r == -1) {
564       if (errno == EINTR || errno == EAGAIN)
565         continue;
566       perrorf (g, "select");
567       return -1;
568     }
569
570     if (FD_ISSET (g->fd[1], &rset2)) {
571       if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
572         return -1;
573     }
574     if (FD_ISSET (g->sock, &rset2)) {
575       sock = accept (g->sock, NULL, NULL);
576       if (sock == -1) {
577         if (errno == EINTR || errno == EAGAIN)
578           continue;
579         perrorf (g, "accept");
580         return -1;
581       }
582     }
583   }
584
585   return sock;
586 }
587
588 int
589 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
590 {
591   struct guestfs_message_header hdr;
592   XDR xdr;
593   u_int32_t len;
594   int serial = g->msg_next_serial++;
595   int r;
596   char *msg_out;
597   size_t msg_out_size;
598
599   if (g->state != BUSY) {
600     error (g, _("guestfs___send: state %d != BUSY"), g->state);
601     return -1;
602   }
603
604   /* We have to allocate this message buffer on the heap because
605    * it is quite large (although will be mostly unused).  We
606    * can't allocate it on the stack because in some environments
607    * we have quite limited stack space available, notably when
608    * running in the JVM.
609    */
610   msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
611   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
612
613   /* Serialize the header. */
614   hdr.prog = GUESTFS_PROGRAM;
615   hdr.vers = GUESTFS_PROTOCOL_VERSION;
616   hdr.proc = proc_nr;
617   hdr.direction = GUESTFS_DIRECTION_CALL;
618   hdr.serial = serial;
619   hdr.status = GUESTFS_STATUS_OK;
620
621   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
622     error (g, _("xdr_guestfs_message_header failed"));
623     goto cleanup1;
624   }
625
626   /* Serialize the args.  If any, because some message types
627    * have no parameters.
628    */
629   if (xdrp) {
630     if (!(*xdrp) (&xdr, args)) {
631       error (g, _("dispatch failed to marshal args"));
632       goto cleanup1;
633     }
634   }
635
636   /* Get the actual length of the message, resize the buffer to match
637    * the actual length, and write the length word at the beginning.
638    */
639   len = xdr_getpos (&xdr);
640   xdr_destroy (&xdr);
641
642   msg_out = safe_realloc (g, msg_out, len + 4);
643   msg_out_size = len + 4;
644
645   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
646   xdr_uint32_t (&xdr, &len);
647
648  again:
649   r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
650   if (r == -2)                  /* Ignore stray daemon cancellations. */
651     goto again;
652   if (r == -1)
653     goto cleanup1;
654   free (msg_out);
655
656   return serial;
657
658  cleanup1:
659   free (msg_out);
660   return -1;
661 }
662
663 static int cancel = 0; /* XXX Implement file cancellation. */
664 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
665 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
666 static int send_file_cancellation (guestfs_h *g);
667 static int send_file_complete (guestfs_h *g);
668
669 /* Send a file.
670  * Returns:
671  *   0 OK
672  *   -1 error
673  *   -2 daemon cancelled (we must read the error message)
674  */
675 int
676 guestfs___send_file (guestfs_h *g, const char *filename)
677 {
678   char buf[GUESTFS_MAX_CHUNK_SIZE];
679   int fd, r, err;
680
681   fd = open (filename, O_RDONLY);
682   if (fd == -1) {
683     perrorf (g, "open: %s", filename);
684     send_file_cancellation (g);
685     /* Daemon sees cancellation and won't reply, so caller can
686      * just return here.
687      */
688     return -1;
689   }
690
691   /* Send file in chunked encoding. */
692   while (!cancel) {
693     r = read (fd, buf, sizeof buf);
694     if (r == -1 && (errno == EINTR || errno == EAGAIN))
695       continue;
696     if (r <= 0) break;
697     err = send_file_data (g, buf, r);
698     if (err < 0) {
699       if (err == -2)            /* daemon sent cancellation */
700         send_file_cancellation (g);
701       return err;
702     }
703   }
704
705   if (cancel) {                 /* cancel from either end */
706     send_file_cancellation (g);
707     return -1;
708   }
709
710   if (r == -1) {
711     perrorf (g, "read: %s", filename);
712     send_file_cancellation (g);
713     return -1;
714   }
715
716   /* End of file, but before we send that, we need to close
717    * the file and check for errors.
718    */
719   if (close (fd) == -1) {
720     perrorf (g, "close: %s", filename);
721     send_file_cancellation (g);
722     return -1;
723   }
724
725   return send_file_complete (g);
726 }
727
728 /* Send a chunk of file data. */
729 static int
730 send_file_data (guestfs_h *g, const char *buf, size_t len)
731 {
732   return send_file_chunk (g, 0, buf, len);
733 }
734
735 /* Send a cancellation message. */
736 static int
737 send_file_cancellation (guestfs_h *g)
738 {
739   return send_file_chunk (g, 1, NULL, 0);
740 }
741
742 /* Send a file complete chunk. */
743 static int
744 send_file_complete (guestfs_h *g)
745 {
746   char buf[1];
747   return send_file_chunk (g, 0, buf, 0);
748 }
749
750 static int
751 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
752 {
753   u_int32_t len;
754   int r;
755   guestfs_chunk chunk;
756   XDR xdr;
757   char *msg_out;
758   size_t msg_out_size;
759
760   if (g->state != BUSY) {
761     error (g, _("send_file_chunk: state %d != READY"), g->state);
762     return -1;
763   }
764
765   /* Allocate the chunk buffer.  Don't use the stack to avoid
766    * excessive stack usage and unnecessary copies.
767    */
768   msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
769   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
770
771   /* Serialize the chunk. */
772   chunk.cancel = cancel;
773   chunk.data.data_len = buflen;
774   chunk.data.data_val = (char *) buf;
775
776   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
777     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
778            buf, buflen);
779     xdr_destroy (&xdr);
780     goto cleanup1;
781   }
782
783   len = xdr_getpos (&xdr);
784   xdr_destroy (&xdr);
785
786   /* Reduce the size of the outgoing message buffer to the real length. */
787   msg_out = safe_realloc (g, msg_out, len + 4);
788   msg_out_size = len + 4;
789
790   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
791   xdr_uint32_t (&xdr, &len);
792
793   r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
794
795   /* Did the daemon send a cancellation message? */
796   if (r == -2) {
797     if (g->verbose)
798       fprintf (stderr, "got daemon cancellation\n");
799     return -2;
800   }
801
802   if (r == -1)
803     goto cleanup1;
804
805   free (msg_out);
806
807   return 0;
808
809  cleanup1:
810   free (msg_out);
811   return -1;
812 }
813
814 /* Receive a reply. */
815 int
816 guestfs___recv (guestfs_h *g, const char *fn,
817                 guestfs_message_header *hdr,
818                 guestfs_message_error *err,
819                 xdrproc_t xdrp, char *ret)
820 {
821   XDR xdr;
822   void *buf;
823   uint32_t size;
824   int r;
825
826  again:
827   r = guestfs___recv_from_daemon (g, &size, &buf);
828   if (r == -1)
829     return -1;
830
831   /* This can happen if a cancellation happens right at the end
832    * of us sending a FileIn parameter to the daemon.  Discard.  The
833    * daemon should send us an error message next.
834    */
835   if (size == GUESTFS_CANCEL_FLAG)
836     goto again;
837
838   if (size == GUESTFS_LAUNCH_FLAG) {
839     error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
840     return -1;
841   }
842
843   xdrmem_create (&xdr, buf, size, XDR_DECODE);
844
845   if (!xdr_guestfs_message_header (&xdr, hdr)) {
846     error (g, "%s: failed to parse reply header", fn);
847     xdr_destroy (&xdr);
848     free (buf);
849     return -1;
850   }
851   if (hdr->status == GUESTFS_STATUS_ERROR) {
852     if (!xdr_guestfs_message_error (&xdr, err)) {
853       error (g, "%s: failed to parse reply error", fn);
854       xdr_destroy (&xdr);
855       free (buf);
856       return -1;
857     }
858   } else {
859     if (xdrp && ret && !xdrp (&xdr, ret)) {
860       error (g, "%s: failed to parse reply", fn);
861       xdr_destroy (&xdr);
862       free (buf);
863       return -1;
864     }
865   }
866   xdr_destroy (&xdr);
867   free (buf);
868
869   return 0;
870 }
871
872 /* Receive a file. */
873
874 /* Returns -1 = error, 0 = EOF, > 0 = more data */
875 static ssize_t receive_file_data (guestfs_h *g, void **buf);
876
877 int
878 guestfs___recv_file (guestfs_h *g, const char *filename)
879 {
880   void *buf;
881   int fd, r;
882
883   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
884   if (fd == -1) {
885     perrorf (g, "open: %s", filename);
886     goto cancel;
887   }
888
889   /* Receive the file in chunked encoding. */
890   while ((r = receive_file_data (g, &buf)) > 0) {
891     if (xwrite (fd, buf, r) == -1) {
892       perrorf (g, "%s: write", filename);
893       free (buf);
894       goto cancel;
895     }
896     free (buf);
897   }
898
899   if (r == -1) {
900     error (g, _("%s: error in chunked encoding"), filename);
901     return -1;
902   }
903
904   if (close (fd) == -1) {
905     perrorf (g, "close: %s", filename);
906     return -1;
907   }
908
909   return 0;
910
911  cancel: ;
912   /* Send cancellation message to daemon, then wait until it
913    * cancels (just throwing away data).
914    */
915   XDR xdr;
916   char fbuf[4];
917   uint32_t flag = GUESTFS_CANCEL_FLAG;
918
919   if (g->verbose)
920     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
921              __func__);
922
923   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
924   xdr_uint32_t (&xdr, &flag);
925   xdr_destroy (&xdr);
926
927   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
928     perrorf (g, _("write to daemon socket"));
929     return -1;
930   }
931
932   while (receive_file_data (g, NULL) > 0)
933     ;                           /* just discard it */
934
935   return -1;
936 }
937
938 /* Receive a chunk of file data. */
939 /* Returns -1 = error, 0 = EOF, > 0 = more data */
940 static ssize_t
941 receive_file_data (guestfs_h *g, void **buf_r)
942 {
943   int r;
944   void *buf;
945   uint32_t len;
946   XDR xdr;
947   guestfs_chunk chunk;
948
949   r = guestfs___recv_from_daemon (g, &len, &buf);
950   if (r == -1) {
951     error (g, _("receive_file_data: parse error in reply callback"));
952     return -1;
953   }
954
955   if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
956     error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
957     return -1;
958   }
959
960   memset (&chunk, 0, sizeof chunk);
961
962   xdrmem_create (&xdr, buf, len, XDR_DECODE);
963   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
964     error (g, _("failed to parse file chunk"));
965     free (buf);
966     return -1;
967   }
968   xdr_destroy (&xdr);
969   /* After decoding, the original buffer is no longer used. */
970   free (buf);
971
972   if (chunk.cancel) {
973     error (g, _("file receive cancelled by daemon"));
974     free (chunk.data.data_val);
975     return -1;
976   }
977
978   if (chunk.data.data_len == 0) { /* end of transfer */
979     free (chunk.data.data_val);
980     return 0;
981   }
982
983   if (buf_r) *buf_r = chunk.data.data_val;
984   else free (chunk.data.data_val); /* else caller frees */
985
986   return chunk.data.data_len;
987 }