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