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