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