regressions: Enable both tests for bug 576879 (not fixed).
[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 static void
330 send_progress_message (guestfs_h *g, const guestfs_progress *message)
331 {
332   uint64_t array[4];
333
334   array[0] = message->proc;
335   array[1] = message->serial;
336   array[2] = message->position;
337   array[3] = message->total;
338
339   guestfs___call_callbacks_array (g, GUESTFS_EVENT_PROGRESS,
340                                   array, sizeof array / sizeof array[0]);
341 }
342
343 static int
344 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
345 {
346   char summary[MAX_MESSAGE_SUMMARY];
347   char buf[4];
348   ssize_t n;
349   uint32_t flag;
350   XDR xdr;
351
352   n = really_read_from_socket (g, fd, buf, 4);
353   if (n == -1)
354     return -1;
355   if (n == 0) {
356     /* Hopefully this indicates the qemu child process has died. */
357     child_cleanup (g);
358     return -1;
359   }
360
361   debug (g, "check_for_daemon_cancellation_or_eof: %s",
362          message_summary (buf, 4, summary));
363
364   xdrmem_create (&xdr, buf, 4, XDR_DECODE);
365   xdr_uint32_t (&xdr, &flag);
366   xdr_destroy (&xdr);
367
368   /* Read and process progress messages that happen during FileIn. */
369   if (flag == GUESTFS_PROGRESS_FLAG) {
370     char buf[PROGRESS_MESSAGE_SIZE];
371
372     n = really_read_from_socket (g, fd, buf, PROGRESS_MESSAGE_SIZE);
373     if (n == -1)
374       return -1;
375     if (n == 0) {
376       child_cleanup (g);
377       return -1;
378     }
379
380     if (g->state == BUSY) {
381       guestfs_progress message;
382
383       xdrmem_create (&xdr, buf, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
384       xdr_guestfs_progress (&xdr, &message);
385       xdr_destroy (&xdr);
386
387       send_progress_message (g, &message);
388     }
389
390     return 0;
391   }
392
393   if (flag != GUESTFS_CANCEL_FLAG) {
394     error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
395            flag, GUESTFS_CANCEL_FLAG);
396     return -1;
397   }
398
399   return -2;
400 }
401
402 /* This writes the whole N bytes of BUF to the daemon socket.
403  *
404  * If the whole write is successful, it returns 0.
405  * If there was an error, it returns -1.
406  * If the daemon sent a cancellation message, it returns -2.
407  *
408  * It also checks qemu stdout for log messages and passes those up
409  * through log_message_cb.
410  *
411  * It also checks for EOF (qemu died) and passes that up through the
412  * child_cleanup function above.
413  */
414 int
415 guestfs___send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
416 {
417   const char *buf = v_buf;
418   fd_set rset, rset2;
419   fd_set wset, wset2;
420   char summary[MAX_MESSAGE_SUMMARY];
421
422   debug (g, "send_to_daemon: %zu bytes: %s", n,
423          message_summary (v_buf, n, summary));
424
425   FD_ZERO (&rset);
426   FD_ZERO (&wset);
427
428   if (g->fd[1] >= 0)            /* Read qemu stdout for log messages & EOF. */
429     FD_SET (g->fd[1], &rset);
430   FD_SET (g->sock, &rset);      /* Read socket for cancellation & EOF. */
431   FD_SET (g->sock, &wset);      /* Write to socket to send the data. */
432
433   int max_fd = MAX (g->sock, g->fd[1]);
434
435   while (n > 0) {
436     rset2 = rset;
437     wset2 = wset;
438     int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
439     if (r == -1) {
440       if (errno == EINTR || errno == EAGAIN)
441         continue;
442       perrorf (g, "select");
443       return -1;
444     }
445
446     if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
447       if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
448         return -1;
449     }
450     if (FD_ISSET (g->sock, &rset2)) {
451       r = check_for_daemon_cancellation_or_eof (g, g->sock);
452       if (r < 0)
453         return r;
454     }
455     if (FD_ISSET (g->sock, &wset2)) {
456       r = write (g->sock, buf, n);
457       if (r == -1) {
458         if (errno == EINTR || errno == EAGAIN)
459           continue;
460         perrorf (g, "write");
461         if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
462           child_cleanup (g);
463         return -1;
464       }
465       buf += r;
466       n -= r;
467     }
468   }
469
470   return 0;
471 }
472
473 /* This reads a single message, file chunk, launch flag or
474  * cancellation flag from the daemon.  If something was read, it
475  * returns 0, otherwise -1.
476  *
477  * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
478  *
479  * *size_rtn returns the size of the returned message or it may be
480  * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
481  *
482  * *buf_rtn is returned containing the message (if any) or will be set
483  * to NULL.  *buf_rtn must be freed by the caller.
484  *
485  * It also checks qemu stdout for log messages and passes those up
486  * through log_message_cb.
487  *
488  * It also checks for EOF (qemu died) and passes that up through the
489  * child_cleanup function above.
490  *
491  * Progress notifications are handled transparently by this function.
492  * If the callback exists, it is called.  The caller of this function
493  * will not see GUESTFS_PROGRESS_FLAG.
494  */
495
496 int
497 guestfs___recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
498 {
499   char summary[MAX_MESSAGE_SUMMARY];
500   fd_set rset, rset2;
501
502   FD_ZERO (&rset);
503
504   if (g->fd[1] >= 0)            /* Read qemu stdout for log messages & EOF. */
505     FD_SET (g->fd[1], &rset);
506   FD_SET (g->sock, &rset);      /* Read socket for data & EOF. */
507
508   int max_fd = MAX (g->sock, g->fd[1]);
509
510   *size_rtn = 0;
511   *buf_rtn = NULL;
512
513   char lenbuf[4];
514   /* nr is the size of the message, but we prime it as -4 because we
515    * have to read the message length word first.
516    */
517   ssize_t nr = -4;
518
519   for (;;) {
520     ssize_t message_size =
521       *size_rtn != GUESTFS_PROGRESS_FLAG ?
522       *size_rtn : PROGRESS_MESSAGE_SIZE;
523     if (nr >= message_size)
524       break;
525
526     rset2 = rset;
527     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
528     if (r == -1) {
529       if (errno == EINTR || errno == EAGAIN)
530         continue;
531       perrorf (g, "select");
532       free (*buf_rtn);
533       *buf_rtn = NULL;
534       return -1;
535     }
536
537     if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
538       if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
539         free (*buf_rtn);
540         *buf_rtn = NULL;
541         return -1;
542       }
543     }
544     if (FD_ISSET (g->sock, &rset2)) {
545       if (nr < 0) {    /* Have we read the message length word yet? */
546         r = read (g->sock, lenbuf+nr+4, -nr);
547         if (r == -1) {
548           if (errno == EINTR || errno == EAGAIN)
549             continue;
550           int err = errno;
551           perrorf (g, "read");
552           /* Under some circumstances we see "Connection reset by peer"
553            * here when the child dies suddenly.  Catch this and call
554            * the cleanup function, same as for EOF.
555            */
556           if (err == ECONNRESET)
557             child_cleanup (g);
558           return -1;
559         }
560         if (r == 0) {
561           error (g, _("unexpected end of file when reading from daemon"));
562           child_cleanup (g);
563           return -1;
564         }
565         nr += r;
566
567         if (nr < 0)         /* Still not got the whole length word. */
568           continue;
569
570         XDR xdr;
571         xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
572         xdr_uint32_t (&xdr, size_rtn);
573         xdr_destroy (&xdr);
574
575         /* *size_rtn changed, recalculate message_size */
576         message_size =
577           *size_rtn != GUESTFS_PROGRESS_FLAG ?
578           *size_rtn : PROGRESS_MESSAGE_SIZE;
579
580         if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
581           if (g->state != LAUNCHING)
582             error (g, _("received magic signature from guestfsd, but in state %d"),
583                    g->state);
584           else {
585             g->state = READY;
586             guestfs___call_callbacks_void (g, GUESTFS_EVENT_LAUNCH_DONE);
587           }
588           debug (g, "recv_from_daemon: received GUESTFS_LAUNCH_FLAG");
589           return 0;
590         }
591         else if (*size_rtn == GUESTFS_CANCEL_FLAG) {
592           debug (g, "recv_from_daemon: received GUESTFS_CANCEL_FLAG");
593           return 0;
594         }
595         else if (*size_rtn == GUESTFS_PROGRESS_FLAG)
596           /*FALLTHROUGH*/;
597         /* If this happens, it's pretty bad and we've probably lost
598          * synchronization.
599          */
600         else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
601           error (g, _("message length (%u) > maximum possible size (%d)"),
602                  (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
603           return -1;
604         }
605
606         /* Allocate the complete buffer, size now known. */
607         *buf_rtn = safe_malloc (g, message_size);
608         /*FALLTHROUGH*/
609       }
610
611       size_t sizetoread = message_size - nr;
612       if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
613
614       r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
615       if (r == -1) {
616         if (errno == EINTR || errno == EAGAIN)
617           continue;
618         perrorf (g, "read");
619         free (*buf_rtn);
620         *buf_rtn = NULL;
621         return -1;
622       }
623       if (r == 0) {
624         error (g, _("unexpected end of file when reading from daemon"));
625         child_cleanup (g);
626         free (*buf_rtn);
627         *buf_rtn = NULL;
628         return -1;
629       }
630       nr += r;
631     }
632   }
633
634   /* Got the full message, caller can start processing it. */
635 #ifdef ENABLE_PACKET_DUMP
636   if (g->verbose) {
637     ssize_t i, j;
638
639     for (i = 0; i < nr; i += 16) {
640       printf ("%04zx: ", i);
641       for (j = i; j < MIN (i+16, nr); ++j)
642         printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
643       for (; j < i+16; ++j)
644         printf ("   ");
645       printf ("|");
646       for (j = i; j < MIN (i+16, nr); ++j)
647         if (c_isprint ((*(char **)buf_rtn)[j]))
648           printf ("%c", (*(char **)buf_rtn)[j]);
649         else
650           printf (".");
651       for (; j < i+16; ++j)
652         printf (" ");
653       printf ("|\n");
654     }
655   }
656 #endif
657
658   if (*size_rtn == GUESTFS_PROGRESS_FLAG) {
659     if (g->state == BUSY) {
660       guestfs_progress message;
661       XDR xdr;
662       xdrmem_create (&xdr, *buf_rtn, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
663       xdr_guestfs_progress (&xdr, &message);
664       xdr_destroy (&xdr);
665
666       send_progress_message (g, &message);
667     }
668
669     free (*buf_rtn);
670     *buf_rtn = NULL;
671
672     /* Process next message. */
673     return guestfs___recv_from_daemon (g, size_rtn, buf_rtn);
674   }
675
676   debug (g, "recv_from_daemon: %" PRIu32 " bytes: %s", *size_rtn,
677          message_summary (*buf_rtn, *size_rtn, summary));
678
679   return 0;
680 }
681
682 /* This is very much like recv_from_daemon above, but g->sock is
683  * a listening socket and we are accepting a new connection on
684  * that socket instead of reading anything.  Returns the newly
685  * accepted socket.
686  */
687 int
688 guestfs___accept_from_daemon (guestfs_h *g)
689 {
690   fd_set rset, rset2;
691
692   debug (g, "accept_from_daemon: %p g->state = %d", g, g->state);
693
694   FD_ZERO (&rset);
695
696   if (g->fd[1] >= 0)            /* Read qemu stdout for log messages & EOF. */
697     FD_SET (g->fd[1], &rset);
698   FD_SET (g->sock, &rset);      /* Read socket for accept. */
699
700   int max_fd = MAX (g->sock, g->fd[1]);
701   int sock = -1;
702
703   while (sock == -1) {
704     /* If the qemu process has died, clean up the zombie (RHBZ#579155).
705      * By partially polling in the select below we ensure that this
706      * function will be called eventually.
707      */
708     waitpid (g->pid, NULL, WNOHANG);
709
710     rset2 = rset;
711
712     struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
713     int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
714     if (r == -1) {
715       if (errno == EINTR || errno == EAGAIN)
716         continue;
717       perrorf (g, "select");
718       return -1;
719     }
720
721     if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
722       if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
723         return -1;
724     }
725     if (FD_ISSET (g->sock, &rset2)) {
726       sock = accept (g->sock, NULL, NULL);
727       if (sock == -1) {
728         if (errno == EINTR || errno == EAGAIN)
729           continue;
730         perrorf (g, "accept");
731         return -1;
732       }
733     }
734   }
735
736   return sock;
737 }
738
739 int
740 guestfs___send (guestfs_h *g, int proc_nr,
741                 uint64_t progress_hint, uint64_t optargs_bitmask,
742                 xdrproc_t xdrp, char *args)
743 {
744   struct guestfs_message_header hdr;
745   XDR xdr;
746   u_int32_t len;
747   int serial = g->msg_next_serial++;
748   int r;
749   char *msg_out;
750   size_t msg_out_size;
751
752   if (g->state != BUSY) {
753     error (g, _("guestfs___send: state %d != BUSY"), g->state);
754     return -1;
755   }
756
757   /* We have to allocate this message buffer on the heap because
758    * it is quite large (although will be mostly unused).  We
759    * can't allocate it on the stack because in some environments
760    * we have quite limited stack space available, notably when
761    * running in the JVM.
762    */
763   msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
764   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
765
766   /* Serialize the header. */
767   hdr.prog = GUESTFS_PROGRAM;
768   hdr.vers = GUESTFS_PROTOCOL_VERSION;
769   hdr.proc = proc_nr;
770   hdr.direction = GUESTFS_DIRECTION_CALL;
771   hdr.serial = serial;
772   hdr.status = GUESTFS_STATUS_OK;
773   hdr.progress_hint = progress_hint;
774   hdr.optargs_bitmask = optargs_bitmask;
775
776   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
777     error (g, _("xdr_guestfs_message_header failed"));
778     goto cleanup1;
779   }
780
781   /* Serialize the args.  If any, because some message types
782    * have no parameters.
783    */
784   if (xdrp) {
785     if (!(*xdrp) (&xdr, args)) {
786       error (g, _("dispatch failed to marshal args"));
787       goto cleanup1;
788     }
789   }
790
791   /* Get the actual length of the message, resize the buffer to match
792    * the actual length, and write the length word at the beginning.
793    */
794   len = xdr_getpos (&xdr);
795   xdr_destroy (&xdr);
796
797   msg_out = safe_realloc (g, msg_out, len + 4);
798   msg_out_size = len + 4;
799
800   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
801   xdr_uint32_t (&xdr, &len);
802
803  again:
804   r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
805   if (r == -2)                  /* Ignore stray daemon cancellations. */
806     goto again;
807   if (r == -1)
808     goto cleanup1;
809   free (msg_out);
810
811   return serial;
812
813  cleanup1:
814   free (msg_out);
815   return -1;
816 }
817
818 static int cancel = 0; /* XXX Implement file cancellation. */
819 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
820 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
821 static int send_file_cancellation (guestfs_h *g);
822 static int send_file_complete (guestfs_h *g);
823
824 /* Send a file.
825  * Returns:
826  *   0 OK
827  *   -1 error
828  *   -2 daemon cancelled (we must read the error message)
829  */
830 int
831 guestfs___send_file (guestfs_h *g, const char *filename)
832 {
833   char buf[GUESTFS_MAX_CHUNK_SIZE];
834   int fd, r, err;
835
836   fd = open (filename, O_RDONLY);
837   if (fd == -1) {
838     perrorf (g, "open: %s", filename);
839     send_file_cancellation (g);
840     /* Daemon sees cancellation and won't reply, so caller can
841      * just return here.
842      */
843     return -1;
844   }
845
846   /* Send file in chunked encoding. */
847   while (!cancel) {
848     r = read (fd, buf, sizeof buf);
849     if (r == -1 && (errno == EINTR || errno == EAGAIN))
850       continue;
851     if (r <= 0) break;
852     err = send_file_data (g, buf, r);
853     if (err < 0) {
854       if (err == -2)            /* daemon sent cancellation */
855         send_file_cancellation (g);
856       return err;
857     }
858   }
859
860   if (cancel) {                 /* cancel from either end */
861     send_file_cancellation (g);
862     return -1;
863   }
864
865   if (r == -1) {
866     perrorf (g, "read: %s", filename);
867     send_file_cancellation (g);
868     return -1;
869   }
870
871   /* End of file, but before we send that, we need to close
872    * the file and check for errors.
873    */
874   if (close (fd) == -1) {
875     perrorf (g, "close: %s", filename);
876     send_file_cancellation (g);
877     return -1;
878   }
879
880   return send_file_complete (g);
881 }
882
883 /* Send a chunk of file data. */
884 static int
885 send_file_data (guestfs_h *g, const char *buf, size_t len)
886 {
887   return send_file_chunk (g, 0, buf, len);
888 }
889
890 /* Send a cancellation message. */
891 static int
892 send_file_cancellation (guestfs_h *g)
893 {
894   return send_file_chunk (g, 1, NULL, 0);
895 }
896
897 /* Send a file complete chunk. */
898 static int
899 send_file_complete (guestfs_h *g)
900 {
901   char buf[1];
902   return send_file_chunk (g, 0, buf, 0);
903 }
904
905 static int
906 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
907 {
908   u_int32_t len;
909   int r;
910   guestfs_chunk chunk;
911   XDR xdr;
912   char *msg_out;
913   size_t msg_out_size;
914
915   if (g->state != BUSY) {
916     error (g, _("send_file_chunk: state %d != READY"), g->state);
917     return -1;
918   }
919
920   /* Allocate the chunk buffer.  Don't use the stack to avoid
921    * excessive stack usage and unnecessary copies.
922    */
923   msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
924   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
925
926   /* Serialize the chunk. */
927   chunk.cancel = cancel;
928   chunk.data.data_len = buflen;
929   chunk.data.data_val = (char *) buf;
930
931   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
932     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
933            buf, buflen);
934     xdr_destroy (&xdr);
935     goto cleanup1;
936   }
937
938   len = xdr_getpos (&xdr);
939   xdr_destroy (&xdr);
940
941   /* Reduce the size of the outgoing message buffer to the real length. */
942   msg_out = safe_realloc (g, msg_out, len + 4);
943   msg_out_size = len + 4;
944
945   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
946   xdr_uint32_t (&xdr, &len);
947
948   r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
949
950   /* Did the daemon send a cancellation message? */
951   if (r == -2) {
952     debug (g, "got daemon cancellation");
953     return -2;
954   }
955
956   if (r == -1)
957     goto cleanup1;
958
959   free (msg_out);
960
961   return 0;
962
963  cleanup1:
964   free (msg_out);
965   return -1;
966 }
967
968 /* Receive a reply. */
969 int
970 guestfs___recv (guestfs_h *g, const char *fn,
971                 guestfs_message_header *hdr,
972                 guestfs_message_error *err,
973                 xdrproc_t xdrp, char *ret)
974 {
975   XDR xdr;
976   void *buf;
977   uint32_t size;
978   int r;
979
980  again:
981   r = guestfs___recv_from_daemon (g, &size, &buf);
982   if (r == -1)
983     return -1;
984
985   /* This can happen if a cancellation happens right at the end
986    * of us sending a FileIn parameter to the daemon.  Discard.  The
987    * daemon should send us an error message next.
988    */
989   if (size == GUESTFS_CANCEL_FLAG)
990     goto again;
991
992   if (size == GUESTFS_LAUNCH_FLAG) {
993     error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
994     return -1;
995   }
996
997   xdrmem_create (&xdr, buf, size, XDR_DECODE);
998
999   if (!xdr_guestfs_message_header (&xdr, hdr)) {
1000     error (g, "%s: failed to parse reply header", fn);
1001     xdr_destroy (&xdr);
1002     free (buf);
1003     return -1;
1004   }
1005   if (hdr->status == GUESTFS_STATUS_ERROR) {
1006     if (!xdr_guestfs_message_error (&xdr, err)) {
1007       error (g, "%s: failed to parse reply error", fn);
1008       xdr_destroy (&xdr);
1009       free (buf);
1010       return -1;
1011     }
1012   } else {
1013     if (xdrp && ret && !xdrp (&xdr, ret)) {
1014       error (g, "%s: failed to parse reply", fn);
1015       xdr_destroy (&xdr);
1016       free (buf);
1017       return -1;
1018     }
1019   }
1020   xdr_destroy (&xdr);
1021   free (buf);
1022
1023   return 0;
1024 }
1025
1026 /* Receive a file. */
1027
1028 /* Returns -1 = error, 0 = EOF, > 0 = more data */
1029 static ssize_t receive_file_data (guestfs_h *g, void **buf);
1030
1031 int
1032 guestfs___recv_file (guestfs_h *g, const char *filename)
1033 {
1034   void *buf;
1035   int fd, r;
1036
1037   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1038   if (fd == -1) {
1039     perrorf (g, "open: %s", filename);
1040     goto cancel;
1041   }
1042
1043   /* Receive the file in chunked encoding. */
1044   while ((r = receive_file_data (g, &buf)) > 0) {
1045     if (xwrite (fd, buf, r) == -1) {
1046       perrorf (g, "%s: write", filename);
1047       free (buf);
1048       goto cancel;
1049     }
1050     free (buf);
1051   }
1052
1053   if (r == -1) {
1054     error (g, _("%s: error in chunked encoding"), filename);
1055     return -1;
1056   }
1057
1058   if (close (fd) == -1) {
1059     perrorf (g, "close: %s", filename);
1060     return -1;
1061   }
1062
1063   return 0;
1064
1065  cancel: ;
1066   /* Send cancellation message to daemon, then wait until it
1067    * cancels (just throwing away data).
1068    */
1069   XDR xdr;
1070   char fbuf[4];
1071   uint32_t flag = GUESTFS_CANCEL_FLAG;
1072
1073   debug (g, "%s: waiting for daemon to acknowledge cancellation",
1074          __func__);
1075
1076   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1077   xdr_uint32_t (&xdr, &flag);
1078   xdr_destroy (&xdr);
1079
1080   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1081     perrorf (g, _("write to daemon socket"));
1082     return -1;
1083   }
1084
1085   while (receive_file_data (g, NULL) > 0)
1086     ;                           /* just discard it */
1087
1088   return -1;
1089 }
1090
1091 /* Receive a chunk of file data. */
1092 /* Returns -1 = error, 0 = EOF, > 0 = more data */
1093 static ssize_t
1094 receive_file_data (guestfs_h *g, void **buf_r)
1095 {
1096   int r;
1097   void *buf;
1098   uint32_t len;
1099   XDR xdr;
1100   guestfs_chunk chunk;
1101
1102   r = guestfs___recv_from_daemon (g, &len, &buf);
1103   if (r == -1) {
1104     error (g, _("receive_file_data: parse error in reply callback"));
1105     return -1;
1106   }
1107
1108   if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
1109     error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
1110     return -1;
1111   }
1112
1113   memset (&chunk, 0, sizeof chunk);
1114
1115   xdrmem_create (&xdr, buf, len, XDR_DECODE);
1116   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1117     error (g, _("failed to parse file chunk"));
1118     free (buf);
1119     return -1;
1120   }
1121   xdr_destroy (&xdr);
1122   /* After decoding, the original buffer is no longer used. */
1123   free (buf);
1124
1125   if (chunk.cancel) {
1126     error (g, _("file receive cancelled by daemon"));
1127     free (chunk.data.data_val);
1128     return -1;
1129   }
1130
1131   if (chunk.data.data_len == 0) { /* end of transfer */
1132     free (chunk.data.data_val);
1133     return 0;
1134   }
1135
1136   if (buf_r) *buf_r = chunk.data.data_val;
1137   else free (chunk.data.data_val); /* else caller frees */
1138
1139   return chunk.data.data_len;
1140 }