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