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