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