If qemu dies during launch, set an error message (RHBZ#588851).
[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
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   if (strchr (filename, ',') != NULL) {
834     error (g, _("filename cannot contain ',' (comma) character"));
835     return -1;
836   }
837
838   if (access (filename, F_OK) == -1) {
839     perrorf (g, "%s", filename);
840     return -1;
841   }
842
843   if (qemu_supports (g, NULL) == -1)
844     return -1;
845
846   /* Only SCSI and virtio drivers support readonly mode.
847    * This is only supported as a QEMU feature since 2010/01.
848    */
849   int supports_ro = 0;
850   if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
851       qemu_supports (g, "readonly=on"))
852     supports_ro = 1;
853
854   size_t len = strlen (filename) + 100;
855   char buf[len];
856
857   snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
858             filename,
859             supports_ro ? "readonly=on," : "",
860             drive_if);
861
862   return guestfs__config (g, "-drive", buf);
863 }
864
865 int
866 guestfs__add_drive (guestfs_h *g, const char *filename)
867 {
868   return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
869 }
870
871 int
872 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
873 {
874   return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
875 }
876
877 int
878 guestfs__add_cdrom (guestfs_h *g, const char *filename)
879 {
880   if (strchr (filename, ',') != NULL) {
881     error (g, _("filename cannot contain ',' (comma) character"));
882     return -1;
883   }
884
885   if (access (filename, F_OK) == -1) {
886     perrorf (g, "%s", filename);
887     return -1;
888   }
889
890   return guestfs__config (g, "-cdrom", filename);
891 }
892
893 /* Returns true iff file is contained in dir. */
894 static int
895 dir_contains_file (const char *dir, const char *file)
896 {
897   int dirlen = strlen (dir);
898   int filelen = strlen (file);
899   int len = dirlen+filelen+2;
900   char path[len];
901
902   snprintf (path, len, "%s/%s", dir, file);
903   return access (path, F_OK) == 0;
904 }
905
906 /* Returns true iff every listed file is contained in 'dir'. */
907 static int
908 dir_contains_files (const char *dir, ...)
909 {
910   va_list args;
911   const char *file;
912
913   va_start (args, dir);
914   while ((file = va_arg (args, const char *)) != NULL) {
915     if (!dir_contains_file (dir, file)) {
916       va_end (args);
917       return 0;
918     }
919   }
920   va_end (args);
921   return 1;
922 }
923
924 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
925 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
926 static int is_openable (guestfs_h *g, const char *path, int flags);
927 static void print_cmdline (guestfs_h *g);
928
929 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
930 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
931 static const char *supermin_name =
932   "initramfs." REPO "." host_cpu ".supermin.img";
933 static const char *supermin_hostfiles_name =
934   "initramfs." REPO "." host_cpu ".supermin.hostfiles";
935
936 int
937 guestfs__launch (guestfs_h *g)
938 {
939   const char *tmpdir;
940   char dir_template[PATH_MAX];
941   int r, pmore;
942   size_t len;
943   int wfd[2], rfd[2];
944   int tries;
945   char *path, *pelem, *pend;
946   char *kernel = NULL, *initrd = NULL;
947   int null_vmchannel_sock;
948   char unixsock[256];
949   struct sockaddr_un addr;
950
951   /* Start the clock ... */
952   gettimeofday (&g->launch_t, NULL);
953
954 #ifdef P_tmpdir
955   tmpdir = P_tmpdir;
956 #else
957   tmpdir = "/tmp";
958 #endif
959
960   tmpdir = getenv ("TMPDIR") ? : tmpdir;
961   snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
962
963   /* Configured? */
964   if (!g->cmdline) {
965     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
966     return -1;
967   }
968
969   if (g->state != CONFIG) {
970     error (g, _("qemu has already been launched"));
971     return -1;
972   }
973
974   /* Make the temporary directory. */
975   if (!g->tmpdir) {
976     g->tmpdir = safe_strdup (g, dir_template);
977     if (mkdtemp (g->tmpdir) == NULL) {
978       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
979       goto cleanup0;
980     }
981   }
982
983   /* First search g->path for the supermin appliance, and try to
984    * synthesize a kernel and initrd from that.  If it fails, we
985    * try the path search again looking for a backup ordinary
986    * appliance.
987    */
988   pelem = path = safe_strdup (g, g->path);
989   do {
990     pend = strchrnul (pelem, ':');
991     pmore = *pend == ':';
992     *pend = '\0';
993     len = pend - pelem;
994
995     /* Empty element of "." means cwd. */
996     if (len == 0 || (len == 1 && *pelem == '.')) {
997       if (g->verbose)
998         fprintf (stderr,
999                  "looking for supermin appliance in current directory\n");
1000       if (dir_contains_files (".",
1001                               supermin_name, supermin_hostfiles_name,
1002                               "kmod.whitelist", NULL)) {
1003         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
1004           return -1;
1005         break;
1006       }
1007     }
1008     /* Look at <path>/supermin* etc. */
1009     else {
1010       if (g->verbose)
1011         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
1012
1013       if (dir_contains_files (pelem,
1014                               supermin_name, supermin_hostfiles_name,
1015                               "kmod.whitelist", NULL)) {
1016         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1017           return -1;
1018         break;
1019       }
1020     }
1021
1022     pelem = pend + 1;
1023   } while (pmore);
1024
1025   free (path);
1026
1027   if (kernel == NULL || initrd == NULL) {
1028     /* Search g->path for the kernel and initrd. */
1029     pelem = path = safe_strdup (g, g->path);
1030     do {
1031       pend = strchrnul (pelem, ':');
1032       pmore = *pend == ':';
1033       *pend = '\0';
1034       len = pend - pelem;
1035
1036       /* Empty element or "." means cwd. */
1037       if (len == 0 || (len == 1 && *pelem == '.')) {
1038         if (g->verbose)
1039           fprintf (stderr,
1040                    "looking for appliance in current directory\n");
1041         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1042           kernel = safe_strdup (g, kernel_name);
1043           initrd = safe_strdup (g, initrd_name);
1044           break;
1045         }
1046       }
1047       /* Look at <path>/kernel etc. */
1048       else {
1049         if (g->verbose)
1050           fprintf (stderr, "looking for appliance in %s\n", pelem);
1051
1052         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1053           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1054           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1055           sprintf (kernel, "%s/%s", pelem, kernel_name);
1056           sprintf (initrd, "%s/%s", pelem, initrd_name);
1057           break;
1058         }
1059       }
1060
1061       pelem = pend + 1;
1062     } while (pmore);
1063
1064     free (path);
1065   }
1066
1067   if (kernel == NULL || initrd == NULL) {
1068     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1069            kernel_name, initrd_name, g->path);
1070     goto cleanup0;
1071   }
1072
1073   if (g->verbose)
1074     print_timestamped_message (g, "begin testing qemu features");
1075
1076   /* Get qemu help text and version. */
1077   if (qemu_supports (g, NULL) == -1)
1078     goto cleanup0;
1079
1080   /* Choose which vmchannel implementation to use. */
1081   if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
1082     /* The "null vmchannel" implementation.  Requires SLIRP (user mode
1083      * networking in qemu) but no other vmchannel support.  The daemon
1084      * will connect back to a random port number on localhost.
1085      */
1086     struct sockaddr_in addr;
1087     socklen_t addrlen = sizeof addr;
1088
1089     g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1090     if (g->sock == -1) {
1091       perrorf (g, "socket");
1092       goto cleanup0;
1093     }
1094     addr.sin_family = AF_INET;
1095     addr.sin_port = htons (0);
1096     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1097     if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1098       perrorf (g, "bind");
1099       goto cleanup0;
1100     }
1101
1102     if (listen (g->sock, 256) == -1) {
1103       perrorf (g, "listen");
1104       goto cleanup0;
1105     }
1106
1107     if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1108       perrorf (g, "getsockname");
1109       goto cleanup0;
1110     }
1111
1112     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1113       perrorf (g, "fcntl");
1114       goto cleanup0;
1115     }
1116
1117     null_vmchannel_sock = ntohs (addr.sin_port);
1118     if (g->verbose)
1119       fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1120   } else {
1121     /* Using some vmchannel impl.  We need to create a local Unix
1122      * domain socket for qemu to use.
1123      */
1124     snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1125     unlink (unixsock);
1126     null_vmchannel_sock = 0;
1127   }
1128
1129   if (!g->direct) {
1130     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1131       perrorf (g, "pipe");
1132       goto cleanup0;
1133     }
1134   }
1135
1136   if (g->verbose)
1137     print_timestamped_message (g, "finished testing qemu features");
1138
1139   r = fork ();
1140   if (r == -1) {
1141     perrorf (g, "fork");
1142     if (!g->direct) {
1143       close (wfd[0]);
1144       close (wfd[1]);
1145       close (rfd[0]);
1146       close (rfd[1]);
1147     }
1148     goto cleanup0;
1149   }
1150
1151   if (r == 0) {                 /* Child (qemu). */
1152     char buf[256];
1153     const char *vmchannel = NULL;
1154
1155     /* Set up the full command line.  Do this in the subprocess so we
1156      * don't need to worry about cleaning up.
1157      */
1158     g->cmdline[0] = g->qemu;
1159
1160     /* qemu sometimes needs this option to enable hardware
1161      * virtualization, but some versions of 'qemu-kvm' will use KVM
1162      * regardless (even where this option appears in the help text).
1163      * It is rumoured that there are versions of qemu where supplying
1164      * this option when hardware virtualization is not available will
1165      * cause qemu to fail, so we we have to check at least that
1166      * /dev/kvm is openable.  That's not reliable, since /dev/kvm
1167      * might be openable by qemu but not by us (think: SELinux) in
1168      * which case the user would not get hardware virtualization,
1169      * although at least shouldn't fail.  A giant clusterfuck with the
1170      * qemu command line, again.
1171      */
1172     if (qemu_supports (g, "-enable-kvm") &&
1173         is_openable (g, "/dev/kvm", O_RDWR))
1174       add_cmdline (g, "-enable-kvm");
1175
1176     /* Newer versions of qemu (from around 2009/12) changed the
1177      * behaviour of monitors so that an implicit '-monitor stdio' is
1178      * assumed if we are in -nographic mode and there is no other
1179      * -monitor option.  Only a single stdio device is allowed, so
1180      * this broke the '-serial stdio' option.  There is a new flag
1181      * called -nodefaults which gets rid of all this default crud, so
1182      * let's use that to avoid this and any future surprises.
1183      */
1184     if (qemu_supports (g, "-nodefaults"))
1185       add_cmdline (g, "-nodefaults");
1186
1187     add_cmdline (g, "-nographic");
1188     add_cmdline (g, "-serial");
1189     add_cmdline (g, "stdio");
1190
1191     snprintf (buf, sizeof buf, "%d", g->memsize);
1192     add_cmdline (g, "-m");
1193     add_cmdline (g, buf);
1194
1195     /* Force exit instead of reboot on panic */
1196     add_cmdline (g, "-no-reboot");
1197
1198     /* These options recommended by KVM developers to improve reliability. */
1199     if (qemu_supports (g, "-no-hpet"))
1200       add_cmdline (g, "-no-hpet");
1201
1202     if (qemu_supports (g, "-rtc-td-hack"))
1203       add_cmdline (g, "-rtc-td-hack");
1204
1205     /* If qemu has SLIRP (user mode network) enabled then we can get
1206      * away with "no vmchannel", where we just connect back to a random
1207      * host port.
1208      */
1209     if (null_vmchannel_sock) {
1210       add_cmdline (g, "-net");
1211       add_cmdline (g, "user,vlan=0,net=" NETWORK);
1212
1213       snprintf (buf, sizeof buf,
1214                 "guestfs_vmchannel=tcp:" ROUTER ":%d",
1215                 null_vmchannel_sock);
1216       vmchannel = strdup (buf);
1217     }
1218
1219     /* New-style -net user,guestfwd=... syntax for guestfwd.  See:
1220      *
1221      * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1222      *
1223      * The original suggested format doesn't work, see:
1224      *
1225      * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1226      *
1227      * However Gerd Hoffman privately suggested to me using -chardev
1228      * instead, which does work.
1229      */
1230     else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1231       snprintf (buf, sizeof buf,
1232                 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1233
1234       add_cmdline (g, "-chardev");
1235       add_cmdline (g, buf);
1236
1237       snprintf (buf, sizeof buf,
1238                 "user,vlan=0,net=" NETWORK ","
1239                 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1240                 "-chardev:guestfsvmc");
1241
1242       add_cmdline (g, "-net");
1243       add_cmdline (g, buf);
1244
1245       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1246     }
1247
1248     /* Not guestfwd.  HOPEFULLY this qemu uses the older -net channel
1249      * syntax, or if not then we'll get a quick failure.
1250      */
1251     else {
1252       snprintf (buf, sizeof buf,
1253                 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1254
1255       add_cmdline (g, "-net");
1256       add_cmdline (g, buf);
1257       add_cmdline (g, "-net");
1258       add_cmdline (g, "user,vlan=0,net=" NETWORK);
1259
1260       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1261     }
1262     add_cmdline (g, "-net");
1263     add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1264
1265 #define LINUX_CMDLINE                                                   \
1266     "panic=1 "         /* force kernel to panic if daemon exits */      \
1267     "console=ttyS0 "   /* serial console */                             \
1268     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
1269     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
1270     "acpi=off "        /* we don't need ACPI, turn it off */            \
1271     "printk.time=1 "   /* display timestamp before kernel messages */   \
1272     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1273
1274     /* Linux kernel command line. */
1275     snprintf (buf, sizeof buf,
1276               LINUX_CMDLINE
1277               "%s "             /* (selinux) */
1278               "%s "             /* (vmchannel) */
1279               "%s "             /* (verbose) */
1280               "TERM=%s "        /* (TERM environment variable) */
1281               "%s",             /* (append) */
1282               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1283               vmchannel ? vmchannel : "",
1284               g->verbose ? "guestfs_verbose=1" : "",
1285               getenv ("TERM") ? : "linux",
1286               g->append ? g->append : "");
1287
1288     add_cmdline (g, "-kernel");
1289     add_cmdline (g, (char *) kernel);
1290     add_cmdline (g, "-initrd");
1291     add_cmdline (g, (char *) initrd);
1292     add_cmdline (g, "-append");
1293     add_cmdline (g, buf);
1294
1295     /* Finish off the command line. */
1296     incr_cmdline_size (g);
1297     g->cmdline[g->cmdline_size-1] = NULL;
1298
1299     if (g->verbose)
1300       print_cmdline (g);
1301
1302     if (!g->direct) {
1303       /* Set up stdin, stdout. */
1304       close (0);
1305       close (1);
1306       close (wfd[1]);
1307       close (rfd[0]);
1308
1309       if (dup (wfd[0]) == -1) {
1310       dup_failed:
1311         perror ("dup failed");
1312         _exit (EXIT_FAILURE);
1313       }
1314       if (dup (rfd[1]) == -1)
1315         goto dup_failed;
1316
1317       close (wfd[0]);
1318       close (rfd[1]);
1319     }
1320
1321 #if 0
1322     /* Set up a new process group, so we can signal this process
1323      * and all subprocesses (eg. if qemu is really a shell script).
1324      */
1325     setpgid (0, 0);
1326 #endif
1327
1328     setenv ("LC_ALL", "C", 1);
1329
1330     execv (g->qemu, g->cmdline); /* Run qemu. */
1331     perror (g->qemu);
1332     _exit (EXIT_FAILURE);
1333   }
1334
1335   /* Parent (library). */
1336   g->pid = r;
1337
1338   free (kernel);
1339   kernel = NULL;
1340   free (initrd);
1341   initrd = NULL;
1342
1343   /* Fork the recovery process off which will kill qemu if the parent
1344    * process fails to do so (eg. if the parent segfaults).
1345    */
1346   g->recoverypid = -1;
1347   if (g->recovery_proc) {
1348     r = fork ();
1349     if (r == 0) {
1350       pid_t qemu_pid = g->pid;
1351       pid_t parent_pid = getppid ();
1352
1353       /* Writing to argv is hideously complicated and error prone.  See:
1354        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1355        */
1356
1357       /* Loop around waiting for one or both of the other processes to
1358        * disappear.  It's fair to say this is very hairy.  The PIDs that
1359        * we are looking at might be reused by another process.  We are
1360        * effectively polling.  Is the cure worse than the disease?
1361        */
1362       for (;;) {
1363         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1364           _exit (EXIT_SUCCESS);
1365         if (kill (parent_pid, 0) == -1) {
1366           /* Parent's gone away, qemu still around, so kill qemu. */
1367           kill (qemu_pid, 9);
1368           _exit (EXIT_SUCCESS);
1369         }
1370         sleep (2);
1371       }
1372     }
1373
1374     /* Don't worry, if the fork failed, this will be -1.  The recovery
1375      * process isn't essential.
1376      */
1377     g->recoverypid = r;
1378   }
1379
1380   if (!g->direct) {
1381     /* Close the other ends of the pipe. */
1382     close (wfd[0]);
1383     close (rfd[1]);
1384
1385     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1386         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1387       perrorf (g, "fcntl");
1388       goto cleanup1;
1389     }
1390
1391     g->fd[0] = wfd[1];          /* stdin of child */
1392     g->fd[1] = rfd[0];          /* stdout of child */
1393   } else {
1394     g->fd[0] = open ("/dev/null", O_RDWR);
1395     if (g->fd[0] == -1) {
1396       perrorf (g, "open /dev/null");
1397       goto cleanup1;
1398     }
1399     g->fd[1] = dup (g->fd[0]);
1400     if (g->fd[1] == -1) {
1401       perrorf (g, "dup");
1402       close (g->fd[0]);
1403       goto cleanup1;
1404     }
1405   }
1406
1407   if (null_vmchannel_sock) {
1408     int sock = -1;
1409     uid_t uid;
1410
1411     /* Null vmchannel implementation: We listen on g->sock for a
1412      * connection.  The connection could come from any local process
1413      * so we must check it comes from the appliance (or at least
1414      * from our UID) for security reasons.
1415      */
1416     while (sock == -1) {
1417       sock = accept_from_daemon (g);
1418       if (sock == -1)
1419         goto cleanup1;
1420
1421       if (check_peer_euid (g, sock, &uid) == -1)
1422         goto cleanup1;
1423       if (uid != geteuid ()) {
1424         fprintf (stderr,
1425                  "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1426                  uid, null_vmchannel_sock);
1427         close (sock);
1428         sock = -1;
1429         continue;
1430       }
1431     }
1432
1433     if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1434       perrorf (g, "fcntl");
1435       goto cleanup1;
1436     }
1437
1438     close (g->sock);
1439     g->sock = sock;
1440   } else {
1441     /* Other vmchannel.  Open the Unix socket.
1442      *
1443      * The vmchannel implementation that got merged with qemu sucks in
1444      * a number of ways.  Both ends do connect(2), which means that no
1445      * one knows what, if anything, is connected to the other end, or
1446      * if it becomes disconnected.  Even worse, we have to wait some
1447      * indeterminate time for qemu to create the socket and connect to
1448      * it (which happens very early in qemu's start-up), so any code
1449      * that uses vmchannel is inherently racy.  Hence this silly loop.
1450      */
1451     g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1452     if (g->sock == -1) {
1453       perrorf (g, "socket");
1454       goto cleanup1;
1455     }
1456
1457     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1458       perrorf (g, "fcntl");
1459       goto cleanup1;
1460     }
1461
1462     addr.sun_family = AF_UNIX;
1463     strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1464     addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1465
1466     tries = 100;
1467     /* Always sleep at least once to give qemu a small chance to start up. */
1468     usleep (10000);
1469     while (tries > 0) {
1470       r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1471       if ((r == -1 && errno == EINPROGRESS) || r == 0)
1472         goto connected;
1473
1474       if (errno != ENOENT)
1475         perrorf (g, "connect");
1476       tries--;
1477       usleep (100000);
1478     }
1479
1480     error (g, _("failed to connect to vmchannel socket"));
1481     goto cleanup1;
1482
1483   connected: ;
1484   }
1485
1486   g->state = LAUNCHING;
1487
1488   /* Wait for qemu to start and to connect back to us via vmchannel and
1489    * send the GUESTFS_LAUNCH_FLAG message.
1490    */
1491   uint32_t size;
1492   void *buf = NULL;
1493   r = recv_from_daemon (g, &size, &buf);
1494   free (buf);
1495
1496   if (r == -1) return -1;
1497
1498   if (size != GUESTFS_LAUNCH_FLAG) {
1499     error (g, _("guestfs_launch failed, see earlier error messages"));
1500     goto cleanup1;
1501   }
1502
1503   if (g->verbose)
1504     print_timestamped_message (g, "appliance is up");
1505
1506   /* This is possible in some really strange situations, such as
1507    * guestfsd starts up OK but then qemu immediately exits.  Check for
1508    * it because the caller is probably expecting to be able to send
1509    * commands after this function returns.
1510    */
1511   if (g->state != READY) {
1512     error (g, _("qemu launched and contacted daemon, but state != READY"));
1513     goto cleanup1;
1514   }
1515
1516   return 0;
1517
1518  cleanup1:
1519   if (!g->direct) {
1520     close (wfd[1]);
1521     close (rfd[0]);
1522   }
1523   if (g->pid > 0) kill (g->pid, 9);
1524   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1525   waitpid (g->pid, NULL, 0);
1526   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1527   g->fd[0] = -1;
1528   g->fd[1] = -1;
1529   g->pid = 0;
1530   g->recoverypid = 0;
1531   memset (&g->launch_t, 0, sizeof g->launch_t);
1532
1533  cleanup0:
1534   if (g->sock >= 0) {
1535     close (g->sock);
1536     g->sock = -1;
1537   }
1538   g->state = CONFIG;
1539   free (kernel);
1540   free (initrd);
1541   return -1;
1542 }
1543
1544 /* This function is used to print the qemu command line before it gets
1545  * executed, when in verbose mode.
1546  */
1547 static void
1548 print_cmdline (guestfs_h *g)
1549 {
1550   int i = 0;
1551   int needs_quote;
1552
1553   while (g->cmdline[i]) {
1554     if (g->cmdline[i][0] == '-') /* -option starts a new line */
1555       fprintf (stderr, " \\\n   ");
1556
1557     if (i > 0) fputc (' ', stderr);
1558
1559     /* Does it need shell quoting?  This only deals with simple cases. */
1560     needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1561
1562     if (needs_quote) fputc ('\'', stderr);
1563     fprintf (stderr, "%s", g->cmdline[i]);
1564     if (needs_quote) fputc ('\'', stderr);
1565     i++;
1566   }
1567
1568   fputc ('\n', stderr);
1569 }
1570
1571 /* This function does the hard work of building the supermin appliance
1572  * on the fly.  'path' is the directory containing the control files.
1573  * 'kernel' and 'initrd' are where we will return the names of the
1574  * kernel and initrd (only initrd is built).  The work is done by
1575  * an external script.  We just tell it where to put the result.
1576  */
1577 static int
1578 build_supermin_appliance (guestfs_h *g, const char *path,
1579                           char **kernel, char **initrd)
1580 {
1581   char cmd[4096];
1582   int r, len;
1583
1584   if (g->verbose)
1585     print_timestamped_message (g, "begin building supermin appliance");
1586
1587   len = strlen (g->tmpdir);
1588   *kernel = safe_malloc (g, len + 8);
1589   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1590   *initrd = safe_malloc (g, len + 8);
1591   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1592
1593   snprintf (cmd, sizeof cmd,
1594             "PATH='%s':$PATH "
1595             "libguestfs-supermin-helper%s '%s' " host_cpu " " REPO " %s %s",
1596             path,
1597             g->verbose ? " --verbose" : "",
1598             path, *kernel, *initrd);
1599   if (g->verbose)
1600     print_timestamped_message (g, "%s", cmd);
1601
1602   r = system (cmd);
1603   if (r == -1 || WEXITSTATUS(r) != 0) {
1604     error (g, _("external command failed: %s"), cmd);
1605     free (*kernel);
1606     free (*initrd);
1607     *kernel = *initrd = NULL;
1608     return -1;
1609   }
1610
1611   if (g->verbose)
1612     print_timestamped_message (g, "finished building supermin appliance");
1613
1614   return 0;
1615 }
1616
1617 /* Compute Y - X and return the result in milliseconds.
1618  * Approximately the same as this code:
1619  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1620  */
1621 static int64_t
1622 timeval_diff (const struct timeval *x, const struct timeval *y)
1623 {
1624   int64_t msec;
1625
1626   msec = (y->tv_sec - x->tv_sec) * 1000;
1627   msec += (y->tv_usec - x->tv_usec) / 1000;
1628   return msec;
1629 }
1630
1631 static void
1632 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1633 {
1634   va_list args;
1635   char *msg;
1636   int err;
1637   struct timeval tv;
1638
1639   va_start (args, fs);
1640   err = vasprintf (&msg, fs, args);
1641   va_end (args);
1642
1643   if (err < 0) return;
1644
1645   gettimeofday (&tv, NULL);
1646
1647   fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1648            timeval_diff (&g->launch_t, &tv), msg);
1649
1650   free (msg);
1651 }
1652
1653 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1654
1655 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1656  * 'qemu -version' so we know what options this qemu supports and
1657  * the version.
1658  */
1659 static int
1660 test_qemu (guestfs_h *g)
1661 {
1662   char cmd[1024];
1663   FILE *fp;
1664
1665   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1666
1667   fp = popen (cmd, "r");
1668   /* qemu -help should always work (qemu -version OTOH wasn't
1669    * supported by qemu 0.9).  If this command doesn't work then it
1670    * probably indicates that the qemu binary is missing.
1671    */
1672   if (!fp) {
1673     /* XXX This error is never printed, even if the qemu binary
1674      * doesn't exist.  Why?
1675      */
1676   error:
1677     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1678     return -1;
1679   }
1680
1681   if (read_all (g, fp, &g->qemu_help) == -1)
1682     goto error;
1683
1684   if (pclose (fp) == -1)
1685     goto error;
1686
1687   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1688             g->qemu);
1689
1690   fp = popen (cmd, "r");
1691   if (fp) {
1692     /* Intentionally ignore errors. */
1693     read_all (g, fp, &g->qemu_version);
1694     pclose (fp);
1695   }
1696
1697   return 0;
1698 }
1699
1700 static int
1701 read_all (guestfs_h *g, FILE *fp, char **ret)
1702 {
1703   int r, n = 0;
1704   char *p;
1705
1706  again:
1707   if (feof (fp)) {
1708     *ret = safe_realloc (g, *ret, n + 1);
1709     (*ret)[n] = '\0';
1710     return n;
1711   }
1712
1713   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1714   p = &(*ret)[n];
1715   r = fread (p, 1, BUFSIZ, fp);
1716   if (ferror (fp)) {
1717     perrorf (g, "read");
1718     return -1;
1719   }
1720   n += r;
1721   goto again;
1722 }
1723
1724 /* Test if option is supported by qemu command line (just by grepping
1725  * the help text).
1726  *
1727  * The first time this is used, it has to run the external qemu
1728  * binary.  If that fails, it returns -1.
1729  *
1730  * To just do the first-time run of the qemu binary, call this with
1731  * option == NULL, in which case it will return -1 if there was an
1732  * error doing that.
1733  */
1734 static int
1735 qemu_supports (guestfs_h *g, const char *option)
1736 {
1737   if (!g->qemu_help) {
1738     if (test_qemu (g) == -1)
1739       return -1;
1740   }
1741
1742   if (option == NULL)
1743     return 1;
1744
1745   return strstr (g->qemu_help, option) != NULL;
1746 }
1747
1748 /* Check if a file can be opened. */
1749 static int
1750 is_openable (guestfs_h *g, const char *path, int flags)
1751 {
1752   int fd = open (path, flags);
1753   if (fd == -1) {
1754     if (g->verbose)
1755       perror (path);
1756     return 0;
1757   }
1758   close (fd);
1759   return 1;
1760 }
1761
1762 /* Check the peer effective UID for a TCP socket.  Ideally we'd like
1763  * SO_PEERCRED for a loopback TCP socket.  This isn't possible on
1764  * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1765  */
1766 static int
1767 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1768 {
1769 #if CAN_CHECK_PEER_EUID
1770   struct sockaddr_in peer;
1771   socklen_t addrlen = sizeof peer;
1772
1773   if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1774     perrorf (g, "getpeername");
1775     return -1;
1776   }
1777
1778   if (peer.sin_family != AF_INET ||
1779       ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1780     error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1781            peer.sin_family, inet_ntoa (peer.sin_addr));
1782     return -1;
1783   }
1784
1785   struct sockaddr_in our;
1786   addrlen = sizeof our;
1787   if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1788     perrorf (g, "getsockname");
1789     return -1;
1790   }
1791
1792   FILE *fp = fopen ("/proc/net/tcp", "r");
1793   if (fp == NULL) {
1794     perrorf (g, "/proc/net/tcp");
1795     return -1;
1796   }
1797
1798   char line[256];
1799   if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1800     error (g, "unexpected end of file in /proc/net/tcp");
1801     fclose (fp);
1802     return -1;
1803   }
1804
1805   while (fgets (line, sizeof line, fp) != NULL) {
1806     unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1807     int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1808     int line_uid;
1809
1810     if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1811                 &dummy0,
1812                 &line_our_addr, &line_our_port,
1813                 &line_peer_addr, &line_peer_port,
1814                 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1815                 &line_uid) == 12) {
1816       /* Note about /proc/net/tcp: local_address and rem_address are
1817        * always in network byte order.  However the port part is
1818        * always in host byte order.
1819        *
1820        * The sockname and peername that we got above are in network
1821        * byte order.  So we have to byte swap the port but not the
1822        * address part.
1823        */
1824       if (line_our_addr == our.sin_addr.s_addr &&
1825           line_our_port == ntohs (our.sin_port) &&
1826           line_peer_addr == peer.sin_addr.s_addr &&
1827           line_peer_port == ntohs (peer.sin_port)) {
1828         *rtn = line_uid;
1829         fclose (fp);
1830         return 0;
1831       }
1832     }
1833   }
1834
1835   error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1836   fclose (fp);
1837   return -1;
1838 #else /* !CAN_CHECK_PEER_EUID */
1839   /* This function exists but should never be called in this
1840    * configuration.
1841    */
1842   abort ();
1843 #endif /* !CAN_CHECK_PEER_EUID */
1844 }
1845
1846 /* You had to call this function after launch in versions <= 1.0.70,
1847  * but it is now a no-op.
1848  */
1849 int
1850 guestfs__wait_ready (guestfs_h *g)
1851 {
1852   if (g->state != READY)  {
1853     error (g, _("qemu has not been launched yet"));
1854     return -1;
1855   }
1856
1857   return 0;
1858 }
1859
1860 int
1861 guestfs__kill_subprocess (guestfs_h *g)
1862 {
1863   if (g->state == CONFIG) {
1864     error (g, _("no subprocess to kill"));
1865     return -1;
1866   }
1867
1868   if (g->verbose)
1869     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1870
1871   if (g->pid > 0) kill (g->pid, SIGTERM);
1872   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1873
1874   return 0;
1875 }
1876
1877 /* Access current state. */
1878 int
1879 guestfs__is_config (guestfs_h *g)
1880 {
1881   return g->state == CONFIG;
1882 }
1883
1884 int
1885 guestfs__is_launching (guestfs_h *g)
1886 {
1887   return g->state == LAUNCHING;
1888 }
1889
1890 int
1891 guestfs__is_ready (guestfs_h *g)
1892 {
1893   return g->state == READY;
1894 }
1895
1896 int
1897 guestfs__is_busy (guestfs_h *g)
1898 {
1899   return g->state == BUSY;
1900 }
1901
1902 int
1903 guestfs__get_state (guestfs_h *g)
1904 {
1905   return g->state;
1906 }
1907
1908 void
1909 guestfs_set_log_message_callback (guestfs_h *g,
1910                                   guestfs_log_message_cb cb, void *opaque)
1911 {
1912   g->log_message_cb = cb;
1913   g->log_message_cb_data = opaque;
1914 }
1915
1916 void
1917 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1918                                       guestfs_subprocess_quit_cb cb, void *opaque)
1919 {
1920   g->subprocess_quit_cb = cb;
1921   g->subprocess_quit_cb_data = opaque;
1922 }
1923
1924 void
1925 guestfs_set_launch_done_callback (guestfs_h *g,
1926                                   guestfs_launch_done_cb cb, void *opaque)
1927 {
1928   g->launch_done_cb = cb;
1929   g->launch_done_cb_data = opaque;
1930 }
1931
1932 /*----------------------------------------------------------------------*/
1933
1934 /* This is the code used to send and receive RPC messages and (for
1935  * certain types of message) to perform file transfers.  This code is
1936  * driven from the generated actions (src/guestfs-actions.c).  There
1937  * are five different cases to consider:
1938  *
1939  * (1) A non-daemon function.  There is no RPC involved at all, it's
1940  * all handled inside the library.
1941  *
1942  * (2) A simple RPC (eg. "mount").  We write the request, then read
1943  * the reply.  The sequence of calls is:
1944  *
1945  *   guestfs___set_busy
1946  *   guestfs___send
1947  *   guestfs___recv
1948  *   guestfs___end_busy
1949  *
1950  * (3) An RPC with FileOut parameters (eg. "upload").  We write the
1951  * request, then write the file(s), then read the reply.  The sequence
1952  * of calls is:
1953  *
1954  *   guestfs___set_busy
1955  *   guestfs___send
1956  *   guestfs___send_file  (possibly multiple times)
1957  *   guestfs___recv
1958  *   guestfs___end_busy
1959  *
1960  * (4) An RPC with FileIn parameters (eg. "download").  We write the
1961  * request, then read the reply, then read the file(s).  The sequence
1962  * of calls is:
1963  *
1964  *   guestfs___set_busy
1965  *   guestfs___send
1966  *   guestfs___recv
1967  *   guestfs___recv_file  (possibly multiple times)
1968  *   guestfs___end_busy
1969  *
1970  * (5) Both FileOut and FileIn parameters.  There are no calls like
1971  * this in the current API, but they would be implemented as a
1972  * combination of cases (3) and (4).
1973  *
1974  * During all writes and reads, we also select(2) on qemu stdout
1975  * looking for messages (guestfsd stderr and guest kernel dmesg), and
1976  * anything received is passed up through the log_message_cb.  This is
1977  * also the reason why all the sockets are non-blocking.  We also have
1978  * to check for EOF (qemu died).  All of this is handled by the
1979  * functions send_to_daemon and recv_from_daemon.
1980  */
1981
1982 int
1983 guestfs___set_busy (guestfs_h *g)
1984 {
1985   if (g->state != READY) {
1986     error (g, _("guestfs_set_busy: called when in state %d != READY"),
1987            g->state);
1988     return -1;
1989   }
1990   g->state = BUSY;
1991   return 0;
1992 }
1993
1994 int
1995 guestfs___end_busy (guestfs_h *g)
1996 {
1997   switch (g->state)
1998     {
1999     case BUSY:
2000       g->state = READY;
2001       break;
2002     case CONFIG:
2003     case READY:
2004       break;
2005
2006     case LAUNCHING:
2007     case NO_HANDLE:
2008     default:
2009       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
2010       return -1;
2011     }
2012   return 0;
2013 }
2014
2015 /* This is called if we detect EOF, ie. qemu died. */
2016 static void
2017 child_cleanup (guestfs_h *g)
2018 {
2019   if (g->verbose)
2020     fprintf (stderr, "child_cleanup: %p: child process died\n", g);
2021
2022   /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
2023   if (g->recoverypid > 0) kill (g->recoverypid, 9);
2024   waitpid (g->pid, NULL, 0);
2025   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
2026   close (g->fd[0]);
2027   close (g->fd[1]);
2028   close (g->sock);
2029   g->fd[0] = -1;
2030   g->fd[1] = -1;
2031   g->sock = -1;
2032   g->pid = 0;
2033   g->recoverypid = 0;
2034   memset (&g->launch_t, 0, sizeof g->launch_t);
2035   g->state = CONFIG;
2036   if (g->subprocess_quit_cb)
2037     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
2038 }
2039
2040 static int
2041 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
2042 {
2043   char buf[BUFSIZ];
2044   int n;
2045
2046 #if 0
2047   if (g->verbose)
2048     fprintf (stderr,
2049              "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2050              g, g->state, fd);
2051 #endif
2052
2053   /* QEMU's console emulates a 16550A serial port.  The real 16550A
2054    * device has a small FIFO buffer (16 bytes) which means here we see
2055    * lots of small reads of 1-16 bytes in length, usually single
2056    * bytes.
2057    */
2058   n = read (fd, buf, sizeof buf);
2059   if (n == 0) {
2060     /* Hopefully this indicates the qemu child process has died. */
2061     child_cleanup (g);
2062
2063     if (error_if_eof) {
2064       /* We weren't expecting eof here (called from launch) so place
2065        * something in the error buffer.  RHBZ#588851.
2066        */
2067       error (g, "child process died unexpectedly");
2068     }
2069     return -1;
2070   }
2071
2072   if (n == -1) {
2073     if (errno == EINTR || errno == EAGAIN)
2074       return 0;
2075
2076     perrorf (g, "read");
2077     return -1;
2078   }
2079
2080   /* In verbose mode, copy all log messages to stderr. */
2081   if (g->verbose)
2082     ignore_value (write (STDERR_FILENO, buf, n));
2083
2084   /* It's an actual log message, send it upwards if anyone is listening. */
2085   if (g->log_message_cb)
2086     g->log_message_cb (g, g->log_message_cb_data, buf, n);
2087
2088   return 0;
2089 }
2090
2091 static int
2092 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2093 {
2094   char buf[4];
2095   int n;
2096   uint32_t flag;
2097   XDR xdr;
2098
2099   if (g->verbose)
2100     fprintf (stderr,
2101              "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2102              g, g->state, fd);
2103
2104   n = read (fd, buf, 4);
2105   if (n == 0) {
2106     /* Hopefully this indicates the qemu child process has died. */
2107     child_cleanup (g);
2108     return -1;
2109   }
2110
2111   if (n == -1) {
2112     if (errno == EINTR || errno == EAGAIN)
2113       return 0;
2114
2115     perrorf (g, "read");
2116     return -1;
2117   }
2118
2119   xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2120   xdr_uint32_t (&xdr, &flag);
2121   xdr_destroy (&xdr);
2122
2123   if (flag != GUESTFS_CANCEL_FLAG) {
2124     error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2125            flag, GUESTFS_CANCEL_FLAG);
2126     return -1;
2127   }
2128
2129   return -2;
2130 }
2131
2132 /* This writes the whole N bytes of BUF to the daemon socket.
2133  *
2134  * If the whole write is successful, it returns 0.
2135  * If there was an error, it returns -1.
2136  * If the daemon sent a cancellation message, it returns -2.
2137  *
2138  * It also checks qemu stdout for log messages and passes those up
2139  * through log_message_cb.
2140  *
2141  * It also checks for EOF (qemu died) and passes that up through the
2142  * child_cleanup function above.
2143  */
2144 static int
2145 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2146 {
2147   const char *buf = v_buf;
2148   fd_set rset, rset2;
2149   fd_set wset, wset2;
2150
2151   if (g->verbose)
2152     fprintf (stderr,
2153              "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2154
2155   FD_ZERO (&rset);
2156   FD_ZERO (&wset);
2157
2158   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
2159   FD_SET (g->sock, &rset);      /* Read socket for cancellation & EOF. */
2160   FD_SET (g->sock, &wset);      /* Write to socket to send the data. */
2161
2162   int max_fd = MAX (g->sock, g->fd[1]);
2163
2164   while (n > 0) {
2165     rset2 = rset;
2166     wset2 = wset;
2167     int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2168     if (r == -1) {
2169       if (errno == EINTR || errno == EAGAIN)
2170         continue;
2171       perrorf (g, "select");
2172       return -1;
2173     }
2174
2175     if (FD_ISSET (g->fd[1], &rset2)) {
2176       if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
2177         return -1;
2178     }
2179     if (FD_ISSET (g->sock, &rset2)) {
2180       r = check_for_daemon_cancellation_or_eof (g, g->sock);
2181       if (r < 0)
2182         return r;
2183     }
2184     if (FD_ISSET (g->sock, &wset2)) {
2185       r = write (g->sock, buf, n);
2186       if (r == -1) {
2187         if (errno == EINTR || errno == EAGAIN)
2188           continue;
2189         perrorf (g, "write");
2190         if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2191           child_cleanup (g);
2192         return -1;
2193       }
2194       buf += r;
2195       n -= r;
2196     }
2197   }
2198
2199   return 0;
2200 }
2201
2202 /* This reads a single message, file chunk, launch flag or
2203  * cancellation flag from the daemon.  If something was read, it
2204  * returns 0, otherwise -1.
2205  *
2206  * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2207  *
2208  * *size_rtn returns the size of the returned message or it may be
2209  * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2210  *
2211  * *buf_rtn is returned containing the message (if any) or will be set
2212  * to NULL.  *buf_rtn must be freed by the caller.
2213  *
2214  * It also checks qemu stdout for log messages and passes those up
2215  * through log_message_cb.
2216  *
2217  * It also checks for EOF (qemu died) and passes that up through the
2218  * child_cleanup function above.
2219  */
2220 static int
2221 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2222 {
2223   fd_set rset, rset2;
2224
2225   if (g->verbose)
2226     fprintf (stderr,
2227              "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2228              g, g->state, size_rtn, buf_rtn);
2229
2230   FD_ZERO (&rset);
2231
2232   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
2233   FD_SET (g->sock, &rset);      /* Read socket for data & EOF. */
2234
2235   int max_fd = MAX (g->sock, g->fd[1]);
2236
2237   *size_rtn = 0;
2238   *buf_rtn = NULL;
2239
2240   char lenbuf[4];
2241   /* nr is the size of the message, but we prime it as -4 because we
2242    * have to read the message length word first.
2243    */
2244   ssize_t nr = -4;
2245
2246   while (nr < (ssize_t) *size_rtn) {
2247     rset2 = rset;
2248     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2249     if (r == -1) {
2250       if (errno == EINTR || errno == EAGAIN)
2251         continue;
2252       perrorf (g, "select");
2253       free (*buf_rtn);
2254       *buf_rtn = NULL;
2255       return -1;
2256     }
2257
2258     if (FD_ISSET (g->fd[1], &rset2)) {
2259       if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
2260         free (*buf_rtn);
2261         *buf_rtn = NULL;
2262         return -1;
2263       }
2264     }
2265     if (FD_ISSET (g->sock, &rset2)) {
2266       if (nr < 0) {    /* Have we read the message length word yet? */
2267         r = read (g->sock, lenbuf+nr+4, -nr);
2268         if (r == -1) {
2269           if (errno == EINTR || errno == EAGAIN)
2270             continue;
2271           int err = errno;
2272           perrorf (g, "read");
2273           /* Under some circumstances we see "Connection reset by peer"
2274            * here when the child dies suddenly.  Catch this and call
2275            * the cleanup function, same as for EOF.
2276            */
2277           if (err == ECONNRESET)
2278             child_cleanup (g);
2279           return -1;
2280         }
2281         if (r == 0) {
2282           error (g, _("unexpected end of file when reading from daemon"));
2283           child_cleanup (g);
2284           return -1;
2285         }
2286         nr += r;
2287
2288         if (nr < 0)         /* Still not got the whole length word. */
2289           continue;
2290
2291         XDR xdr;
2292         xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2293         xdr_uint32_t (&xdr, size_rtn);
2294         xdr_destroy (&xdr);
2295
2296         if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2297           if (g->state != LAUNCHING)
2298             error (g, _("received magic signature from guestfsd, but in state %d"),
2299                    g->state);
2300           else {
2301             g->state = READY;
2302             if (g->launch_done_cb)
2303               g->launch_done_cb (g, g->launch_done_cb_data);
2304           }
2305           return 0;
2306         }
2307         else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2308           return 0;
2309         /* If this happens, it's pretty bad and we've probably lost
2310          * synchronization.
2311          */
2312         else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2313           error (g, _("message length (%u) > maximum possible size (%d)"),
2314                  (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2315           return -1;
2316         }
2317
2318         /* Allocate the complete buffer, size now known. */
2319         *buf_rtn = safe_malloc (g, *size_rtn);
2320         /*FALLTHROUGH*/
2321       }
2322
2323       size_t sizetoread = *size_rtn - nr;
2324       if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2325
2326       r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2327       if (r == -1) {
2328         if (errno == EINTR || errno == EAGAIN)
2329           continue;
2330         perrorf (g, "read");
2331         free (*buf_rtn);
2332         *buf_rtn = NULL;
2333         return -1;
2334       }
2335       if (r == 0) {
2336         error (g, _("unexpected end of file when reading from daemon"));
2337         child_cleanup (g);
2338         free (*buf_rtn);
2339         *buf_rtn = NULL;
2340         return -1;
2341       }
2342       nr += r;
2343     }
2344   }
2345
2346   /* Got the full message, caller can start processing it. */
2347 #ifdef ENABLE_PACKET_DUMP
2348   if (g->verbose) {
2349     ssize_t i, j;
2350
2351     for (i = 0; i < nr; i += 16) {
2352       printf ("%04zx: ", i);
2353       for (j = i; j < MIN (i+16, nr); ++j)
2354         printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2355       for (; j < i+16; ++j)
2356         printf ("   ");
2357       printf ("|");
2358       for (j = i; j < MIN (i+16, nr); ++j)
2359         if (c_isprint ((*(char **)buf_rtn)[j]))
2360           printf ("%c", (*(char **)buf_rtn)[j]);
2361         else
2362           printf (".");
2363       for (; j < i+16; ++j)
2364         printf (" ");
2365       printf ("|\n");
2366     }
2367   }
2368 #endif
2369
2370   return 0;
2371 }
2372
2373 /* This is very much like recv_from_daemon above, but g->sock is
2374  * a listening socket and we are accepting a new connection on
2375  * that socket instead of reading anything.  Returns the newly
2376  * accepted socket.
2377  */
2378 static int
2379 accept_from_daemon (guestfs_h *g)
2380 {
2381   fd_set rset, rset2;
2382
2383   if (g->verbose)
2384     fprintf (stderr,
2385              "accept_from_daemon: %p g->state = %d\n", g, g->state);
2386
2387   FD_ZERO (&rset);
2388
2389   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
2390   FD_SET (g->sock, &rset);      /* Read socket for accept. */
2391
2392   int max_fd = MAX (g->sock, g->fd[1]);
2393   int sock = -1;
2394
2395   while (sock == -1) {
2396     /* If the qemu process has died, clean up the zombie (RHBZ#579155).
2397      * By partially polling in the select below we ensure that this
2398      * function will be called eventually.
2399      */
2400     waitpid (g->pid, NULL, WNOHANG);
2401
2402     rset2 = rset;
2403
2404     struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
2405     int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
2406     if (r == -1) {
2407       if (errno == EINTR || errno == EAGAIN)
2408         continue;
2409       perrorf (g, "select");
2410       return -1;
2411     }
2412
2413     if (FD_ISSET (g->fd[1], &rset2)) {
2414       if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
2415         return -1;
2416     }
2417     if (FD_ISSET (g->sock, &rset2)) {
2418       sock = accept (g->sock, NULL, NULL);
2419       if (sock == -1) {
2420         if (errno == EINTR || errno == EAGAIN)
2421           continue;
2422         perrorf (g, "accept");
2423         return -1;
2424       }
2425     }
2426   }
2427
2428   return sock;
2429 }
2430
2431 int
2432 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2433 {
2434   struct guestfs_message_header hdr;
2435   XDR xdr;
2436   u_int32_t len;
2437   int serial = g->msg_next_serial++;
2438   int r;
2439   char *msg_out;
2440   size_t msg_out_size;
2441
2442   if (g->state != BUSY) {
2443     error (g, _("guestfs___send: state %d != BUSY"), g->state);
2444     return -1;
2445   }
2446
2447   /* We have to allocate this message buffer on the heap because
2448    * it is quite large (although will be mostly unused).  We
2449    * can't allocate it on the stack because in some environments
2450    * we have quite limited stack space available, notably when
2451    * running in the JVM.
2452    */
2453   msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2454   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2455
2456   /* Serialize the header. */
2457   hdr.prog = GUESTFS_PROGRAM;
2458   hdr.vers = GUESTFS_PROTOCOL_VERSION;
2459   hdr.proc = proc_nr;
2460   hdr.direction = GUESTFS_DIRECTION_CALL;
2461   hdr.serial = serial;
2462   hdr.status = GUESTFS_STATUS_OK;
2463
2464   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2465     error (g, _("xdr_guestfs_message_header failed"));
2466     goto cleanup1;
2467   }
2468
2469   /* Serialize the args.  If any, because some message types
2470    * have no parameters.
2471    */
2472   if (xdrp) {
2473     if (!(*xdrp) (&xdr, args)) {
2474       error (g, _("dispatch failed to marshal args"));
2475       goto cleanup1;
2476     }
2477   }
2478
2479   /* Get the actual length of the message, resize the buffer to match
2480    * the actual length, and write the length word at the beginning.
2481    */
2482   len = xdr_getpos (&xdr);
2483   xdr_destroy (&xdr);
2484
2485   msg_out = safe_realloc (g, msg_out, len + 4);
2486   msg_out_size = len + 4;
2487
2488   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2489   xdr_uint32_t (&xdr, &len);
2490
2491  again:
2492   r = send_to_daemon (g, msg_out, msg_out_size);
2493   if (r == -2)                  /* Ignore stray daemon cancellations. */
2494     goto again;
2495   if (r == -1)
2496     goto cleanup1;
2497   free (msg_out);
2498
2499   return serial;
2500
2501  cleanup1:
2502   free (msg_out);
2503   return -1;
2504 }
2505
2506 static int cancel = 0; /* XXX Implement file cancellation. */
2507 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2508 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2509 static int send_file_cancellation (guestfs_h *g);
2510 static int send_file_complete (guestfs_h *g);
2511
2512 /* Send a file.
2513  * Returns:
2514  *   0 OK
2515  *   -1 error
2516  *   -2 daemon cancelled (we must read the error message)
2517  */
2518 int
2519 guestfs___send_file (guestfs_h *g, const char *filename)
2520 {
2521   char buf[GUESTFS_MAX_CHUNK_SIZE];
2522   int fd, r, err;
2523
2524   fd = open (filename, O_RDONLY);
2525   if (fd == -1) {
2526     perrorf (g, "open: %s", filename);
2527     send_file_cancellation (g);
2528     /* Daemon sees cancellation and won't reply, so caller can
2529      * just return here.
2530      */
2531     return -1;
2532   }
2533
2534   /* Send file in chunked encoding. */
2535   while (!cancel) {
2536     r = read (fd, buf, sizeof buf);
2537     if (r == -1 && (errno == EINTR || errno == EAGAIN))
2538       continue;
2539     if (r <= 0) break;
2540     err = send_file_data (g, buf, r);
2541     if (err < 0) {
2542       if (err == -2)            /* daemon sent cancellation */
2543         send_file_cancellation (g);
2544       return err;
2545     }
2546   }
2547
2548   if (cancel) {                 /* cancel from either end */
2549     send_file_cancellation (g);
2550     return -1;
2551   }
2552
2553   if (r == -1) {
2554     perrorf (g, "read: %s", filename);
2555     send_file_cancellation (g);
2556     return -1;
2557   }
2558
2559   /* End of file, but before we send that, we need to close
2560    * the file and check for errors.
2561    */
2562   if (close (fd) == -1) {
2563     perrorf (g, "close: %s", filename);
2564     send_file_cancellation (g);
2565     return -1;
2566   }
2567
2568   return send_file_complete (g);
2569 }
2570
2571 /* Send a chunk of file data. */
2572 static int
2573 send_file_data (guestfs_h *g, const char *buf, size_t len)
2574 {
2575   return send_file_chunk (g, 0, buf, len);
2576 }
2577
2578 /* Send a cancellation message. */
2579 static int
2580 send_file_cancellation (guestfs_h *g)
2581 {
2582   return send_file_chunk (g, 1, NULL, 0);
2583 }
2584
2585 /* Send a file complete chunk. */
2586 static int
2587 send_file_complete (guestfs_h *g)
2588 {
2589   char buf[1];
2590   return send_file_chunk (g, 0, buf, 0);
2591 }
2592
2593 static int
2594 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2595 {
2596   u_int32_t len;
2597   int r;
2598   guestfs_chunk chunk;
2599   XDR xdr;
2600   char *msg_out;
2601   size_t msg_out_size;
2602
2603   if (g->state != BUSY) {
2604     error (g, _("send_file_chunk: state %d != READY"), g->state);
2605     return -1;
2606   }
2607
2608   /* Allocate the chunk buffer.  Don't use the stack to avoid
2609    * excessive stack usage and unnecessary copies.
2610    */
2611   msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2612   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2613
2614   /* Serialize the chunk. */
2615   chunk.cancel = cancel;
2616   chunk.data.data_len = buflen;
2617   chunk.data.data_val = (char *) buf;
2618
2619   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2620     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2621            buf, buflen);
2622     xdr_destroy (&xdr);
2623     goto cleanup1;
2624   }
2625
2626   len = xdr_getpos (&xdr);
2627   xdr_destroy (&xdr);
2628
2629   /* Reduce the size of the outgoing message buffer to the real length. */
2630   msg_out = safe_realloc (g, msg_out, len + 4);
2631   msg_out_size = len + 4;
2632
2633   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2634   xdr_uint32_t (&xdr, &len);
2635
2636   r = send_to_daemon (g, msg_out, msg_out_size);
2637
2638   /* Did the daemon send a cancellation message? */
2639   if (r == -2) {
2640     if (g->verbose)
2641       fprintf (stderr, "got daemon cancellation\n");
2642     return -2;
2643   }
2644
2645   if (r == -1)
2646     goto cleanup1;
2647
2648   free (msg_out);
2649
2650   return 0;
2651
2652  cleanup1:
2653   free (msg_out);
2654   return -1;
2655 }
2656
2657 /* Receive a reply. */
2658 int
2659 guestfs___recv (guestfs_h *g, const char *fn,
2660                 guestfs_message_header *hdr,
2661                 guestfs_message_error *err,
2662                 xdrproc_t xdrp, char *ret)
2663 {
2664   XDR xdr;
2665   void *buf;
2666   uint32_t size;
2667   int r;
2668
2669  again:
2670   r = recv_from_daemon (g, &size, &buf);
2671   if (r == -1)
2672     return -1;
2673
2674   /* This can happen if a cancellation happens right at the end
2675    * of us sending a FileIn parameter to the daemon.  Discard.  The
2676    * daemon should send us an error message next.
2677    */
2678   if (size == GUESTFS_CANCEL_FLAG)
2679     goto again;
2680
2681   if (size == GUESTFS_LAUNCH_FLAG) {
2682     error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2683     return -1;
2684   }
2685
2686   xdrmem_create (&xdr, buf, size, XDR_DECODE);
2687
2688   if (!xdr_guestfs_message_header (&xdr, hdr)) {
2689     error (g, "%s: failed to parse reply header", fn);
2690     xdr_destroy (&xdr);
2691     free (buf);
2692     return -1;
2693   }
2694   if (hdr->status == GUESTFS_STATUS_ERROR) {
2695     if (!xdr_guestfs_message_error (&xdr, err)) {
2696       error (g, "%s: failed to parse reply error", fn);
2697       xdr_destroy (&xdr);
2698       free (buf);
2699       return -1;
2700     }
2701   } else {
2702     if (xdrp && ret && !xdrp (&xdr, ret)) {
2703       error (g, "%s: failed to parse reply", fn);
2704       xdr_destroy (&xdr);
2705       free (buf);
2706       return -1;
2707     }
2708   }
2709   xdr_destroy (&xdr);
2710   free (buf);
2711
2712   return 0;
2713 }
2714
2715 /* Receive a file. */
2716
2717 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2718 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2719
2720 int
2721 guestfs___recv_file (guestfs_h *g, const char *filename)
2722 {
2723   void *buf;
2724   int fd, r;
2725
2726   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2727   if (fd == -1) {
2728     perrorf (g, "open: %s", filename);
2729     goto cancel;
2730   }
2731
2732   /* Receive the file in chunked encoding. */
2733   while ((r = receive_file_data (g, &buf)) > 0) {
2734     if (xwrite (fd, buf, r) == -1) {
2735       perrorf (g, "%s: write", filename);
2736       free (buf);
2737       goto cancel;
2738     }
2739     free (buf);
2740   }
2741
2742   if (r == -1) {
2743     error (g, _("%s: error in chunked encoding"), filename);
2744     return -1;
2745   }
2746
2747   if (close (fd) == -1) {
2748     perrorf (g, "close: %s", filename);
2749     return -1;
2750   }
2751
2752   return 0;
2753
2754  cancel: ;
2755   /* Send cancellation message to daemon, then wait until it
2756    * cancels (just throwing away data).
2757    */
2758   XDR xdr;
2759   char fbuf[4];
2760   uint32_t flag = GUESTFS_CANCEL_FLAG;
2761
2762   if (g->verbose)
2763     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2764              __func__);
2765
2766   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2767   xdr_uint32_t (&xdr, &flag);
2768   xdr_destroy (&xdr);
2769
2770   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2771     perrorf (g, _("write to daemon socket"));
2772     return -1;
2773   }
2774
2775   while (receive_file_data (g, NULL) > 0)
2776     ;                           /* just discard it */
2777
2778   return -1;
2779 }
2780
2781 /* Receive a chunk of file data. */
2782 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2783 static ssize_t
2784 receive_file_data (guestfs_h *g, void **buf_r)
2785 {
2786   int r;
2787   void *buf;
2788   uint32_t len;
2789   XDR xdr;
2790   guestfs_chunk chunk;
2791
2792   r = recv_from_daemon (g, &len, &buf);
2793   if (r == -1) {
2794     error (g, _("receive_file_data: parse error in reply callback"));
2795     return -1;
2796   }
2797
2798   if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2799     error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2800     return -1;
2801   }
2802
2803   memset (&chunk, 0, sizeof chunk);
2804
2805   xdrmem_create (&xdr, buf, len, XDR_DECODE);
2806   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2807     error (g, _("failed to parse file chunk"));
2808     free (buf);
2809     return -1;
2810   }
2811   xdr_destroy (&xdr);
2812   /* After decoding, the original buffer is no longer used. */
2813   free (buf);
2814
2815   if (chunk.cancel) {
2816     error (g, _("file receive cancelled by daemon"));
2817     free (chunk.data.data_val);
2818     return -1;
2819   }
2820
2821   if (chunk.data.data_len == 0) { /* end of transfer */
2822     free (chunk.data.data_val);
2823     return 0;
2824   }
2825
2826   if (buf_r) *buf_r = chunk.data.data_val;
2827   else free (chunk.data.data_val); /* else caller frees */
2828
2829   return chunk.data.data_len;
2830 }