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