Enable new-style -chardev ... guestfwd command line.
[libguestfs.git] / src / guestfs.c
1 /* libguestfs
2  * Copyright (C) 2009 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 <unistd.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <sys/stat.h>
33 #include <sys/select.h>
34 #include <dirent.h>
35
36 #include <rpc/types.h>
37 #include <rpc/xdr.h>
38
39 #ifdef HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
45 #endif
46
47 #ifdef HAVE_SYS_WAIT_H
48 #include <sys/wait.h>
49 #endif
50
51 #ifdef HAVE_SYS_SOCKET_H
52 #include <sys/socket.h>
53 #endif
54
55 #ifdef HAVE_SYS_UN_H
56 #include <sys/un.h>
57 #endif
58
59 #include "guestfs.h"
60 #include "guestfs-internal-actions.h"
61 #include "guestfs_protocol.h"
62 #include "ignore-value.h"
63
64 #ifdef HAVE_GETTEXT
65 #include "gettext.h"
66 #define _(str) dgettext(PACKAGE, (str))
67 //#define N_(str) dgettext(PACKAGE, (str))
68 #else
69 #define _(str) str
70 //#define N_(str) str
71 #endif
72
73 #define error guestfs_error
74 #define perrorf guestfs_perrorf
75 #define safe_malloc guestfs_safe_malloc
76 #define safe_realloc guestfs_safe_realloc
77 #define safe_strdup guestfs_safe_strdup
78 //#define safe_memdup guestfs_safe_memdup
79
80 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
81 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
82 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
83 static void close_handles (void);
84
85 #define UNIX_PATH_MAX 108
86
87 /* Also in guestfsd.c */
88 #define GUESTFWD_PORT 6666
89 #define GUESTFWD_ADDR "10.0.2.4"
90
91 /* GuestFS handle and connection. */
92 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
93
94 struct guestfs_h
95 {
96   struct guestfs_h *next;       /* Linked list of open handles. */
97
98   /* State: see the state machine diagram in the man page guestfs(3). */
99   enum state state;
100
101   int fd[2];                    /* Stdin/stdout of qemu. */
102   int sock;                     /* Daemon communications socket. */
103   pid_t pid;                    /* Qemu PID. */
104   pid_t recoverypid;            /* Recovery process PID. */
105   time_t start_t;               /* The time when we started qemu. */
106
107   char *tmpdir;                 /* Temporary directory containing socket. */
108
109   char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
110
111   char **cmdline;               /* Qemu command line. */
112   int cmdline_size;
113
114   int verbose;
115   int trace;
116   int autosync;
117
118   char *path;                   /* Path to kernel, initrd. */
119   char *qemu;                   /* Qemu binary. */
120   char *append;                 /* Append to kernel command line. */
121
122   int memsize;                  /* Size of RAM (megabytes). */
123
124   int selinux;                  /* selinux enabled? */
125
126   char *last_error;
127
128   /* Callbacks. */
129   guestfs_abort_cb           abort_cb;
130   guestfs_error_handler_cb   error_cb;
131   void *                     error_cb_data;
132   guestfs_log_message_cb     log_message_cb;
133   void *                     log_message_cb_data;
134   guestfs_subprocess_quit_cb subprocess_quit_cb;
135   void *                     subprocess_quit_cb_data;
136   guestfs_launch_done_cb     launch_done_cb;
137   void *                     launch_done_cb_data;
138
139   int msg_next_serial;
140 };
141
142 static guestfs_h *handles = NULL;
143 static int atexit_handler_set = 0;
144
145 guestfs_h *
146 guestfs_create (void)
147 {
148   guestfs_h *g;
149   const char *str;
150
151   g = malloc (sizeof (*g));
152   if (!g) return NULL;
153
154   memset (g, 0, sizeof (*g));
155
156   g->state = CONFIG;
157
158   g->fd[0] = -1;
159   g->fd[1] = -1;
160   g->sock = -1;
161
162   g->abort_cb = abort;
163   g->error_cb = default_error_cb;
164   g->error_cb_data = NULL;
165
166   str = getenv ("LIBGUESTFS_DEBUG");
167   g->verbose = str != NULL && strcmp (str, "1") == 0;
168
169   str = getenv ("LIBGUESTFS_TRACE");
170   g->trace = str != NULL && strcmp (str, "1") == 0;
171
172   str = getenv ("LIBGUESTFS_PATH");
173   g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
174   if (!g->path) goto error;
175
176   str = getenv ("LIBGUESTFS_QEMU");
177   g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
178   if (!g->qemu) goto error;
179
180   str = getenv ("LIBGUESTFS_APPEND");
181   if (str) {
182     g->append = strdup (str);
183     if (!g->append) goto error;
184   }
185
186   /* Choose a suitable memory size.  Previously we tried to choose
187    * a minimal memory size, but this isn't really necessary since
188    * recent QEMU and KVM don't do anything nasty like locking
189    * memory into core any more.  Thus we can safely choose a
190    * large, generous amount of memory, and it'll just get swapped
191    * on smaller systems.
192    */
193   str = getenv ("LIBGUESTFS_MEMSIZE");
194   if (str) {
195     if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
196       fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
197       goto error;
198     }
199   } else
200     g->memsize = 500;
201
202   /* Start with large serial numbers so they are easy to spot
203    * inside the protocol.
204    */
205   g->msg_next_serial = 0x00123400;
206
207   /* Link the handles onto a global list.  This is the one area
208    * where the library needs to be made thread-safe. (XXX)
209    */
210   /* acquire mutex (XXX) */
211   g->next = handles;
212   handles = g;
213   if (!atexit_handler_set) {
214     atexit (close_handles);
215     atexit_handler_set = 1;
216   }
217   /* release mutex (XXX) */
218
219   if (g->verbose)
220     fprintf (stderr, "new guestfs handle %p\n", g);
221
222   return g;
223
224  error:
225   free (g->path);
226   free (g->qemu);
227   free (g->append);
228   free (g);
229   return NULL;
230 }
231
232 void
233 guestfs_close (guestfs_h *g)
234 {
235   int i;
236   char filename[256];
237   guestfs_h *gg;
238
239   if (g->state == NO_HANDLE) {
240     /* Not safe to call 'error' here, so ... */
241     fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
242     return;
243   }
244
245   if (g->verbose)
246     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
247
248   /* Try to sync if autosync flag is set. */
249   if (g->autosync && g->state == READY) {
250     guestfs_umount_all (g);
251     guestfs_sync (g);
252   }
253
254   /* Remove any handlers that might be called back before we kill the
255    * subprocess.
256    */
257   g->log_message_cb = NULL;
258
259   if (g->state != CONFIG)
260     guestfs_kill_subprocess (g);
261
262   /* Close sockets. */
263   if (g->fd[0] >= 0)
264     close (g->fd[0]);
265   if (g->fd[1] >= 0)
266     close (g->fd[1]);
267   if (g->sock >= 0)
268     close (g->sock);
269   g->fd[0] = -1;
270   g->fd[1] = -1;
271   g->sock = -1;
272
273   /* Wait for subprocess(es) to exit. */
274   waitpid (g->pid, NULL, 0);
275   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
276
277   /* Remove tmpfiles. */
278   if (g->tmpdir) {
279     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
280     unlink (filename);
281
282     snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
283     unlink (filename);
284
285     snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
286     unlink (filename);
287
288     rmdir (g->tmpdir);
289
290     free (g->tmpdir);
291   }
292
293   if (g->cmdline) {
294     for (i = 0; i < g->cmdline_size; ++i)
295       free (g->cmdline[i]);
296     free (g->cmdline);
297   }
298
299   /* Mark the handle as dead before freeing it. */
300   g->state = NO_HANDLE;
301
302   /* acquire mutex (XXX) */
303   if (handles == g)
304     handles = g->next;
305   else {
306     for (gg = handles; gg->next != g; gg = gg->next)
307       ;
308     gg->next = g->next;
309   }
310   /* release mutex (XXX) */
311
312   free (g->last_error);
313   free (g->path);
314   free (g->qemu);
315   free (g->append);
316   free (g->qemu_help);
317   free (g->qemu_version);
318   free (g);
319 }
320
321 /* Close all open handles (called from atexit(3)). */
322 static void
323 close_handles (void)
324 {
325   while (handles) guestfs_close (handles);
326 }
327
328 const char *
329 guestfs_last_error (guestfs_h *g)
330 {
331   return g->last_error;
332 }
333
334 static void
335 set_last_error (guestfs_h *g, const char *msg)
336 {
337   free (g->last_error);
338   g->last_error = strdup (msg);
339 }
340
341 static void
342 default_error_cb (guestfs_h *g, void *data, const char *msg)
343 {
344   fprintf (stderr, _("libguestfs: error: %s\n"), msg);
345 }
346
347 void
348 guestfs_error (guestfs_h *g, const char *fs, ...)
349 {
350   va_list args;
351   char *msg;
352
353   va_start (args, fs);
354   int err = vasprintf (&msg, fs, args);
355   va_end (args);
356
357   if (err < 0) return;
358
359   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
360   set_last_error (g, msg);
361
362   free (msg);
363 }
364
365 void
366 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
367 {
368   va_list args;
369   char *msg;
370   int errnum = errno;
371
372   va_start (args, fs);
373   int err = vasprintf (&msg, fs, args);
374   va_end (args);
375
376   if (err < 0) return;
377
378 #ifndef _GNU_SOURCE
379   char buf[256];
380   strerror_r (errnum, buf, sizeof buf);
381 #else
382   char _buf[256];
383   char *buf;
384   buf = strerror_r (errnum, _buf, sizeof _buf);
385 #endif
386
387   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
388   strcat (msg, ": ");
389   strcat (msg, buf);
390
391   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
392   set_last_error (g, msg);
393
394   free (msg);
395 }
396
397 void *
398 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
399 {
400   void *ptr = malloc (nbytes);
401   if (nbytes > 0 && !ptr) g->abort_cb ();
402   return ptr;
403 }
404
405 /* Return 1 if an array of N objects, each of size S, cannot exist due
406    to size arithmetic overflow.  S must be positive and N must be
407    nonnegative.  This is a macro, not an inline function, so that it
408    works correctly even when SIZE_MAX < N.
409
410    By gnulib convention, SIZE_MAX represents overflow in size
411    calculations, so the conservative dividend to use here is
412    SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
413    However, malloc (SIZE_MAX) fails on all known hosts where
414    sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
415    exactly-SIZE_MAX allocations on such hosts; this avoids a test and
416    branch when S is known to be 1.  */
417 # define xalloc_oversized(n, s) \
418     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
419
420 /* Technically we should add an autoconf test for this, testing for the desired
421    functionality, like what's done in gnulib, but for now, this is fine.  */
422 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
423
424 /* Allocate zeroed memory for N elements of S bytes, with error
425    checking.  S must be nonzero.  */
426 void *
427 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
428 {
429   /* From gnulib's calloc function in xmalloc.c.  */
430   void *p;
431   /* Test for overflow, since some calloc implementations don't have
432      proper overflow checks.  But omit overflow and size-zero tests if
433      HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
434      returns NULL if successful.  */
435   if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
436       || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
437     g->abort_cb ();
438   return p;
439 }
440
441 void *
442 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
443 {
444   void *p = realloc (ptr, nbytes);
445   if (nbytes > 0 && !p) g->abort_cb ();
446   return p;
447 }
448
449 char *
450 guestfs_safe_strdup (guestfs_h *g, const char *str)
451 {
452   char *s = strdup (str);
453   if (!s) g->abort_cb ();
454   return s;
455 }
456
457 void *
458 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
459 {
460   void *p = malloc (size);
461   if (!p) g->abort_cb ();
462   memcpy (p, ptr, size);
463   return p;
464 }
465
466 static int
467 xwrite (int fd, const void *v_buf, size_t len)
468 {
469   const char *buf = v_buf;
470   int r;
471
472   while (len > 0) {
473     r = write (fd, buf, len);
474     if (r == -1)
475       return -1;
476
477     buf += r;
478     len -= r;
479   }
480
481   return 0;
482 }
483
484 void
485 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
486 {
487   g->abort_cb = cb;
488 }
489
490 guestfs_abort_cb
491 guestfs_get_out_of_memory_handler (guestfs_h *g)
492 {
493   return g->abort_cb;
494 }
495
496 void
497 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
498 {
499   g->error_cb = cb;
500   g->error_cb_data = data;
501 }
502
503 guestfs_error_handler_cb
504 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
505 {
506   if (data_rtn) *data_rtn = g->error_cb_data;
507   return g->error_cb;
508 }
509
510 int
511 guestfs__set_verbose (guestfs_h *g, int v)
512 {
513   g->verbose = !!v;
514   return 0;
515 }
516
517 int
518 guestfs__get_verbose (guestfs_h *g)
519 {
520   return g->verbose;
521 }
522
523 int
524 guestfs__set_autosync (guestfs_h *g, int a)
525 {
526   g->autosync = !!a;
527   return 0;
528 }
529
530 int
531 guestfs__get_autosync (guestfs_h *g)
532 {
533   return g->autosync;
534 }
535
536 int
537 guestfs__set_path (guestfs_h *g, const char *path)
538 {
539   free (g->path);
540   g->path = NULL;
541
542   g->path =
543     path == NULL ?
544     safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
545   return 0;
546 }
547
548 const char *
549 guestfs__get_path (guestfs_h *g)
550 {
551   return g->path;
552 }
553
554 int
555 guestfs__set_qemu (guestfs_h *g, const char *qemu)
556 {
557   free (g->qemu);
558   g->qemu = NULL;
559
560   g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
561   return 0;
562 }
563
564 const char *
565 guestfs__get_qemu (guestfs_h *g)
566 {
567   return g->qemu;
568 }
569
570 int
571 guestfs__set_append (guestfs_h *g, const char *append)
572 {
573   free (g->append);
574   g->append = NULL;
575
576   g->append = append ? safe_strdup (g, append) : NULL;
577   return 0;
578 }
579
580 const char *
581 guestfs__get_append (guestfs_h *g)
582 {
583   return g->append;
584 }
585
586 int
587 guestfs__set_memsize (guestfs_h *g, int memsize)
588 {
589   g->memsize = memsize;
590   return 0;
591 }
592
593 int
594 guestfs__get_memsize (guestfs_h *g)
595 {
596   return g->memsize;
597 }
598
599 int
600 guestfs__set_selinux (guestfs_h *g, int selinux)
601 {
602   g->selinux = selinux;
603   return 0;
604 }
605
606 int
607 guestfs__get_selinux (guestfs_h *g)
608 {
609   return g->selinux;
610 }
611
612 int
613 guestfs__get_pid (guestfs_h *g)
614 {
615   if (g->pid > 0)
616     return g->pid;
617   else {
618     error (g, "get_pid: no qemu subprocess");
619     return -1;
620   }
621 }
622
623 struct guestfs_version *
624 guestfs__version (guestfs_h *g)
625 {
626   struct guestfs_version *r;
627
628   r = safe_malloc (g, sizeof *r);
629   r->major = PACKAGE_VERSION_MAJOR;
630   r->minor = PACKAGE_VERSION_MINOR;
631   r->release = PACKAGE_VERSION_RELEASE;
632   r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
633   return r;
634 }
635
636 int
637 guestfs__set_trace (guestfs_h *g, int t)
638 {
639   g->trace = !!t;
640   return 0;
641 }
642
643 int
644 guestfs__get_trace (guestfs_h *g)
645 {
646   return g->trace;
647 }
648
649 /* Add a string to the current command line. */
650 static void
651 incr_cmdline_size (guestfs_h *g)
652 {
653   if (g->cmdline == NULL) {
654     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
655     g->cmdline_size = 1;
656     g->cmdline = safe_malloc (g, sizeof (char *));
657     g->cmdline[0] = NULL;
658   }
659
660   g->cmdline_size++;
661   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
662 }
663
664 static int
665 add_cmdline (guestfs_h *g, const char *str)
666 {
667   if (g->state != CONFIG) {
668     error (g,
669         _("command line cannot be altered after qemu subprocess launched"));
670     return -1;
671   }
672
673   incr_cmdline_size (g);
674   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
675   return 0;
676 }
677
678 int
679 guestfs__config (guestfs_h *g,
680                  const char *qemu_param, const char *qemu_value)
681 {
682   if (qemu_param[0] != '-') {
683     error (g, _("guestfs_config: parameter must begin with '-' character"));
684     return -1;
685   }
686
687   /* A bit fascist, but the user will probably break the extra
688    * parameters that we add if they try to set any of these.
689    */
690   if (strcmp (qemu_param, "-kernel") == 0 ||
691       strcmp (qemu_param, "-initrd") == 0 ||
692       strcmp (qemu_param, "-nographic") == 0 ||
693       strcmp (qemu_param, "-serial") == 0 ||
694       strcmp (qemu_param, "-full-screen") == 0 ||
695       strcmp (qemu_param, "-std-vga") == 0 ||
696       strcmp (qemu_param, "-vnc") == 0) {
697     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
698     return -1;
699   }
700
701   if (add_cmdline (g, qemu_param) != 0) return -1;
702
703   if (qemu_value != NULL) {
704     if (add_cmdline (g, qemu_value) != 0) return -1;
705   }
706
707   return 0;
708 }
709
710 int
711 guestfs__add_drive (guestfs_h *g, const char *filename)
712 {
713   size_t len = strlen (filename) + 64;
714   char buf[len];
715
716   if (strchr (filename, ',') != NULL) {
717     error (g, _("filename cannot contain ',' (comma) character"));
718     return -1;
719   }
720
721   /* cache=off improves reliability in the event of a host crash.
722    *
723    * However this option causes qemu to try to open the file with
724    * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
725    * So we check if we can open the file with or without O_DIRECT,
726    * and use cache=off (or not) accordingly.
727    *
728    * This test also checks for the presence of the file, which
729    * is a documented semantic of this interface.
730    */
731   int fd = open (filename, O_RDONLY|O_DIRECT);
732   if (fd >= 0) {
733     close (fd);
734     snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
735   } else {
736     fd = open (filename, O_RDONLY);
737     if (fd >= 0) {
738       close (fd);
739       snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
740     } else {
741       perrorf (g, "%s", filename);
742       return -1;
743     }
744   }
745
746   return guestfs__config (g, "-drive", buf);
747 }
748
749 int
750 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
751 {
752   size_t len = strlen (filename) + 64;
753   char buf[len];
754
755   if (strchr (filename, ',') != NULL) {
756     error (g, _("filename cannot contain ',' (comma) character"));
757     return -1;
758   }
759
760   if (access (filename, F_OK) == -1) {
761     perrorf (g, "%s", filename);
762     return -1;
763   }
764
765   snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
766
767   return guestfs__config (g, "-drive", buf);
768 }
769
770 int
771 guestfs__add_cdrom (guestfs_h *g, const char *filename)
772 {
773   if (strchr (filename, ',') != NULL) {
774     error (g, _("filename cannot contain ',' (comma) character"));
775     return -1;
776   }
777
778   if (access (filename, F_OK) == -1) {
779     perrorf (g, "%s", filename);
780     return -1;
781   }
782
783   return guestfs__config (g, "-cdrom", filename);
784 }
785
786 /* Returns true iff file is contained in dir. */
787 static int
788 dir_contains_file (const char *dir, const char *file)
789 {
790   int dirlen = strlen (dir);
791   int filelen = strlen (file);
792   int len = dirlen+filelen+2;
793   char path[len];
794
795   snprintf (path, len, "%s/%s", dir, file);
796   return access (path, F_OK) == 0;
797 }
798
799 /* Returns true iff every listed file is contained in 'dir'. */
800 static int
801 dir_contains_files (const char *dir, ...)
802 {
803   va_list args;
804   const char *file;
805
806   va_start (args, dir);
807   while ((file = va_arg (args, const char *)) != NULL) {
808     if (!dir_contains_file (dir, file)) {
809       va_end (args);
810       return 0;
811     }
812   }
813   va_end (args);
814   return 1;
815 }
816
817 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
818 static int test_qemu (guestfs_h *g);
819 static int qemu_supports (guestfs_h *g, const char *option);
820 static void print_cmdline (guestfs_h *g);
821
822 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
823 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
824 static const char *supermin_name =
825   "initramfs." REPO "." host_cpu ".supermin.img";
826 static const char *supermin_hostfiles_name =
827   "initramfs." REPO "." host_cpu ".supermin.hostfiles";
828
829 int
830 guestfs__launch (guestfs_h *g)
831 {
832   const char *tmpdir;
833   char dir_template[PATH_MAX];
834   int r, pmore;
835   size_t len;
836   int wfd[2], rfd[2];
837   int tries;
838   char *path, *pelem, *pend;
839   char *kernel = NULL, *initrd = NULL;
840   char unixsock[256];
841   struct sockaddr_un addr;
842
843 #ifdef P_tmpdir
844   tmpdir = P_tmpdir;
845 #else
846   tmpdir = "/tmp";
847 #endif
848
849   tmpdir = getenv ("TMPDIR") ? : tmpdir;
850   snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
851
852   /* Configured? */
853   if (!g->cmdline) {
854     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
855     return -1;
856   }
857
858   if (g->state != CONFIG) {
859     error (g, _("qemu has already been launched"));
860     return -1;
861   }
862
863   /* Make the temporary directory. */
864   if (!g->tmpdir) {
865     g->tmpdir = safe_strdup (g, dir_template);
866     if (mkdtemp (g->tmpdir) == NULL) {
867       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
868       goto cleanup0;
869     }
870   }
871
872   /* First search g->path for the supermin appliance, and try to
873    * synthesize a kernel and initrd from that.  If it fails, we
874    * try the path search again looking for a backup ordinary
875    * appliance.
876    */
877   pelem = path = safe_strdup (g, g->path);
878   do {
879     pend = strchrnul (pelem, ':');
880     pmore = *pend == ':';
881     *pend = '\0';
882     len = pend - pelem;
883
884     /* Empty element of "." means cwd. */
885     if (len == 0 || (len == 1 && *pelem == '.')) {
886       if (g->verbose)
887         fprintf (stderr,
888                  "looking for supermin appliance in current directory\n");
889       if (dir_contains_files (".",
890                               supermin_name, supermin_hostfiles_name,
891                               "kmod.whitelist", NULL)) {
892         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
893           return -1;
894         break;
895       }
896     }
897     /* Look at <path>/supermin* etc. */
898     else {
899       if (g->verbose)
900         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
901
902       if (dir_contains_files (pelem,
903                               supermin_name, supermin_hostfiles_name,
904                               "kmod.whitelist", NULL)) {
905         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
906           return -1;
907         break;
908       }
909     }
910
911     pelem = pend + 1;
912   } while (pmore);
913
914   free (path);
915
916   if (kernel == NULL || initrd == NULL) {
917     /* Search g->path for the kernel and initrd. */
918     pelem = path = safe_strdup (g, g->path);
919     do {
920       pend = strchrnul (pelem, ':');
921       pmore = *pend == ':';
922       *pend = '\0';
923       len = pend - pelem;
924
925       /* Empty element or "." means cwd. */
926       if (len == 0 || (len == 1 && *pelem == '.')) {
927         if (g->verbose)
928           fprintf (stderr,
929                    "looking for appliance in current directory\n");
930         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
931           kernel = safe_strdup (g, kernel_name);
932           initrd = safe_strdup (g, initrd_name);
933           break;
934         }
935       }
936       /* Look at <path>/kernel etc. */
937       else {
938         if (g->verbose)
939           fprintf (stderr, "looking for appliance in %s\n", pelem);
940
941         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
942           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
943           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
944           sprintf (kernel, "%s/%s", pelem, kernel_name);
945           sprintf (initrd, "%s/%s", pelem, initrd_name);
946           break;
947         }
948       }
949
950       pelem = pend + 1;
951     } while (pmore);
952
953     free (path);
954   }
955
956   if (kernel == NULL || initrd == NULL) {
957     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
958            kernel_name, initrd_name, g->path);
959     goto cleanup0;
960   }
961
962   /* Get qemu help text and version. */
963   if (test_qemu (g) == -1)
964     goto cleanup0;
965
966   /* Make the vmchannel socket. */
967   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
968   unlink (unixsock);
969
970   if (pipe (wfd) == -1 || pipe (rfd) == -1) {
971     perrorf (g, "pipe");
972     goto cleanup0;
973   }
974
975   r = fork ();
976   if (r == -1) {
977     perrorf (g, "fork");
978     close (wfd[0]);
979     close (wfd[1]);
980     close (rfd[0]);
981     close (rfd[1]);
982     goto cleanup0;
983   }
984
985   if (r == 0) {                 /* Child (qemu). */
986     char buf[256];
987     char append[256];
988     char memsize_str[256];
989
990     /* Set up the full command line.  Do this in the subprocess so we
991      * don't need to worry about cleaning up.
992      */
993     g->cmdline[0] = g->qemu;
994
995 #define LINUX_CMDLINE                                                   \
996     "panic=1 "         /* force kernel to panic if daemon exits */      \
997     "console=ttyS0 "   /* serial console */                             \
998     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
999     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
1000     "acpi=off "        /* we don't need ACPI, turn it off */            \
1001     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1002
1003     /* Linux kernel command line. */
1004     snprintf (append, sizeof append,
1005               LINUX_CMDLINE
1006               "%s"              /* (selinux) */
1007               "%s"              /* (verbose) */
1008               "%s",             /* (append) */
1009               g->selinux ? "selinux=1 enforcing=0 " : "selinux=0 ",
1010               g->verbose ? "guestfs_verbose=1 " : " ",
1011               g->append ? g->append : "");
1012
1013     snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1014
1015     add_cmdline (g, "-m");
1016     add_cmdline (g, memsize_str);
1017     add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1018     add_cmdline (g, "-kernel");
1019     add_cmdline (g, (char *) kernel);
1020     add_cmdline (g, "-initrd");
1021     add_cmdline (g, (char *) initrd);
1022     add_cmdline (g, "-append");
1023     add_cmdline (g, append);
1024     add_cmdline (g, "-nographic");
1025     add_cmdline (g, "-serial");
1026     add_cmdline (g, "stdio");
1027
1028     if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1029       /* New-style -net user,guestfwd=... syntax for guestfwd.  See:
1030        *
1031        * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1032        *
1033        * The original suggested format doesn't work, see:
1034        *
1035        * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1036        *
1037        * However Gerd Hoffman privately suggested to me using -chardev
1038        * instead, which does work.
1039        */
1040       snprintf (buf, sizeof buf,
1041                 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1042
1043       add_cmdline (g, "-chardev");
1044       add_cmdline (g, buf);
1045
1046       snprintf (buf, sizeof buf,
1047                 "user,vlan=0,net=10.0.2.0/8,"
1048                 "guestfwd=tcp:%s:%d-chardev:guestfsvmc",
1049                 GUESTFWD_ADDR, GUESTFWD_PORT);
1050
1051       add_cmdline (g, "-net");
1052       add_cmdline (g, buf);
1053     } else {
1054       /* Not guestfwd.  HOPEFULLY this qemu uses the older -net channel
1055        * syntax, or if not then we'll get a quick failure.
1056        */
1057       snprintf (buf, sizeof buf,
1058                 "channel,%d:unix:%s,server,nowait", GUESTFWD_PORT, unixsock);
1059
1060       add_cmdline (g, "-net");
1061       add_cmdline (g, buf);
1062       add_cmdline (g, "-net");
1063       add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1064     }
1065     add_cmdline (g, "-net");
1066     add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1067
1068     /* These options recommended by KVM developers to improve reliability. */
1069     if (qemu_supports (g, "-no-hpet"))
1070       add_cmdline (g, "-no-hpet");
1071
1072     if (qemu_supports (g, "-rtc-td-hack"))
1073       add_cmdline (g, "-rtc-td-hack");
1074
1075     /* Finish off the command line. */
1076     incr_cmdline_size (g);
1077     g->cmdline[g->cmdline_size-1] = NULL;
1078
1079     if (g->verbose)
1080       print_cmdline (g);
1081
1082     /* Set up stdin, stdout. */
1083     close (0);
1084     close (1);
1085     close (wfd[1]);
1086     close (rfd[0]);
1087
1088     if (dup (wfd[0]) == -1) {
1089     dup_failed:
1090       perror ("dup failed");
1091       _exit (1);
1092     }
1093     if (dup (rfd[1]) == -1)
1094       goto dup_failed;
1095
1096     close (wfd[0]);
1097     close (rfd[1]);
1098
1099 #if 0
1100     /* Set up a new process group, so we can signal this process
1101      * and all subprocesses (eg. if qemu is really a shell script).
1102      */
1103     setpgid (0, 0);
1104 #endif
1105
1106     execv (g->qemu, g->cmdline); /* Run qemu. */
1107     perror (g->qemu);
1108     _exit (1);
1109   }
1110
1111   /* Parent (library). */
1112   g->pid = r;
1113
1114   free (kernel);
1115   kernel = NULL;
1116   free (initrd);
1117   initrd = NULL;
1118
1119   /* Fork the recovery process off which will kill qemu if the parent
1120    * process fails to do so (eg. if the parent segfaults).
1121    */
1122   r = fork ();
1123   if (r == 0) {
1124     pid_t qemu_pid = g->pid;
1125     pid_t parent_pid = getppid ();
1126
1127     /* Writing to argv is hideously complicated and error prone.  See:
1128      * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1129      */
1130
1131     /* Loop around waiting for one or both of the other processes to
1132      * disappear.  It's fair to say this is very hairy.  The PIDs that
1133      * we are looking at might be reused by another process.  We are
1134      * effectively polling.  Is the cure worse than the disease?
1135      */
1136     for (;;) {
1137       if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1138         _exit (0);
1139       if (kill (parent_pid, 0) == -1) {
1140         /* Parent's gone away, qemu still around, so kill qemu. */
1141         kill (qemu_pid, 9);
1142         _exit (0);
1143       }
1144       sleep (2);
1145     }
1146   }
1147
1148   /* Don't worry, if the fork failed, this will be -1.  The recovery
1149    * process isn't essential.
1150    */
1151   g->recoverypid = r;
1152
1153   /* Start the clock ... */
1154   time (&g->start_t);
1155
1156   /* Close the other ends of the pipe. */
1157   close (wfd[0]);
1158   close (rfd[1]);
1159
1160   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1161       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1162     perrorf (g, "fcntl");
1163     goto cleanup1;
1164   }
1165
1166   g->fd[0] = wfd[1];            /* stdin of child */
1167   g->fd[1] = rfd[0];            /* stdout of child */
1168
1169   /* Open the Unix socket.  The vmchannel implementation that got
1170    * merged with qemu sucks in a number of ways.  Both ends do
1171    * connect(2), which means that no one knows what, if anything, is
1172    * connected to the other end, or if it becomes disconnected.  Even
1173    * worse, we have to wait some indeterminate time for qemu to create
1174    * the socket and connect to it (which happens very early in qemu's
1175    * start-up), so any code that uses vmchannel is inherently racy.
1176    * Hence this silly loop.
1177    */
1178   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1179   if (g->sock == -1) {
1180     perrorf (g, "socket");
1181     goto cleanup1;
1182   }
1183
1184   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1185     perrorf (g, "fcntl");
1186     goto cleanup2;
1187   }
1188
1189   addr.sun_family = AF_UNIX;
1190   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1191   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1192
1193   tries = 100;
1194   /* Always sleep at least once to give qemu a small chance to start up. */
1195   usleep (10000);
1196   while (tries > 0) {
1197     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1198     if ((r == -1 && errno == EINPROGRESS) || r == 0)
1199       goto connected;
1200
1201     if (errno != ENOENT)
1202       perrorf (g, "connect");
1203     tries--;
1204     usleep (100000);
1205   }
1206
1207   error (g, _("failed to connect to vmchannel socket"));
1208   goto cleanup2;
1209
1210  connected:
1211   g->state = LAUNCHING;
1212   return 0;
1213
1214  cleanup2:
1215   close (g->sock);
1216
1217  cleanup1:
1218   close (wfd[1]);
1219   close (rfd[0]);
1220   kill (g->pid, 9);
1221   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1222   waitpid (g->pid, NULL, 0);
1223   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1224   g->fd[0] = -1;
1225   g->fd[1] = -1;
1226   g->sock = -1;
1227   g->pid = 0;
1228   g->recoverypid = 0;
1229   g->start_t = 0;
1230
1231  cleanup0:
1232   free (kernel);
1233   free (initrd);
1234   return -1;
1235 }
1236
1237 /* This function is used to print the qemu command line before it gets
1238  * executed, when in verbose mode.
1239  */
1240 static void
1241 print_cmdline (guestfs_h *g)
1242 {
1243   int i = 0;
1244   int needs_quote;
1245
1246   while (g->cmdline[i]) {
1247     if (g->cmdline[i][0] == '-') /* -option starts a new line */
1248       fprintf (stderr, " \\\n   ");
1249
1250     if (i > 0) fputc (' ', stderr);
1251
1252     /* Does it need shell quoting?  This only deals with simple cases. */
1253     needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1254
1255     if (needs_quote) fputc ('\'', stderr);
1256     fprintf (stderr, "%s", g->cmdline[i]);
1257     if (needs_quote) fputc ('\'', stderr);
1258     i++;
1259   }
1260
1261   fputc ('\n', stderr);
1262 }
1263
1264 /* This function does the hard work of building the supermin appliance
1265  * on the fly.  'path' is the directory containing the control files.
1266  * 'kernel' and 'initrd' are where we will return the names of the
1267  * kernel and initrd (only initrd is built).  The work is done by
1268  * an external script.  We just tell it where to put the result.
1269  */
1270 static int
1271 build_supermin_appliance (guestfs_h *g, const char *path,
1272                           char **kernel, char **initrd)
1273 {
1274   char cmd[4096];
1275   int r, len;
1276
1277   len = strlen (g->tmpdir);
1278   *kernel = safe_malloc (g, len + 8);
1279   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1280   *initrd = safe_malloc (g, len + 8);
1281   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1282
1283   snprintf (cmd, sizeof cmd,
1284             "PATH='%s':$PATH "
1285             "libguestfs-supermin-helper '%s' %s %s",
1286             path,
1287             path, *kernel, *initrd);
1288
1289   r = system (cmd);
1290   if (r == -1 || WEXITSTATUS(r) != 0) {
1291     error (g, _("external command failed: %s"), cmd);
1292     free (*kernel);
1293     free (*initrd);
1294     *kernel = *initrd = NULL;
1295     return -1;
1296   }
1297
1298   return 0;
1299 }
1300
1301 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1302
1303 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1304  * 'qemu -version' so we know what options this qemu supports and
1305  * the version.
1306  */
1307 static int
1308 test_qemu (guestfs_h *g)
1309 {
1310   char cmd[1024];
1311   FILE *fp;
1312
1313   free (g->qemu_help);
1314   free (g->qemu_version);
1315   g->qemu_help = NULL;
1316   g->qemu_version = NULL;
1317
1318   snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1319
1320   fp = popen (cmd, "r");
1321   /* qemu -help should always work (qemu -version OTOH wasn't
1322    * supported by qemu 0.9).  If this command doesn't work then it
1323    * probably indicates that the qemu binary is missing.
1324    */
1325   if (!fp) {
1326     /* XXX This error is never printed, even if the qemu binary
1327      * doesn't exist.  Why?
1328      */
1329   error:
1330     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1331     return -1;
1332   }
1333
1334   if (read_all (g, fp, &g->qemu_help) == -1)
1335     goto error;
1336
1337   if (pclose (fp) == -1)
1338     goto error;
1339
1340   snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1341
1342   fp = popen (cmd, "r");
1343   if (fp) {
1344     /* Intentionally ignore errors. */
1345     read_all (g, fp, &g->qemu_version);
1346     pclose (fp);
1347   }
1348
1349   return 0;
1350 }
1351
1352 static int
1353 read_all (guestfs_h *g, FILE *fp, char **ret)
1354 {
1355   int r, n = 0;
1356   char *p;
1357
1358  again:
1359   if (feof (fp)) {
1360     *ret = safe_realloc (g, *ret, n + 1);
1361     (*ret)[n] = '\0';
1362     return n;
1363   }
1364
1365   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1366   p = &(*ret)[n];
1367   r = fread (p, 1, BUFSIZ, fp);
1368   if (ferror (fp)) {
1369     perrorf (g, "read");
1370     return -1;
1371   }
1372   n += r;
1373   goto again;
1374 }
1375
1376 /* Test if option is supported by qemu command line (just by grepping
1377  * the help text).
1378  */
1379 static int
1380 qemu_supports (guestfs_h *g, const char *option)
1381 {
1382   return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1383 }
1384
1385 int
1386 guestfs__wait_ready (guestfs_h *g)
1387 {
1388   int r;
1389   uint32_t size;
1390   void *buf = NULL;
1391
1392   if (g->state == READY) return 0;
1393
1394   if (g->state == BUSY) {
1395     error (g, _("qemu has finished launching already"));
1396     return -1;
1397   }
1398
1399   if (g->state != LAUNCHING) {
1400     error (g, _("qemu has not been launched yet"));
1401     return -1;
1402   }
1403
1404   r = recv_from_daemon (g, &size, &buf);
1405   free (buf);
1406
1407   if (r == -1) return -1;
1408
1409   if (size != GUESTFS_LAUNCH_FLAG) {
1410     error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1411     return -1;
1412   }
1413
1414   /* This is possible in some really strange situations, such as
1415    * guestfsd starts up OK but then qemu immediately exits.  Check for
1416    * it because the caller is probably expecting to be able to send
1417    * commands after this function returns.
1418    */
1419   if (g->state != READY) {
1420     error (g, _("qemu launched and contacted daemon, but state != READY"));
1421     return -1;
1422   }
1423
1424   return 0;
1425 }
1426
1427 int
1428 guestfs__kill_subprocess (guestfs_h *g)
1429 {
1430   if (g->state == CONFIG) {
1431     error (g, _("no subprocess to kill"));
1432     return -1;
1433   }
1434
1435   if (g->verbose)
1436     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1437
1438   kill (g->pid, SIGTERM);
1439   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1440
1441   return 0;
1442 }
1443
1444 /* Access current state. */
1445 int
1446 guestfs__is_config (guestfs_h *g)
1447 {
1448   return g->state == CONFIG;
1449 }
1450
1451 int
1452 guestfs__is_launching (guestfs_h *g)
1453 {
1454   return g->state == LAUNCHING;
1455 }
1456
1457 int
1458 guestfs__is_ready (guestfs_h *g)
1459 {
1460   return g->state == READY;
1461 }
1462
1463 int
1464 guestfs__is_busy (guestfs_h *g)
1465 {
1466   return g->state == BUSY;
1467 }
1468
1469 int
1470 guestfs__get_state (guestfs_h *g)
1471 {
1472   return g->state;
1473 }
1474
1475 void
1476 guestfs_set_log_message_callback (guestfs_h *g,
1477                                   guestfs_log_message_cb cb, void *opaque)
1478 {
1479   g->log_message_cb = cb;
1480   g->log_message_cb_data = opaque;
1481 }
1482
1483 void
1484 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1485                                       guestfs_subprocess_quit_cb cb, void *opaque)
1486 {
1487   g->subprocess_quit_cb = cb;
1488   g->subprocess_quit_cb_data = opaque;
1489 }
1490
1491 void
1492 guestfs_set_launch_done_callback (guestfs_h *g,
1493                                   guestfs_launch_done_cb cb, void *opaque)
1494 {
1495   g->launch_done_cb = cb;
1496   g->launch_done_cb_data = opaque;
1497 }
1498
1499 /*----------------------------------------------------------------------*/
1500
1501 /* This is the code used to send and receive RPC messages and (for
1502  * certain types of message) to perform file transfers.  This code is
1503  * driven from the generated actions (src/guestfs-actions.c).  There
1504  * are five different cases to consider:
1505  *
1506  * (1) A non-daemon function.  There is no RPC involved at all, it's
1507  * all handled inside the library.
1508  *
1509  * (2) A simple RPC (eg. "mount").  We write the request, then read
1510  * the reply.  The sequence of calls is:
1511  *
1512  *   guestfs___set_busy
1513  *   guestfs___send
1514  *   guestfs___recv
1515  *   guestfs___end_busy
1516  *
1517  * (3) An RPC with FileOut parameters (eg. "upload").  We write the
1518  * request, then write the file(s), then read the reply.  The sequence
1519  * of calls is:
1520  *
1521  *   guestfs___set_busy
1522  *   guestfs___send
1523  *   guestfs___send_file  (possibly multiple times)
1524  *   guestfs___recv
1525  *   guestfs___end_busy
1526  *
1527  * (4) An RPC with FileIn parameters (eg. "download").  We write the
1528  * request, then read the reply, then read the file(s).  The sequence
1529  * of calls is:
1530  *
1531  *   guestfs___set_busy
1532  *   guestfs___send
1533  *   guestfs___recv
1534  *   guestfs___recv_file  (possibly multiple times)
1535  *   guestfs___end_busy
1536  *
1537  * (5) Both FileOut and FileIn parameters.  There are no calls like
1538  * this in the current API, but they would be implemented as a
1539  * combination of cases (3) and (4).
1540  *
1541  * During all writes and reads, we also select(2) on qemu stdout
1542  * looking for messages (guestfsd stderr and guest kernel dmesg), and
1543  * anything received is passed up through the log_message_cb.  This is
1544  * also the reason why all the sockets are non-blocking.  We also have
1545  * to check for EOF (qemu died).  All of this is handled by the
1546  * functions send_to_daemon and recv_from_daemon.
1547  */
1548
1549 int
1550 guestfs___set_busy (guestfs_h *g)
1551 {
1552   if (g->state != READY) {
1553     error (g, _("guestfs_set_busy: called when in state %d != READY"),
1554            g->state);
1555     return -1;
1556   }
1557   g->state = BUSY;
1558   return 0;
1559 }
1560
1561 int
1562 guestfs___end_busy (guestfs_h *g)
1563 {
1564   switch (g->state)
1565     {
1566     case BUSY:
1567       g->state = READY;
1568       break;
1569     case CONFIG:
1570     case READY:
1571       break;
1572
1573     case LAUNCHING:
1574     case NO_HANDLE:
1575     default:
1576       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1577       return -1;
1578     }
1579   return 0;
1580 }
1581
1582 /* This is called if we detect EOF, ie. qemu died. */
1583 static void
1584 child_cleanup (guestfs_h *g)
1585 {
1586   if (g->verbose)
1587     fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1588
1589   /*kill (g->pid, SIGTERM);*/
1590   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1591   waitpid (g->pid, NULL, 0);
1592   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1593   close (g->fd[0]);
1594   close (g->fd[1]);
1595   close (g->sock);
1596   g->fd[0] = -1;
1597   g->fd[1] = -1;
1598   g->sock = -1;
1599   g->pid = 0;
1600   g->recoverypid = 0;
1601   g->start_t = 0;
1602   g->state = CONFIG;
1603   if (g->subprocess_quit_cb)
1604     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1605 }
1606
1607 static int
1608 read_log_message_or_eof (guestfs_h *g, int fd)
1609 {
1610   char buf[BUFSIZ];
1611   int n;
1612
1613 #if 0
1614   if (g->verbose)
1615     fprintf (stderr,
1616              "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1617              g, g->state, fd);
1618 #endif
1619
1620   /* QEMU's console emulates a 16550A serial port.  The real 16550A
1621    * device has a small FIFO buffer (16 bytes) which means here we see
1622    * lots of small reads of 1-16 bytes in length, usually single
1623    * bytes.
1624    */
1625   n = read (fd, buf, sizeof buf);
1626   if (n == 0) {
1627     /* Hopefully this indicates the qemu child process has died. */
1628     child_cleanup (g);
1629     return -1;
1630   }
1631
1632   if (n == -1) {
1633     if (errno == EINTR || errno == EAGAIN)
1634       return 0;
1635
1636     perrorf (g, "read");
1637     return -1;
1638   }
1639
1640   /* In verbose mode, copy all log messages to stderr. */
1641   if (g->verbose)
1642     ignore_value (write (STDERR_FILENO, buf, n));
1643
1644   /* It's an actual log message, send it upwards if anyone is listening. */
1645   if (g->log_message_cb)
1646     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1647
1648   return 0;
1649 }
1650
1651 static int
1652 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1653 {
1654   char buf[4];
1655   int n;
1656   uint32_t flag;
1657   XDR xdr;
1658
1659   if (g->verbose)
1660     fprintf (stderr,
1661              "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1662              g, g->state, fd);
1663
1664   n = read (fd, buf, 4);
1665   if (n == 0) {
1666     /* Hopefully this indicates the qemu child process has died. */
1667     child_cleanup (g);
1668     return -1;
1669   }
1670
1671   if (n == -1) {
1672     if (errno == EINTR || errno == EAGAIN)
1673       return 0;
1674
1675     perrorf (g, "read");
1676     return -1;
1677   }
1678
1679   xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1680   xdr_uint32_t (&xdr, &flag);
1681   xdr_destroy (&xdr);
1682
1683   if (flag != GUESTFS_CANCEL_FLAG) {
1684     error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1685            flag, GUESTFS_CANCEL_FLAG);
1686     return -1;
1687   }
1688
1689   return -2;
1690 }
1691
1692 /* This writes the whole N bytes of BUF to the daemon socket.
1693  *
1694  * If the whole write is successful, it returns 0.
1695  * If there was an error, it returns -1.
1696  * If the daemon sent a cancellation message, it returns -2.
1697  *
1698  * It also checks qemu stdout for log messages and passes those up
1699  * through log_message_cb.
1700  *
1701  * It also checks for EOF (qemu died) and passes that up through the
1702  * child_cleanup function above.
1703  */
1704 static int
1705 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1706 {
1707   const char *buf = v_buf;
1708   fd_set rset, rset2;
1709   fd_set wset, wset2;
1710
1711   if (g->verbose)
1712     fprintf (stderr,
1713              "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1714
1715   FD_ZERO (&rset);
1716   FD_ZERO (&wset);
1717
1718   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
1719   FD_SET (g->sock, &rset);      /* Read socket for cancellation & EOF. */
1720   FD_SET (g->sock, &wset);      /* Write to socket to send the data. */
1721
1722   int max_fd = g->sock > g->fd[1] ? g->sock : g->fd[1];
1723
1724   while (n > 0) {
1725     rset2 = rset;
1726     wset2 = wset;
1727     int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1728     if (r == -1) {
1729       if (errno == EINTR || errno == EAGAIN)
1730         continue;
1731       perrorf (g, "select");
1732       return -1;
1733     }
1734
1735     if (FD_ISSET (g->fd[1], &rset2)) {
1736       if (read_log_message_or_eof (g, g->fd[1]) == -1)
1737         return -1;
1738     }
1739     if (FD_ISSET (g->sock, &rset2)) {
1740       r = check_for_daemon_cancellation_or_eof (g, g->sock);
1741       if (r < 0)
1742         return r;
1743     }
1744     if (FD_ISSET (g->sock, &wset2)) {
1745       r = write (g->sock, buf, n);
1746       if (r == -1) {
1747         if (errno == EINTR || errno == EAGAIN)
1748           continue;
1749         perrorf (g, "write");
1750         if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1751           child_cleanup (g);
1752         return -1;
1753       }
1754       buf += r;
1755       n -= r;
1756     }
1757   }
1758
1759   return 0;
1760 }
1761
1762 /* This reads a single message, file chunk, launch flag or
1763  * cancellation flag from the daemon.  If something was read, it
1764  * returns 0, otherwise -1.
1765  *
1766  * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
1767  *
1768  * *size_rtn returns the size of the returned message or it may be
1769  * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
1770  *
1771  * *buf_rtn is returned containing the message (if any) or will be set
1772  * to NULL.  *buf_rtn must be freed by the caller.
1773  *
1774  * It also checks qemu stdout for log messages and passes those up
1775  * through log_message_cb.
1776  *
1777  * It also checks for EOF (qemu died) and passes that up through the
1778  * child_cleanup function above.
1779  */
1780 static int
1781 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
1782 {
1783   fd_set rset, rset2;
1784
1785   if (g->verbose)
1786     fprintf (stderr,
1787              "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
1788              g, g->state, size_rtn, buf_rtn);
1789
1790   FD_ZERO (&rset);
1791
1792   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
1793   FD_SET (g->sock, &rset);      /* Read socket for data & EOF. */
1794
1795   int max_fd = g->sock > g->fd[1] ? g->sock : g->fd[1];
1796
1797   *size_rtn = 0;
1798   *buf_rtn = NULL;
1799
1800   char lenbuf[4];
1801   /* nr is the size of the message, but we prime it as -4 because we
1802    * have to read the message length word first.
1803    */
1804   ssize_t nr = -4;
1805
1806   while (nr < (ssize_t) *size_rtn) {
1807     rset2 = rset;
1808     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
1809     if (r == -1) {
1810       if (errno == EINTR || errno == EAGAIN)
1811         continue;
1812       perrorf (g, "select");
1813       free (*buf_rtn);
1814       *buf_rtn = NULL;
1815       return -1;
1816     }
1817
1818     if (FD_ISSET (g->fd[1], &rset2)) {
1819       if (read_log_message_or_eof (g, g->fd[1]) == -1) {
1820         free (*buf_rtn);
1821         *buf_rtn = NULL;
1822         return -1;
1823       }
1824     }
1825     if (FD_ISSET (g->sock, &rset2)) {
1826       if (nr < 0) {    /* Have we read the message length word yet? */
1827         r = read (g->sock, lenbuf+nr+4, -nr);
1828         if (r == -1) {
1829           if (errno == EINTR || errno == EAGAIN)
1830             continue;
1831           int err = errno;
1832           perrorf (g, "read");
1833           /* Under some circumstances we see "Connection reset by peer"
1834            * here when the child dies suddenly.  Catch this and call
1835            * the cleanup function, same as for EOF.
1836            */
1837           if (err == ECONNRESET)
1838             child_cleanup (g);
1839           return -1;
1840         }
1841         if (r == 0) {
1842           error (g, _("unexpected end of file when reading from daemon"));
1843           child_cleanup (g);
1844           return -1;
1845         }
1846         nr += r;
1847
1848         if (nr < 0)         /* Still not got the whole length word. */
1849           continue;
1850
1851         XDR xdr;
1852         xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
1853         xdr_uint32_t (&xdr, size_rtn);
1854         xdr_destroy (&xdr);
1855
1856         if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
1857           if (g->state != LAUNCHING)
1858             error (g, _("received magic signature from guestfsd, but in state %d"),
1859                    g->state);
1860           else {
1861             g->state = READY;
1862             if (g->launch_done_cb)
1863               g->launch_done_cb (g, g->launch_done_cb_data);
1864           }
1865           return 0;
1866         }
1867         else if (*size_rtn == GUESTFS_CANCEL_FLAG)
1868           return 0;
1869         /* If this happens, it's pretty bad and we've probably lost
1870          * synchronization.
1871          */
1872         else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
1873           error (g, _("message length (%u) > maximum possible size (%d)"),
1874                  (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
1875           return -1;
1876         }
1877
1878         /* Allocate the complete buffer, size now known. */
1879         *buf_rtn = safe_malloc (g, *size_rtn);
1880         /*FALLTHROUGH*/
1881       }
1882
1883       size_t sizetoread = *size_rtn - nr;
1884       if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
1885
1886       r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
1887       if (r == -1) {
1888         if (errno == EINTR || errno == EAGAIN)
1889           continue;
1890         perrorf (g, "read");
1891         free (*buf_rtn);
1892         *buf_rtn = NULL;
1893         return -1;
1894       }
1895       if (r == 0) {
1896         error (g, _("unexpected end of file when reading from daemon"));
1897         child_cleanup (g);
1898         free (*buf_rtn);
1899         *buf_rtn = NULL;
1900         return -1;
1901       }
1902       nr += r;
1903     }
1904   }
1905
1906   /* Got the full message, caller can start processing it. */
1907 #ifdef ENABLE_PACKET_DUMP
1908   if (g->verbose) {
1909     ssize_t i, j;
1910
1911     for (i = 0; i < nr; i += 16) {
1912       printf ("%04zx: ", i);
1913       for (j = i; j < MIN (i+16, nr); ++j)
1914         printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
1915       for (; j < i+16; ++j)
1916         printf ("   ");
1917       printf ("|");
1918       for (j = i; j < MIN (i+16, nr); ++j)
1919         if (isprint ((*(char **)buf_rtn)[j]))
1920           printf ("%c", (*(char **)buf_rtn)[j]);
1921         else
1922           printf (".");
1923       for (; j < i+16; ++j)
1924         printf (" ");
1925       printf ("|\n");
1926     }
1927   }
1928 #endif
1929
1930   return 0;
1931 }
1932
1933 int
1934 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1935 {
1936   struct guestfs_message_header hdr;
1937   XDR xdr;
1938   u_int32_t len;
1939   int serial = g->msg_next_serial++;
1940   int r;
1941   char *msg_out;
1942   size_t msg_out_size;
1943
1944   if (g->state != BUSY) {
1945     error (g, _("guestfs___send: state %d != BUSY"), g->state);
1946     return -1;
1947   }
1948
1949   /* We have to allocate this message buffer on the heap because
1950    * it is quite large (although will be mostly unused).  We
1951    * can't allocate it on the stack because in some environments
1952    * we have quite limited stack space available, notably when
1953    * running in the JVM.
1954    */
1955   msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1956   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1957
1958   /* Serialize the header. */
1959   hdr.prog = GUESTFS_PROGRAM;
1960   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1961   hdr.proc = proc_nr;
1962   hdr.direction = GUESTFS_DIRECTION_CALL;
1963   hdr.serial = serial;
1964   hdr.status = GUESTFS_STATUS_OK;
1965
1966   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1967     error (g, _("xdr_guestfs_message_header failed"));
1968     goto cleanup1;
1969   }
1970
1971   /* Serialize the args.  If any, because some message types
1972    * have no parameters.
1973    */
1974   if (xdrp) {
1975     if (!(*xdrp) (&xdr, args)) {
1976       error (g, _("dispatch failed to marshal args"));
1977       goto cleanup1;
1978     }
1979   }
1980
1981   /* Get the actual length of the message, resize the buffer to match
1982    * the actual length, and write the length word at the beginning.
1983    */
1984   len = xdr_getpos (&xdr);
1985   xdr_destroy (&xdr);
1986
1987   msg_out = safe_realloc (g, msg_out, len + 4);
1988   msg_out_size = len + 4;
1989
1990   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
1991   xdr_uint32_t (&xdr, &len);
1992
1993  again:
1994   r = send_to_daemon (g, msg_out, msg_out_size);
1995   if (r == -2)                  /* Ignore stray daemon cancellations. */
1996     goto again;
1997   if (r == -1)
1998     goto cleanup1;
1999   free (msg_out);
2000
2001   return serial;
2002
2003  cleanup1:
2004   free (msg_out);
2005   return -1;
2006 }
2007
2008 static int cancel = 0; /* XXX Implement file cancellation. */
2009 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2010 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2011 static int send_file_cancellation (guestfs_h *g);
2012 static int send_file_complete (guestfs_h *g);
2013
2014 /* Send a file.
2015  * Returns:
2016  *   0 OK
2017  *   -1 error
2018  *   -2 daemon cancelled (we must read the error message)
2019  */
2020 int
2021 guestfs___send_file (guestfs_h *g, const char *filename)
2022 {
2023   char buf[GUESTFS_MAX_CHUNK_SIZE];
2024   int fd, r, err;
2025
2026   fd = open (filename, O_RDONLY);
2027   if (fd == -1) {
2028     perrorf (g, "open: %s", filename);
2029     send_file_cancellation (g);
2030     /* Daemon sees cancellation and won't reply, so caller can
2031      * just return here.
2032      */
2033     return -1;
2034   }
2035
2036   /* Send file in chunked encoding. */
2037   while (!cancel) {
2038     r = read (fd, buf, sizeof buf);
2039     if (r == -1 && (errno == EINTR || errno == EAGAIN))
2040       continue;
2041     if (r <= 0) break;
2042     err = send_file_data (g, buf, r);
2043     if (err < 0) {
2044       if (err == -2)            /* daemon sent cancellation */
2045         send_file_cancellation (g);
2046       return err;
2047     }
2048   }
2049
2050   if (cancel) {                 /* cancel from either end */
2051     send_file_cancellation (g);
2052     return -1;
2053   }
2054
2055   if (r == -1) {
2056     perrorf (g, "read: %s", filename);
2057     send_file_cancellation (g);
2058     return -1;
2059   }
2060
2061   /* End of file, but before we send that, we need to close
2062    * the file and check for errors.
2063    */
2064   if (close (fd) == -1) {
2065     perrorf (g, "close: %s", filename);
2066     send_file_cancellation (g);
2067     return -1;
2068   }
2069
2070   return send_file_complete (g);
2071 }
2072
2073 /* Send a chunk of file data. */
2074 static int
2075 send_file_data (guestfs_h *g, const char *buf, size_t len)
2076 {
2077   return send_file_chunk (g, 0, buf, len);
2078 }
2079
2080 /* Send a cancellation message. */
2081 static int
2082 send_file_cancellation (guestfs_h *g)
2083 {
2084   return send_file_chunk (g, 1, NULL, 0);
2085 }
2086
2087 /* Send a file complete chunk. */
2088 static int
2089 send_file_complete (guestfs_h *g)
2090 {
2091   char buf[1];
2092   return send_file_chunk (g, 0, buf, 0);
2093 }
2094
2095 static int
2096 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2097 {
2098   u_int32_t len;
2099   int r;
2100   guestfs_chunk chunk;
2101   XDR xdr;
2102   char *msg_out;
2103   size_t msg_out_size;
2104
2105   if (g->state != BUSY) {
2106     error (g, _("send_file_chunk: state %d != READY"), g->state);
2107     return -1;
2108   }
2109
2110   /* Allocate the chunk buffer.  Don't use the stack to avoid
2111    * excessive stack usage and unnecessary copies.
2112    */
2113   msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2114   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2115
2116   /* Serialize the chunk. */
2117   chunk.cancel = cancel;
2118   chunk.data.data_len = buflen;
2119   chunk.data.data_val = (char *) buf;
2120
2121   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2122     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2123            buf, buflen);
2124     xdr_destroy (&xdr);
2125     goto cleanup1;
2126   }
2127
2128   len = xdr_getpos (&xdr);
2129   xdr_destroy (&xdr);
2130
2131   /* Reduce the size of the outgoing message buffer to the real length. */
2132   msg_out = safe_realloc (g, msg_out, len + 4);
2133   msg_out_size = len + 4;
2134
2135   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2136   xdr_uint32_t (&xdr, &len);
2137
2138   r = send_to_daemon (g, msg_out, msg_out_size);
2139
2140   /* Did the daemon send a cancellation message? */
2141   if (r == -2) {
2142     if (g->verbose)
2143       fprintf (stderr, "got daemon cancellation\n");
2144     return -2;
2145   }
2146
2147   if (r == -1)
2148     goto cleanup1;
2149
2150   free (msg_out);
2151
2152   return 0;
2153
2154  cleanup1:
2155   free (msg_out);
2156   return -1;
2157 }
2158
2159 /* Receive a reply. */
2160 int
2161 guestfs___recv (guestfs_h *g, const char *fn,
2162                 guestfs_message_header *hdr,
2163                 guestfs_message_error *err,
2164                 xdrproc_t xdrp, char *ret)
2165 {
2166   XDR xdr;
2167   void *buf;
2168   uint32_t size;
2169   int r;
2170
2171  again:
2172   r = recv_from_daemon (g, &size, &buf);
2173   if (r == -1)
2174     return -1;
2175
2176   /* This can happen if a cancellation happens right at the end
2177    * of us sending a FileIn parameter to the daemon.  Discard.  The
2178    * daemon should send us an error message next.
2179    */
2180   if (size == GUESTFS_CANCEL_FLAG)
2181     goto again;
2182
2183   if (size == GUESTFS_LAUNCH_FLAG) {
2184     error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2185     return -1;
2186   }
2187
2188   xdrmem_create (&xdr, buf, size, XDR_DECODE);
2189
2190   if (!xdr_guestfs_message_header (&xdr, hdr)) {
2191     error (g, "%s: failed to parse reply header", fn);
2192     xdr_destroy (&xdr);
2193     free (buf);
2194     return -1;
2195   }
2196   if (hdr->status == GUESTFS_STATUS_ERROR) {
2197     if (!xdr_guestfs_message_error (&xdr, err)) {
2198       error (g, "%s: failed to parse reply error", fn);
2199       xdr_destroy (&xdr);
2200       free (buf);
2201       return -1;
2202     }
2203   } else {
2204     if (xdrp && ret && !xdrp (&xdr, ret)) {
2205       error (g, "%s: failed to parse reply", fn);
2206       xdr_destroy (&xdr);
2207       free (buf);
2208       return -1;
2209     }
2210   }
2211   xdr_destroy (&xdr);
2212   free (buf);
2213
2214   return 0;
2215 }
2216
2217 /* Receive a file. */
2218
2219 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2220 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2221
2222 int
2223 guestfs___recv_file (guestfs_h *g, const char *filename)
2224 {
2225   void *buf;
2226   int fd, r;
2227   size_t len;
2228
2229   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2230   if (fd == -1) {
2231     perrorf (g, "open: %s", filename);
2232     goto cancel;
2233   }
2234
2235   /* Receive the file in chunked encoding. */
2236   while ((r = receive_file_data (g, &buf)) > 0) {
2237     if (xwrite (fd, buf, r) == -1) {
2238       perrorf (g, "%s: write", filename);
2239       free (buf);
2240       goto cancel;
2241     }
2242     free (buf);
2243   }
2244
2245   if (r == -1) {
2246     error (g, _("%s: error in chunked encoding"), filename);
2247     return -1;
2248   }
2249
2250   if (close (fd) == -1) {
2251     perrorf (g, "close: %s", filename);
2252     return -1;
2253   }
2254
2255   return 0;
2256
2257  cancel: ;
2258   /* Send cancellation message to daemon, then wait until it
2259    * cancels (just throwing away data).
2260    */
2261   XDR xdr;
2262   char fbuf[4];
2263   uint32_t flag = GUESTFS_CANCEL_FLAG;
2264
2265   if (g->verbose)
2266     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2267              __func__);
2268
2269   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2270   xdr_uint32_t (&xdr, &flag);
2271   xdr_destroy (&xdr);
2272
2273   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2274     perrorf (g, _("write to daemon socket"));
2275     return -1;
2276   }
2277
2278   while (receive_file_data (g, NULL) > 0)
2279     ;                           /* just discard it */
2280
2281   return -1;
2282 }
2283
2284 /* Receive a chunk of file data. */
2285 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2286 static ssize_t
2287 receive_file_data (guestfs_h *g, void **buf_r)
2288 {
2289   int r;
2290   void *buf;
2291   uint32_t len;
2292   XDR xdr;
2293   guestfs_chunk chunk;
2294
2295   r = recv_from_daemon (g, &len, &buf);
2296   if (r == -1) {
2297     error (g, _("receive_file_data: parse error in reply callback"));
2298     return -1;
2299   }
2300
2301   if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2302     error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2303     return -1;
2304   }
2305
2306   memset (&chunk, 0, sizeof chunk);
2307
2308   xdrmem_create (&xdr, buf, len, XDR_DECODE);
2309   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2310     error (g, _("failed to parse file chunk"));
2311     free (buf);
2312     return -1;
2313   }
2314   xdr_destroy (&xdr);
2315   /* After decoding, the original buffer is no longer used. */
2316   free (buf);
2317
2318   if (chunk.cancel) {
2319     error (g, _("file receive cancelled by daemon"));
2320     free (chunk.data.data_val);
2321     return -1;
2322   }
2323
2324   if (chunk.data.data_len == 0) { /* end of transfer */
2325     free (chunk.data.data_val);
2326     return 0;
2327   }
2328
2329   if (buf_r) *buf_r = chunk.data.data_val;
2330   else free (chunk.data.data_val); /* else caller frees */
2331
2332   return chunk.data.data_len;
2333 }