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