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