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