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