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