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