9add092a1993fef2e018637a1d38070fd229b021
[libguestfs.git] / src / launch.c
1 /* libguestfs
2  * Copyright (C) 2009-2011 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 #include <assert.h>
38
39 #include <rpc/types.h>
40 #include <rpc/xdr.h>
41
42 #ifdef HAVE_ERRNO_H
43 #include <errno.h>
44 #endif
45
46 #ifdef HAVE_SYS_TYPES_H
47 #include <sys/types.h>
48 #endif
49
50 #ifdef HAVE_SYS_WAIT_H
51 #include <sys/wait.h>
52 #endif
53
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57
58 #ifdef HAVE_SYS_UN_H
59 #include <sys/un.h>
60 #endif
61
62 #include <arpa/inet.h>
63 #include <netinet/in.h>
64
65 #include "c-ctype.h"
66 #include "ignore-value.h"
67 #include "glthread/lock.h"
68
69 #include "guestfs.h"
70 #include "guestfs-internal.h"
71 #include "guestfs-internal-actions.h"
72 #include "guestfs_protocol.h"
73
74 static int launch_appliance (guestfs_h *g);
75 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
76 static void print_qemu_command_line (guestfs_h *g, char **argv);
77 static int connect_unix_socket (guestfs_h *g, const char *sock);
78 static int qemu_supports (guestfs_h *g, const char *option);
79 static char *qemu_drive_param (guestfs_h *g, const struct drive *drv);
80
81 #if 0
82 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
83
84 static void compile_regexps (void) __attribute__((constructor));
85 static void free_regexps (void) __attribute__((destructor));
86
87 static void
88 compile_regexps (void)
89 {
90   const char *err;
91   int offset;
92
93 #define COMPILE(re,pattern,options)                                     \
94   do {                                                                  \
95     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
96     if (re == NULL) {                                                   \
97       ignore_value (write (2, err, strlen (err)));                      \
98       abort ();                                                         \
99     }                                                                   \
100   } while (0)
101 }
102
103 static void
104 free_regexps (void)
105 {
106 }
107 #endif
108
109 /* Functions to add a string to the current command line. */
110 static void
111 alloc_cmdline (guestfs_h *g)
112 {
113   if (g->cmdline == NULL) {
114     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
115     g->cmdline_size = 1;
116     g->cmdline = safe_malloc (g, sizeof (char *));
117     g->cmdline[0] = NULL;
118   }
119 }
120
121 static void
122 incr_cmdline_size (guestfs_h *g)
123 {
124   alloc_cmdline (g);
125   g->cmdline_size++;
126   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
127 }
128
129 static int
130 add_cmdline (guestfs_h *g, const char *str)
131 {
132   if (g->state != CONFIG) {
133     error (g,
134         _("command line cannot be altered after qemu subprocess launched"));
135     return -1;
136   }
137
138   incr_cmdline_size (g);
139   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
140   return 0;
141 }
142
143 struct drive **
144 guestfs___checkpoint_drives (guestfs_h *g)
145 {
146   struct drive **i = &g->drives;
147   while (*i != NULL) i = &((*i)->next);
148   return i;
149 }
150
151 void
152 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
153 {
154   guestfs___free_drives(i);
155 }
156
157 /* Internal command to return the command line. */
158 char **
159 guestfs__debug_cmdline (guestfs_h *g)
160 {
161   size_t i;
162   char **r;
163
164   alloc_cmdline (g);
165
166   r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
167   r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
168
169   for (i = 1; i < g->cmdline_size; ++i)
170     r[i] = safe_strdup (g, g->cmdline[i]);
171
172   r[g->cmdline_size] = NULL;
173
174   return r;                     /* caller frees */
175 }
176
177 /* Internal command to return the list of drives. */
178 char **
179 guestfs__debug_drives (guestfs_h *g)
180 {
181   size_t i, count;
182   char **ret;
183   struct drive *drv;
184
185   for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
186     ;
187
188   ret = safe_malloc (g, sizeof (char *) * (count + 1));
189
190   for (i = 0, drv = g->drives; drv; i++, drv = drv->next)
191     ret[i] = qemu_drive_param (g, drv);
192
193   ret[count] = NULL;
194
195   return ret;                   /* caller frees */
196 }
197
198 int
199 guestfs__config (guestfs_h *g,
200                  const char *qemu_param, const char *qemu_value)
201 {
202   if (qemu_param[0] != '-') {
203     error (g, _("guestfs_config: parameter must begin with '-' character"));
204     return -1;
205   }
206
207   /* A bit fascist, but the user will probably break the extra
208    * parameters that we add if they try to set any of these.
209    */
210   if (STREQ (qemu_param, "-kernel") ||
211       STREQ (qemu_param, "-initrd") ||
212       STREQ (qemu_param, "-nographic") ||
213       STREQ (qemu_param, "-serial") ||
214       STREQ (qemu_param, "-full-screen") ||
215       STREQ (qemu_param, "-std-vga") ||
216       STREQ (qemu_param, "-vnc")) {
217     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
218     return -1;
219   }
220
221   if (add_cmdline (g, qemu_param) != 0) return -1;
222
223   if (qemu_value != NULL) {
224     if (add_cmdline (g, qemu_value) != 0) return -1;
225   }
226
227   return 0;
228 }
229
230 /* cache=off improves reliability in the event of a host crash.
231  *
232  * However this option causes qemu to try to open the file with
233  * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
234  * So we check if we can open the file with or without O_DIRECT,
235  * and use cache=off (or not) accordingly.
236  *
237  * NB: This function is only called on the !readonly path.  We must
238  * try to open with O_RDWR to test that the file is readable and
239  * writable here.
240  */
241 static int
242 test_cache_off (guestfs_h *g, const char *filename)
243 {
244   int fd = open (filename, O_RDWR|O_DIRECT);
245   if (fd >= 0) {
246     close (fd);
247     return 1;
248   }
249
250   fd = open (filename, O_RDWR);
251   if (fd >= 0) {
252     close (fd);
253     return 0;
254   }
255
256   perrorf (g, "%s", filename);
257   return -1;
258 }
259
260 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
261 static int
262 valid_format_iface (const char *str)
263 {
264   size_t len = strlen (str);
265
266   if (len == 0)
267     return 0;
268
269   while (len > 0) {
270     char c = *str++;
271     len--;
272     if (c != '-' && c != '_' && !c_isalnum (c))
273       return 0;
274   }
275   return 1;
276 }
277
278 int
279 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
280                          const struct guestfs_add_drive_opts_argv *optargs)
281 {
282   int readonly;
283   char *format;
284   char *iface;
285   char *name;
286   int use_cache_off;
287
288   if (strchr (filename, ',') != NULL) {
289     error (g, _("filename cannot contain ',' (comma) character"));
290     return -1;
291   }
292
293   readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
294              ? optargs->readonly : 0;
295   format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
296            ? safe_strdup (g, optargs->format) : NULL;
297   iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
298           ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
299   name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
300           ? safe_strdup (g, optargs->name) : NULL;
301
302   if (format && !valid_format_iface (format)) {
303     error (g, _("%s parameter is empty or contains disallowed characters"),
304            "format");
305     free (format);
306     free (iface);
307     free (name);
308     return -1;
309   }
310   if (!valid_format_iface (iface)) {
311     error (g, _("%s parameter is empty or contains disallowed characters"),
312            "iface");
313     free (format);
314     free (iface);
315     free (name);
316     return -1;
317   }
318
319   /* For writable files, see if we can use cache=off.  This also
320    * checks for the existence of the file.  For readonly we have
321    * to do the check explicitly.
322    */
323   use_cache_off = readonly ? 0 : test_cache_off (g, filename);
324   if (use_cache_off == -1) {
325     free (format);
326     free (iface);
327     free (name);
328     return -1;
329   }
330
331   if (readonly) {
332     if (access (filename, R_OK) == -1) {
333       perrorf (g, "%s", filename);
334       free (format);
335       free (iface);
336       free (name);
337       return -1;
338     }
339   }
340
341   struct drive **i = &(g->drives);
342   while (*i != NULL) i = &((*i)->next);
343
344   *i = safe_malloc (g, sizeof (struct drive));
345   (*i)->next = NULL;
346   (*i)->path = safe_strdup (g, filename);
347   (*i)->readonly = readonly;
348   (*i)->format = format;
349   (*i)->iface = iface;
350   (*i)->name = name;
351   (*i)->use_cache_off = use_cache_off;
352
353   return 0;
354 }
355
356 int
357 guestfs__add_drive (guestfs_h *g, const char *filename)
358 {
359   struct guestfs_add_drive_opts_argv optargs = {
360     .bitmask = 0,
361   };
362
363   return guestfs__add_drive_opts (g, filename, &optargs);
364 }
365
366 int
367 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
368 {
369   struct guestfs_add_drive_opts_argv optargs = {
370     .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
371     .readonly = 1,
372   };
373
374   return guestfs__add_drive_opts (g, filename, &optargs);
375 }
376
377 int
378 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
379                             const char *iface)
380 {
381   struct guestfs_add_drive_opts_argv optargs = {
382     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
383     .iface = iface,
384   };
385
386   return guestfs__add_drive_opts (g, filename, &optargs);
387 }
388
389 int
390 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
391                                const char *iface)
392 {
393   struct guestfs_add_drive_opts_argv optargs = {
394     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
395              | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
396     .iface = iface,
397     .readonly = 1,
398   };
399
400   return guestfs__add_drive_opts (g, filename, &optargs);
401 }
402
403 int
404 guestfs__add_cdrom (guestfs_h *g, const char *filename)
405 {
406   if (strchr (filename, ',') != NULL) {
407     error (g, _("filename cannot contain ',' (comma) character"));
408     return -1;
409   }
410
411   if (access (filename, F_OK) == -1) {
412     perrorf (g, "%s", filename);
413     return -1;
414   }
415
416   return guestfs__config (g, "-cdrom", filename);
417 }
418
419 static int is_openable (guestfs_h *g, const char *path, int flags);
420
421 int
422 guestfs__launch (guestfs_h *g)
423 {
424   /* Configured? */
425   if (g->state != CONFIG) {
426     error (g, _("the libguestfs handle has already been launched"));
427     return -1;
428   }
429
430   TRACE0 (launch_start);
431
432   /* Make the temporary directory. */
433   if (!g->tmpdir) {
434     TMP_TEMPLATE_ON_STACK (dir_template);
435     g->tmpdir = safe_strdup (g, dir_template);
436     if (mkdtemp (g->tmpdir) == NULL) {
437       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
438       return -1;
439     }
440   }
441
442   /* Allow anyone to read the temporary directory.  The socket in this
443    * directory won't be readable but anyone can see it exists if they
444    * want. (RHBZ#610880).
445    */
446   if (chmod (g->tmpdir, 0755) == -1)
447     warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
448
449   /* Launch the appliance or attach to an existing daemon. */
450   switch (g->attach_method) {
451   case ATTACH_METHOD_APPLIANCE:
452     return launch_appliance (g);
453
454   case ATTACH_METHOD_UNIX:
455     return connect_unix_socket (g, g->attach_method_arg);
456
457   default:
458     abort ();
459   }
460 }
461
462 static int
463 launch_appliance (guestfs_h *g)
464 {
465   int r;
466   int wfd[2], rfd[2];
467   char guestfsd_sock[256];
468   struct sockaddr_un addr;
469
470   /* At present you must add drives before starting the appliance.  In
471    * future when we enable hotplugging you won't need to do this.
472    */
473   if (!g->drives) {
474     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
475     return -1;
476   }
477
478   /* Start the clock ... */
479   gettimeofday (&g->launch_t, NULL);
480   guestfs___launch_send_progress (g, 0);
481
482   TRACE0 (launch_build_appliance_start);
483
484   /* Locate and/or build the appliance. */
485   char *kernel = NULL, *initrd = NULL, *appliance = NULL;
486   if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
487     return -1;
488
489   TRACE0 (launch_build_appliance_end);
490
491   guestfs___launch_send_progress (g, 3);
492
493   if (g->verbose)
494     guestfs___print_timestamped_message (g, "begin testing qemu features");
495
496   /* Get qemu help text and version. */
497   if (qemu_supports (g, NULL) == -1)
498     goto cleanup0;
499
500   /* Using virtio-serial, we need to create a local Unix domain socket
501    * for qemu to connect to.
502    */
503   snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
504   unlink (guestfsd_sock);
505
506   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
507   if (g->sock == -1) {
508     perrorf (g, "socket");
509     goto cleanup0;
510   }
511
512   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
513     perrorf (g, "fcntl");
514     goto cleanup0;
515   }
516
517   addr.sun_family = AF_UNIX;
518   strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
519   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
520
521   if (bind (g->sock, &addr, sizeof addr) == -1) {
522     perrorf (g, "bind");
523     goto cleanup0;
524   }
525
526   if (listen (g->sock, 1) == -1) {
527     perrorf (g, "listen");
528     goto cleanup0;
529   }
530
531   if (!g->direct) {
532     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
533       perrorf (g, "pipe");
534       goto cleanup0;
535     }
536   }
537
538   if (g->verbose)
539     guestfs___print_timestamped_message (g, "finished testing qemu features");
540
541   r = fork ();
542   if (r == -1) {
543     perrorf (g, "fork");
544     if (!g->direct) {
545       close (wfd[0]);
546       close (wfd[1]);
547       close (rfd[0]);
548       close (rfd[1]);
549     }
550     goto cleanup0;
551   }
552
553   if (r == 0) {                 /* Child (qemu). */
554     char buf[256];
555
556     /* Set up the full command line.  Do this in the subprocess so we
557      * don't need to worry about cleaning up.
558      */
559
560     /* Set g->cmdline[0] to the name of the qemu process.  However
561      * it is possible that no g->cmdline has been allocated yet so
562      * we must do that first.
563      */
564     alloc_cmdline (g);
565     g->cmdline[0] = g->qemu;
566
567     /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
568      * devices.  The -global option must exist, but you can pass any
569      * strings to it so we don't need to check for the specific virtio
570      * feature.
571      */
572     if (qemu_supports (g, "-global")) {
573       add_cmdline (g, "-global");
574       add_cmdline (g, "virtio-blk-pci.scsi=off");
575     }
576
577     /* Add drives */
578     struct drive *drv = g->drives;
579     while (drv != NULL) {
580       /* Construct the final -drive parameter. */
581       char *buf = qemu_drive_param (g, drv);
582
583       add_cmdline (g, "-drive");
584       add_cmdline (g, buf);
585       free (buf);
586
587       drv = drv->next;
588     }
589
590     if (qemu_supports (g, "-nodefconfig"))
591       add_cmdline (g, "-nodefconfig");
592
593     /* The qemu -machine option (added 2010-12) is a bit more sane
594      * since it falls back through various different acceleration
595      * modes, so try that first (thanks Markus Armbruster).
596      */
597     if (qemu_supports (g, "-machine")) {
598       add_cmdline (g, "-machine");
599 #if QEMU_MACHINE_TYPE_IS_BROKEN
600       /* Workaround for qemu 0.15: We have to add the '[type=]pc'
601        * since there is no default.  This is not a permanent solution
602        * because this only works on PC-like hardware.  Other platforms
603        * like ppc would need a different machine type.
604        *
605        * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
606        * not a problem in qemu < 0.15.
607        */
608       add_cmdline (g, "pc,accel=kvm:tcg");
609 #else
610       add_cmdline (g, "accel=kvm:tcg");
611 #endif
612     } else {
613       /* qemu sometimes needs this option to enable hardware
614        * virtualization, but some versions of 'qemu-kvm' will use KVM
615        * regardless (even where this option appears in the help text).
616        * It is rumoured that there are versions of qemu where supplying
617        * this option when hardware virtualization is not available will
618        * cause qemu to fail, so we we have to check at least that
619        * /dev/kvm is openable.  That's not reliable, since /dev/kvm
620        * might be openable by qemu but not by us (think: SELinux) in
621        * which case the user would not get hardware virtualization,
622        * although at least shouldn't fail.  A giant clusterfuck with the
623        * qemu command line, again.
624        */
625       if (qemu_supports (g, "-enable-kvm") &&
626           is_openable (g, "/dev/kvm", O_RDWR))
627         add_cmdline (g, "-enable-kvm");
628     }
629
630     /* Newer versions of qemu (from around 2009/12) changed the
631      * behaviour of monitors so that an implicit '-monitor stdio' is
632      * assumed if we are in -nographic mode and there is no other
633      * -monitor option.  Only a single stdio device is allowed, so
634      * this broke the '-serial stdio' option.  There is a new flag
635      * called -nodefaults which gets rid of all this default crud, so
636      * let's use that to avoid this and any future surprises.
637      */
638     if (qemu_supports (g, "-nodefaults"))
639       add_cmdline (g, "-nodefaults");
640
641     add_cmdline (g, "-nographic");
642
643     if (g->smp > 1) {
644       snprintf (buf, sizeof buf, "%d", g->smp);
645       add_cmdline (g, "-smp");
646       add_cmdline (g, buf);
647     }
648
649     snprintf (buf, sizeof buf, "%d", g->memsize);
650     add_cmdline (g, "-m");
651     add_cmdline (g, buf);
652
653     /* Force exit instead of reboot on panic */
654     add_cmdline (g, "-no-reboot");
655
656     /* These options recommended by KVM developers to improve reliability. */
657     if (qemu_supports (g, "-no-hpet"))
658       add_cmdline (g, "-no-hpet");
659
660     if (qemu_supports (g, "-rtc-td-hack"))
661       add_cmdline (g, "-rtc-td-hack");
662
663     /* Create the virtio serial bus. */
664     add_cmdline (g, "-device");
665     add_cmdline (g, "virtio-serial");
666
667 #if 0
668     /* Use virtio-console (a variant form of virtio-serial) for the
669      * guest's serial console.
670      */
671     add_cmdline (g, "-chardev");
672     add_cmdline (g, "stdio,id=console");
673     add_cmdline (g, "-device");
674     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
675 #else
676     /* When the above works ...  until then: */
677     add_cmdline (g, "-serial");
678     add_cmdline (g, "stdio");
679 #endif
680
681     /* Set up virtio-serial for the communications channel. */
682     add_cmdline (g, "-chardev");
683     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
684     add_cmdline (g, buf);
685     add_cmdline (g, "-device");
686     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
687
688     /* Enable user networking. */
689     if (g->enable_network) {
690       add_cmdline (g, "-netdev");
691       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
692       add_cmdline (g, "-device");
693       add_cmdline (g, NET_IF ",netdev=usernet");
694     }
695
696 #define LINUX_CMDLINE                                                   \
697     "panic=1 "         /* force kernel to panic if daemon exits */      \
698     "console=ttyS0 "   /* serial console */                             \
699     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
700     "no_timer_check "  /* fix for RHBZ#502058 */                        \
701     "acpi=off "        /* we don't need ACPI, turn it off */            \
702     "printk.time=1 "   /* display timestamp before kernel messages */   \
703     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
704
705     /* Linux kernel command line. */
706     snprintf (buf, sizeof buf,
707               LINUX_CMDLINE
708               "%s "             /* (selinux) */
709               "%s "             /* (verbose) */
710               "TERM=%s "        /* (TERM environment variable) */
711               "%s",             /* (append) */
712               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
713               g->verbose ? "guestfs_verbose=1" : "",
714               getenv ("TERM") ? : "linux",
715               g->append ? g->append : "");
716
717     add_cmdline (g, "-kernel");
718     add_cmdline (g, kernel);
719     add_cmdline (g, "-initrd");
720     add_cmdline (g, initrd);
721     add_cmdline (g, "-append");
722     add_cmdline (g, buf);
723
724     /* Add the ext2 appliance drive (last of all). */
725     if (appliance) {
726       const char *cachemode = "";
727       if (qemu_supports (g, "cache=")) {
728         if (qemu_supports (g, "unsafe"))
729           cachemode = ",cache=unsafe";
730         else if (qemu_supports (g, "writeback"))
731           cachemode = ",cache=writeback";
732       }
733
734       char buf2[PATH_MAX + 64];
735       add_cmdline (g, "-drive");
736       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
737                 appliance, cachemode);
738       add_cmdline (g, buf2);
739     }
740
741     /* Finish off the command line. */
742     incr_cmdline_size (g);
743     g->cmdline[g->cmdline_size-1] = NULL;
744
745     if (!g->direct) {
746       /* Set up stdin, stdout, stderr. */
747       close (0);
748       close (1);
749       close (wfd[1]);
750       close (rfd[0]);
751
752       /* Stdin. */
753       if (dup (wfd[0]) == -1) {
754       dup_failed:
755         perror ("dup failed");
756         _exit (EXIT_FAILURE);
757       }
758       /* Stdout. */
759       if (dup (rfd[1]) == -1)
760         goto dup_failed;
761
762       /* Particularly since qemu 0.15, qemu spews all sorts of debug
763        * information on stderr.  It is useful to both capture this and
764        * not confuse casual users, so send stderr to the pipe as well.
765        */
766       close (2);
767       if (dup (rfd[1]) == -1)
768         goto dup_failed;
769
770       close (wfd[0]);
771       close (rfd[1]);
772     }
773
774     /* Dump the command line (after setting up stderr above). */
775     if (g->verbose)
776       print_qemu_command_line (g, g->cmdline);
777
778     /* Put qemu in a new process group. */
779     if (g->pgroup)
780       setpgid (0, 0);
781
782     setenv ("LC_ALL", "C", 1);
783
784     TRACE0 (launch_run_qemu);
785
786     execv (g->qemu, g->cmdline); /* Run qemu. */
787     perror (g->qemu);
788     _exit (EXIT_FAILURE);
789   }
790
791   /* Parent (library). */
792   g->pid = r;
793
794   free (kernel);
795   kernel = NULL;
796   free (initrd);
797   initrd = NULL;
798   free (appliance);
799   appliance = NULL;
800
801   /* Fork the recovery process off which will kill qemu if the parent
802    * process fails to do so (eg. if the parent segfaults).
803    */
804   g->recoverypid = -1;
805   if (g->recovery_proc) {
806     r = fork ();
807     if (r == 0) {
808       pid_t qemu_pid = g->pid;
809       pid_t parent_pid = getppid ();
810
811       /* It would be nice to be able to put this in the same process
812        * group as qemu (ie. setpgid (0, qemu_pid)).  However this is
813        * not possible because we don't have any guarantee here that
814        * the qemu process has started yet.
815        */
816       if (g->pgroup)
817         setpgid (0, 0);
818
819       /* Writing to argv is hideously complicated and error prone.  See:
820        * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
821        */
822
823       /* Loop around waiting for one or both of the other processes to
824        * disappear.  It's fair to say this is very hairy.  The PIDs that
825        * we are looking at might be reused by another process.  We are
826        * effectively polling.  Is the cure worse than the disease?
827        */
828       for (;;) {
829         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
830           _exit (EXIT_SUCCESS);
831         if (kill (parent_pid, 0) == -1) {
832           /* Parent's gone away, qemu still around, so kill qemu. */
833           kill (qemu_pid, 9);
834           _exit (EXIT_SUCCESS);
835         }
836         sleep (2);
837       }
838     }
839
840     /* Don't worry, if the fork failed, this will be -1.  The recovery
841      * process isn't essential.
842      */
843     g->recoverypid = r;
844   }
845
846   if (!g->direct) {
847     /* Close the other ends of the pipe. */
848     close (wfd[0]);
849     close (rfd[1]);
850
851     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
852         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
853       perrorf (g, "fcntl");
854       goto cleanup1;
855     }
856
857     g->fd[0] = wfd[1];          /* stdin of child */
858     g->fd[1] = rfd[0];          /* stdout of child */
859   } else {
860     g->fd[0] = open ("/dev/null", O_RDWR);
861     if (g->fd[0] == -1) {
862       perrorf (g, "open /dev/null");
863       goto cleanup1;
864     }
865     g->fd[1] = dup (g->fd[0]);
866     if (g->fd[1] == -1) {
867       perrorf (g, "dup");
868       close (g->fd[0]);
869       goto cleanup1;
870     }
871   }
872
873   g->state = LAUNCHING;
874
875   /* Wait for qemu to start and to connect back to us via
876    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
877    */
878   r = guestfs___accept_from_daemon (g);
879   if (r == -1)
880     goto cleanup1;
881
882   /* NB: We reach here just because qemu has opened the socket.  It
883    * does not mean the daemon is up until we read the
884    * GUESTFS_LAUNCH_FLAG below.  Failures in qemu startup can still
885    * happen even if we reach here, even early failures like not being
886    * able to open a drive.
887    */
888
889   close (g->sock); /* Close the listening socket. */
890   g->sock = r; /* This is the accepted data socket. */
891
892   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
893     perrorf (g, "fcntl");
894     goto cleanup1;
895   }
896
897   uint32_t size;
898   void *buf = NULL;
899   r = guestfs___recv_from_daemon (g, &size, &buf);
900   free (buf);
901
902   if (r == -1) return -1;
903
904   if (size != GUESTFS_LAUNCH_FLAG) {
905     error (g, _("guestfs_launch failed, see earlier error messages"));
906     goto cleanup1;
907   }
908
909   if (g->verbose)
910     guestfs___print_timestamped_message (g, "appliance is up");
911
912   /* This is possible in some really strange situations, such as
913    * guestfsd starts up OK but then qemu immediately exits.  Check for
914    * it because the caller is probably expecting to be able to send
915    * commands after this function returns.
916    */
917   if (g->state != READY) {
918     error (g, _("qemu launched and contacted daemon, but state != READY"));
919     goto cleanup1;
920   }
921
922   TRACE0 (launch_end);
923
924   guestfs___launch_send_progress (g, 12);
925
926   return 0;
927
928  cleanup1:
929   if (!g->direct) {
930     close (wfd[1]);
931     close (rfd[0]);
932   }
933   if (g->pid > 0) kill (g->pid, 9);
934   if (g->recoverypid > 0) kill (g->recoverypid, 9);
935   if (g->pid > 0) waitpid (g->pid, NULL, 0);
936   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
937   g->fd[0] = -1;
938   g->fd[1] = -1;
939   g->pid = 0;
940   g->recoverypid = 0;
941   memset (&g->launch_t, 0, sizeof g->launch_t);
942
943  cleanup0:
944   if (g->sock >= 0) {
945     close (g->sock);
946     g->sock = -1;
947   }
948   g->state = CONFIG;
949   free (kernel);
950   free (initrd);
951   free (appliance);
952   return -1;
953 }
954
955 /* Alternate attach method: instead of launching the appliance,
956  * connect to an existing unix socket.
957  */
958 static int
959 connect_unix_socket (guestfs_h *g, const char *sockpath)
960 {
961   int r;
962   struct sockaddr_un addr;
963
964   /* Start the clock ... */
965   gettimeofday (&g->launch_t, NULL);
966
967   /* Set these to nothing so we don't try to kill random processes or
968    * read from random file descriptors.
969    */
970   g->pid = 0;
971   g->recoverypid = 0;
972   g->fd[0] = -1;
973   g->fd[1] = -1;
974
975   if (g->verbose)
976     guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
977
978   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
979   if (g->sock == -1) {
980     perrorf (g, "socket");
981     return -1;
982   }
983
984   addr.sun_family = AF_UNIX;
985   strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
986   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
987
988   g->state = LAUNCHING;
989
990   if (connect (g->sock, &addr, sizeof addr) == -1) {
991     perrorf (g, "bind");
992     goto cleanup;
993   }
994
995   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
996     perrorf (g, "fcntl");
997     goto cleanup;
998   }
999
1000   uint32_t size;
1001   void *buf = NULL;
1002   r = guestfs___recv_from_daemon (g, &size, &buf);
1003   free (buf);
1004
1005   if (r == -1) return -1;
1006
1007   if (size != GUESTFS_LAUNCH_FLAG) {
1008     error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1009     goto cleanup;
1010   }
1011
1012   if (g->verbose)
1013     guestfs___print_timestamped_message (g, "connected");
1014
1015   if (g->state != READY) {
1016     error (g, _("contacted guestfsd, but state != READY"));
1017     goto cleanup;
1018   }
1019
1020   return 0;
1021
1022  cleanup:
1023   close (g->sock);
1024   return -1;
1025 }
1026
1027 /* launch (of the ordinary appliance) generates approximate progress
1028  * messages.  Currently these are defined as follows:
1029  *
1030  *    0 / 12: launch clock starts
1031  *    3 / 12: appliance created
1032  *    6 / 12: detected that guest kernel started
1033  *    9 / 12: detected that /init script is running
1034  *   12 / 12: launch completed successfully
1035  *
1036  * Notes:
1037  * (1) This is not a documented ABI and the behaviour may be changed
1038  * or removed in future.
1039  * (2) Messages are only sent if more than 5 seconds has elapsed
1040  * since the launch clock started.
1041  * (3) There is a gross hack in proto.c to make this work.
1042  */
1043 void
1044 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1045 {
1046   struct timeval tv;
1047
1048   gettimeofday (&tv, NULL);
1049   if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1050     guestfs_progress progress_message =
1051       { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1052
1053     guestfs___progress_message_callback (g, &progress_message);
1054   }
1055 }
1056
1057 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1058  * to override it at runtime using $TMPDIR.
1059  * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1060  */
1061 const char *
1062 guestfs_tmpdir (void)
1063 {
1064   const char *tmpdir;
1065
1066 #ifdef P_tmpdir
1067   tmpdir = P_tmpdir;
1068 #else
1069   tmpdir = "/tmp";
1070 #endif
1071
1072   const char *t = getenv ("TMPDIR");
1073   if (t) tmpdir = t;
1074
1075   return tmpdir;
1076 }
1077
1078 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1079  * allow users to override it at runtime using $TMPDIR.
1080  * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1081  */
1082 const char *
1083 guestfs___persistent_tmpdir (void)
1084 {
1085   const char *tmpdir;
1086
1087   tmpdir = "/var/tmp";
1088
1089   const char *t = getenv ("TMPDIR");
1090   if (t) tmpdir = t;
1091
1092   return tmpdir;
1093 }
1094
1095 /* Compute Y - X and return the result in milliseconds.
1096  * Approximately the same as this code:
1097  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1098  */
1099 static int64_t
1100 timeval_diff (const struct timeval *x, const struct timeval *y)
1101 {
1102   int64_t msec;
1103
1104   msec = (y->tv_sec - x->tv_sec) * 1000;
1105   msec += (y->tv_usec - x->tv_usec) / 1000;
1106   return msec;
1107 }
1108
1109 /* Note that since this calls 'debug' it should only be called
1110  * from the parent process.
1111  */
1112 void
1113 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1114 {
1115   va_list args;
1116   char *msg;
1117   int err;
1118   struct timeval tv;
1119
1120   va_start (args, fs);
1121   err = vasprintf (&msg, fs, args);
1122   va_end (args);
1123
1124   if (err < 0) return;
1125
1126   gettimeofday (&tv, NULL);
1127
1128   debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1129
1130   free (msg);
1131 }
1132
1133 /* This is called from the forked subprocess just before qemu runs, so
1134  * it can just print the message straight to stderr, where it will be
1135  * picked up and funnelled through the usual appliance event API.
1136  */
1137 static void
1138 print_qemu_command_line (guestfs_h *g, char **argv)
1139 {
1140   int i = 0;
1141   int needs_quote;
1142
1143   struct timeval tv;
1144   gettimeofday (&tv, NULL);
1145   fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1146
1147   while (argv[i]) {
1148     if (argv[i][0] == '-') /* -option starts a new line */
1149       fprintf (stderr, " \\\n   ");
1150
1151     if (i > 0) fputc (' ', stderr);
1152
1153     /* Does it need shell quoting?  This only deals with simple cases. */
1154     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1155
1156     if (needs_quote) fputc ('\'', stderr);
1157     fprintf (stderr, "%s", argv[i]);
1158     if (needs_quote) fputc ('\'', stderr);
1159     i++;
1160   }
1161 }
1162
1163 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1164 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1165
1166 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1167  * 'qemu -version' so we know what options this qemu supports and
1168  * the version.
1169  */
1170 static int
1171 test_qemu (guestfs_h *g)
1172 {
1173   char cmd[1024];
1174   FILE *fp;
1175
1176   free (g->qemu_help);
1177   g->qemu_help = NULL;
1178   free (g->qemu_version);
1179   g->qemu_version = NULL;
1180
1181   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1182
1183   /* qemu -help should always work (qemu -version OTOH wasn't
1184    * supported by qemu 0.9).  If this command doesn't work then it
1185    * probably indicates that the qemu binary is missing.
1186    */
1187   if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1188     error (g, _("command failed: %s\n\nIf qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU\nenvironment variable.  There may also be errors printed above."),
1189            cmd);
1190     return -1;
1191   }
1192
1193   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1194             g->qemu);
1195
1196   /* Intentionally ignore errors from qemu -version. */
1197   ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1198
1199   return 0;
1200 }
1201
1202 static int
1203 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1204 {
1205   FILE *fp;
1206
1207   fp = popen (cmd, "r");
1208   if (fp == NULL)
1209     return -1;
1210
1211   if (read_all (g, fp, ret) == -1) {
1212     pclose (fp);
1213     return -1;
1214   }
1215
1216   if (pclose (fp) != 0)
1217     return -1;
1218
1219   return 0;
1220 }
1221
1222 static int
1223 read_all (guestfs_h *g, FILE *fp, char **ret)
1224 {
1225   int r, n = 0;
1226   char *p;
1227
1228  again:
1229   if (feof (fp)) {
1230     *ret = safe_realloc (g, *ret, n + 1);
1231     (*ret)[n] = '\0';
1232     return n;
1233   }
1234
1235   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1236   p = &(*ret)[n];
1237   r = fread (p, 1, BUFSIZ, fp);
1238   if (ferror (fp)) {
1239     perrorf (g, "read");
1240     return -1;
1241   }
1242   n += r;
1243   goto again;
1244 }
1245
1246 /* Test if option is supported by qemu command line (just by grepping
1247  * the help text).
1248  *
1249  * The first time this is used, it has to run the external qemu
1250  * binary.  If that fails, it returns -1.
1251  *
1252  * To just do the first-time run of the qemu binary, call this with
1253  * option == NULL, in which case it will return -1 if there was an
1254  * error doing that.
1255  */
1256 static int
1257 qemu_supports (guestfs_h *g, const char *option)
1258 {
1259   if (!g->qemu_help) {
1260     if (test_qemu (g) == -1)
1261       return -1;
1262   }
1263
1264   if (option == NULL)
1265     return 1;
1266
1267   return strstr (g->qemu_help, option) != NULL;
1268 }
1269
1270 #if 0
1271 /* As above but using a regex instead of a fixed string. */
1272 static int
1273 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1274 {
1275   if (!g->qemu_help) {
1276     if (test_qemu (g) == -1)
1277       return -1;
1278   }
1279
1280   return match (g, g->qemu_help, option_regex);
1281 }
1282 #endif
1283
1284 /* Check if a file can be opened. */
1285 static int
1286 is_openable (guestfs_h *g, const char *path, int flags)
1287 {
1288   int fd = open (path, flags);
1289   if (fd == -1) {
1290     debug (g, "is_openable: %s: %m", path);
1291     return 0;
1292   }
1293   close (fd);
1294   return 1;
1295 }
1296
1297 static char *
1298 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1299 {
1300   size_t len = 64;
1301   char *r;
1302
1303   len += strlen (drv->path);
1304   len += strlen (drv->iface);
1305   if (drv->format)
1306     len += strlen (drv->format);
1307
1308   r = safe_malloc (g, len);
1309
1310   snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1311             drv->path,
1312             drv->readonly ? ",snapshot=on" : "",
1313             drv->use_cache_off ? ",cache=off" : "",
1314             drv->format ? ",format=" : "",
1315             drv->format ? drv->format : "",
1316             drv->iface);
1317
1318   return r;                     /* caller frees */
1319 }
1320
1321 /* You had to call this function after launch in versions <= 1.0.70,
1322  * but it is now a no-op.
1323  */
1324 int
1325 guestfs__wait_ready (guestfs_h *g)
1326 {
1327   if (g->state != READY)  {
1328     error (g, _("qemu has not been launched yet"));
1329     return -1;
1330   }
1331
1332   return 0;
1333 }
1334
1335 int
1336 guestfs__kill_subprocess (guestfs_h *g)
1337 {
1338   if (g->state == CONFIG) {
1339     error (g, _("no subprocess to kill"));
1340     return -1;
1341   }
1342
1343   debug (g, "sending SIGTERM to process %d", g->pid);
1344
1345   if (g->pid > 0) kill (g->pid, SIGTERM);
1346   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1347
1348   return 0;
1349 }
1350
1351 /* Access current state. */
1352 int
1353 guestfs__is_config (guestfs_h *g)
1354 {
1355   return g->state == CONFIG;
1356 }
1357
1358 int
1359 guestfs__is_launching (guestfs_h *g)
1360 {
1361   return g->state == LAUNCHING;
1362 }
1363
1364 int
1365 guestfs__is_ready (guestfs_h *g)
1366 {
1367   return g->state == READY;
1368 }
1369
1370 int
1371 guestfs__is_busy (guestfs_h *g)
1372 {
1373   return g->state == BUSY;
1374 }
1375
1376 int
1377 guestfs__get_state (guestfs_h *g)
1378 {
1379   return g->state;
1380 }