qemu detection: Free up previous qemu help/version strings if they exist.
[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     if (qemu_supports (g, "-nodefconfig"))
489       add_cmdline (g, "-nodefconfig");
490
491     /* The qemu -machine option (added 2010-12) is a bit more sane
492      * since it falls back through various different acceleration
493      * modes, so try that first (thanks Markus Armbruster).
494      */
495     if (qemu_supports (g, "-machine")) {
496       add_cmdline (g, "-machine");
497       add_cmdline (g, "accel=kvm:tcg");
498     } else {
499       /* qemu sometimes needs this option to enable hardware
500        * virtualization, but some versions of 'qemu-kvm' will use KVM
501        * regardless (even where this option appears in the help text).
502        * It is rumoured that there are versions of qemu where supplying
503        * this option when hardware virtualization is not available will
504        * cause qemu to fail, so we we have to check at least that
505        * /dev/kvm is openable.  That's not reliable, since /dev/kvm
506        * might be openable by qemu but not by us (think: SELinux) in
507        * which case the user would not get hardware virtualization,
508        * although at least shouldn't fail.  A giant clusterfuck with the
509        * qemu command line, again.
510        */
511       if (qemu_supports (g, "-enable-kvm") &&
512           is_openable (g, "/dev/kvm", O_RDWR))
513         add_cmdline (g, "-enable-kvm");
514     }
515
516     /* Newer versions of qemu (from around 2009/12) changed the
517      * behaviour of monitors so that an implicit '-monitor stdio' is
518      * assumed if we are in -nographic mode and there is no other
519      * -monitor option.  Only a single stdio device is allowed, so
520      * this broke the '-serial stdio' option.  There is a new flag
521      * called -nodefaults which gets rid of all this default crud, so
522      * let's use that to avoid this and any future surprises.
523      */
524     if (qemu_supports (g, "-nodefaults"))
525       add_cmdline (g, "-nodefaults");
526
527     add_cmdline (g, "-nographic");
528
529     snprintf (buf, sizeof buf, "%d", g->memsize);
530     add_cmdline (g, "-m");
531     add_cmdline (g, buf);
532
533     /* Force exit instead of reboot on panic */
534     add_cmdline (g, "-no-reboot");
535
536     /* These options recommended by KVM developers to improve reliability. */
537     if (qemu_supports (g, "-no-hpet"))
538       add_cmdline (g, "-no-hpet");
539
540     if (qemu_supports (g, "-rtc-td-hack"))
541       add_cmdline (g, "-rtc-td-hack");
542
543     /* Create the virtio serial bus. */
544     add_cmdline (g, "-device");
545     add_cmdline (g, "virtio-serial");
546
547 #if 0
548     /* Use virtio-console (a variant form of virtio-serial) for the
549      * guest's serial console.
550      */
551     add_cmdline (g, "-chardev");
552     add_cmdline (g, "stdio,id=console");
553     add_cmdline (g, "-device");
554     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
555 #else
556     /* When the above works ...  until then: */
557     add_cmdline (g, "-serial");
558     add_cmdline (g, "stdio");
559 #endif
560
561     /* Set up virtio-serial for the communications channel. */
562     add_cmdline (g, "-chardev");
563     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
564     add_cmdline (g, buf);
565     add_cmdline (g, "-device");
566     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
567
568     /* Enable user networking. */
569     if (g->enable_network) {
570       add_cmdline (g, "-netdev");
571       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
572       add_cmdline (g, "-device");
573       add_cmdline (g, NET_IF ",netdev=usernet");
574     }
575
576 #define LINUX_CMDLINE                                                   \
577     "panic=1 "         /* force kernel to panic if daemon exits */      \
578     "console=ttyS0 "   /* serial console */                             \
579     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
580     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
581     "acpi=off "        /* we don't need ACPI, turn it off */            \
582     "printk.time=1 "   /* display timestamp before kernel messages */   \
583     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
584
585     /* Linux kernel command line. */
586     snprintf (buf, sizeof buf,
587               LINUX_CMDLINE
588               "%s "             /* (selinux) */
589               "%s "             /* (verbose) */
590               "TERM=%s "        /* (TERM environment variable) */
591               "%s",             /* (append) */
592               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
593               g->verbose ? "guestfs_verbose=1" : "",
594               getenv ("TERM") ? : "linux",
595               g->append ? g->append : "");
596
597     add_cmdline (g, "-kernel");
598     add_cmdline (g, kernel);
599     add_cmdline (g, "-initrd");
600     add_cmdline (g, initrd);
601     add_cmdline (g, "-append");
602     add_cmdline (g, buf);
603
604     /* Add the ext2 appliance drive (last of all). */
605     if (appliance) {
606       const char *cachemode = "";
607       if (qemu_supports (g, "cache=")) {
608         if (qemu_supports (g, "unsafe"))
609           cachemode = ",cache=unsafe";
610         else if (qemu_supports (g, "writeback"))
611           cachemode = ",cache=writeback";
612       }
613
614       char buf2[PATH_MAX + 64];
615       add_cmdline (g, "-drive");
616       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
617                 appliance, cachemode);
618       add_cmdline (g, buf2);
619     }
620
621     /* Finish off the command line. */
622     incr_cmdline_size (g);
623     g->cmdline[g->cmdline_size-1] = NULL;
624
625     if (g->verbose)
626       guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
627
628     if (!g->direct) {
629       /* Set up stdin, stdout, stderr. */
630       close (0);
631       close (1);
632       close (wfd[1]);
633       close (rfd[0]);
634
635       /* Stdin. */
636       if (dup (wfd[0]) == -1) {
637       dup_failed:
638         perror ("dup failed");
639         _exit (EXIT_FAILURE);
640       }
641       /* Stdout. */
642       if (dup (rfd[1]) == -1)
643         goto dup_failed;
644
645       /* Particularly since qemu 0.15, qemu spews all sorts of debug
646        * information on stderr.  It is useful to both capture this and
647        * not confuse casual users, so send stderr to the pipe as well.
648        */
649       close (2);
650       if (dup (rfd[1]) == -1)
651         goto dup_failed;
652
653       close (wfd[0]);
654       close (rfd[1]);
655     }
656
657 #if 0
658     /* Set up a new process group, so we can signal this process
659      * and all subprocesses (eg. if qemu is really a shell script).
660      */
661     setpgid (0, 0);
662 #endif
663
664     setenv ("LC_ALL", "C", 1);
665
666     execv (g->qemu, g->cmdline); /* Run qemu. */
667     perror (g->qemu);
668     _exit (EXIT_FAILURE);
669   }
670
671   /* Parent (library). */
672   g->pid = r;
673
674   free (kernel);
675   kernel = NULL;
676   free (initrd);
677   initrd = NULL;
678   free (appliance);
679   appliance = NULL;
680
681   /* Fork the recovery process off which will kill qemu if the parent
682    * process fails to do so (eg. if the parent segfaults).
683    */
684   g->recoverypid = -1;
685   if (g->recovery_proc) {
686     r = fork ();
687     if (r == 0) {
688       pid_t qemu_pid = g->pid;
689       pid_t parent_pid = getppid ();
690
691       /* Writing to argv is hideously complicated and error prone.  See:
692        * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
693        */
694
695       /* Loop around waiting for one or both of the other processes to
696        * disappear.  It's fair to say this is very hairy.  The PIDs that
697        * we are looking at might be reused by another process.  We are
698        * effectively polling.  Is the cure worse than the disease?
699        */
700       for (;;) {
701         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
702           _exit (EXIT_SUCCESS);
703         if (kill (parent_pid, 0) == -1) {
704           /* Parent's gone away, qemu still around, so kill qemu. */
705           kill (qemu_pid, 9);
706           _exit (EXIT_SUCCESS);
707         }
708         sleep (2);
709       }
710     }
711
712     /* Don't worry, if the fork failed, this will be -1.  The recovery
713      * process isn't essential.
714      */
715     g->recoverypid = r;
716   }
717
718   if (!g->direct) {
719     /* Close the other ends of the pipe. */
720     close (wfd[0]);
721     close (rfd[1]);
722
723     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
724         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
725       perrorf (g, "fcntl");
726       goto cleanup1;
727     }
728
729     g->fd[0] = wfd[1];          /* stdin of child */
730     g->fd[1] = rfd[0];          /* stdout of child */
731   } else {
732     g->fd[0] = open ("/dev/null", O_RDWR);
733     if (g->fd[0] == -1) {
734       perrorf (g, "open /dev/null");
735       goto cleanup1;
736     }
737     g->fd[1] = dup (g->fd[0]);
738     if (g->fd[1] == -1) {
739       perrorf (g, "dup");
740       close (g->fd[0]);
741       goto cleanup1;
742     }
743   }
744
745   g->state = LAUNCHING;
746
747   /* Wait for qemu to start and to connect back to us via
748    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
749    */
750   r = guestfs___accept_from_daemon (g);
751   if (r == -1)
752     goto cleanup1;
753
754   close (g->sock); /* Close the listening socket. */
755   g->sock = r; /* This is the accepted data socket. */
756
757   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
758     perrorf (g, "fcntl");
759     goto cleanup1;
760   }
761
762   uint32_t size;
763   void *buf = NULL;
764   r = guestfs___recv_from_daemon (g, &size, &buf);
765   free (buf);
766
767   if (r == -1) return -1;
768
769   if (size != GUESTFS_LAUNCH_FLAG) {
770     error (g, _("guestfs_launch failed, see earlier error messages"));
771     goto cleanup1;
772   }
773
774   if (g->verbose)
775     guestfs___print_timestamped_message (g, "appliance is up");
776
777   /* This is possible in some really strange situations, such as
778    * guestfsd starts up OK but then qemu immediately exits.  Check for
779    * it because the caller is probably expecting to be able to send
780    * commands after this function returns.
781    */
782   if (g->state != READY) {
783     error (g, _("qemu launched and contacted daemon, but state != READY"));
784     goto cleanup1;
785   }
786
787   guestfs___launch_send_progress (g, 12);
788
789   return 0;
790
791  cleanup1:
792   if (!g->direct) {
793     close (wfd[1]);
794     close (rfd[0]);
795   }
796   if (g->pid > 0) kill (g->pid, 9);
797   if (g->recoverypid > 0) kill (g->recoverypid, 9);
798   if (g->pid > 0) waitpid (g->pid, NULL, 0);
799   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
800   g->fd[0] = -1;
801   g->fd[1] = -1;
802   g->pid = 0;
803   g->recoverypid = 0;
804   memset (&g->launch_t, 0, sizeof g->launch_t);
805
806  cleanup0:
807   if (g->sock >= 0) {
808     close (g->sock);
809     g->sock = -1;
810   }
811   g->state = CONFIG;
812   free (kernel);
813   free (initrd);
814   free (appliance);
815   return -1;
816 }
817
818 /* Alternate attach method: instead of launching the appliance,
819  * connect to an existing unix socket.
820  */
821 static int
822 connect_unix_socket (guestfs_h *g, const char *sockpath)
823 {
824   int r;
825   struct sockaddr_un addr;
826
827   /* Start the clock ... */
828   gettimeofday (&g->launch_t, NULL);
829
830   /* Set these to nothing so we don't try to kill random processes or
831    * read from random file descriptors.
832    */
833   g->pid = 0;
834   g->recoverypid = 0;
835   g->fd[0] = -1;
836   g->fd[1] = -1;
837
838   if (g->verbose)
839     guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
840
841   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
842   if (g->sock == -1) {
843     perrorf (g, "socket");
844     return -1;
845   }
846
847   addr.sun_family = AF_UNIX;
848   strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
849   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
850
851   g->state = LAUNCHING;
852
853   if (connect (g->sock, &addr, sizeof addr) == -1) {
854     perrorf (g, "bind");
855     goto cleanup;
856   }
857
858   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
859     perrorf (g, "fcntl");
860     goto cleanup;
861   }
862
863   uint32_t size;
864   void *buf = NULL;
865   r = guestfs___recv_from_daemon (g, &size, &buf);
866   free (buf);
867
868   if (r == -1) return -1;
869
870   if (size != GUESTFS_LAUNCH_FLAG) {
871     error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
872     goto cleanup;
873   }
874
875   if (g->verbose)
876     guestfs___print_timestamped_message (g, "connected");
877
878   if (g->state != READY) {
879     error (g, _("contacted guestfsd, but state != READY"));
880     goto cleanup;
881   }
882
883   return 0;
884
885  cleanup:
886   close (g->sock);
887   return -1;
888 }
889
890 /* launch (of the ordinary appliance) generates approximate progress
891  * messages.  Currently these are defined as follows:
892  *
893  *    0 / 12: launch clock starts
894  *    3 / 12: appliance created
895  *    6 / 12: detected that guest kernel started
896  *    9 / 12: detected that /init script is running
897  *   12 / 12: launch completed successfully
898  *
899  * Notes:
900  * (1) This is not a documented ABI and the behaviour may be changed
901  * or removed in future.
902  * (2) Messages are only sent if more than 5 seconds has elapsed
903  * since the launch clock started.
904  * (3) There is a gross hack in proto.c to make this work.
905  */
906 void
907 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
908 {
909   struct timeval tv;
910
911   gettimeofday (&tv, NULL);
912   if (timeval_diff (&g->launch_t, &tv) >= 5000) {
913     guestfs_progress progress_message =
914       { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
915
916     guestfs___progress_message_callback (g, &progress_message);
917   }
918 }
919
920 /* Return the location of the tmpdir (eg. "/tmp") and allow users
921  * to override it at runtime using $TMPDIR.
922  * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
923  */
924 const char *
925 guestfs_tmpdir (void)
926 {
927   const char *tmpdir;
928
929 #ifdef P_tmpdir
930   tmpdir = P_tmpdir;
931 #else
932   tmpdir = "/tmp";
933 #endif
934
935   const char *t = getenv ("TMPDIR");
936   if (t) tmpdir = t;
937
938   return tmpdir;
939 }
940
941 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
942  * allow users to override it at runtime using $TMPDIR.
943  * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
944  */
945 const char *
946 guestfs___persistent_tmpdir (void)
947 {
948   const char *tmpdir;
949
950   tmpdir = "/var/tmp";
951
952   const char *t = getenv ("TMPDIR");
953   if (t) tmpdir = t;
954
955   return tmpdir;
956 }
957
958 /* Compute Y - X and return the result in milliseconds.
959  * Approximately the same as this code:
960  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
961  */
962 static int64_t
963 timeval_diff (const struct timeval *x, const struct timeval *y)
964 {
965   int64_t msec;
966
967   msec = (y->tv_sec - x->tv_sec) * 1000;
968   msec += (y->tv_usec - x->tv_usec) / 1000;
969   return msec;
970 }
971
972 void
973 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
974 {
975   int i = 0;
976   int needs_quote;
977   char *buf = NULL;
978   size_t len;
979   FILE *fp;
980
981   fp = open_memstream (&buf, &len);
982   if (fp == NULL) {
983     warning (g, "open_memstream: %m");
984     return;
985   }
986
987   struct timeval tv;
988   gettimeofday (&tv, NULL);
989   fprintf (fp, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
990
991   while (argv[i]) {
992     if (argv[i][0] == '-') /* -option starts a new line */
993       fprintf (fp, " \\\n   ");
994
995     if (i > 0) fputc (' ', fp);
996
997     /* Does it need shell quoting?  This only deals with simple cases. */
998     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
999
1000     if (needs_quote) fputc ('\'', fp);
1001     fprintf (fp, "%s", argv[i]);
1002     if (needs_quote) fputc ('\'', fp);
1003     i++;
1004   }
1005
1006   fclose (fp);
1007
1008   debug (g, "%s", buf);
1009
1010   free (buf);
1011 }
1012
1013 void
1014 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1015 {
1016   va_list args;
1017   char *msg;
1018   int err;
1019   struct timeval tv;
1020
1021   va_start (args, fs);
1022   err = vasprintf (&msg, fs, args);
1023   va_end (args);
1024
1025   if (err < 0) return;
1026
1027   gettimeofday (&tv, NULL);
1028
1029   debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1030
1031   free (msg);
1032 }
1033
1034 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1035 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1036
1037 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1038  * 'qemu -version' so we know what options this qemu supports and
1039  * the version.
1040  */
1041 static int
1042 test_qemu (guestfs_h *g)
1043 {
1044   char cmd[1024];
1045   FILE *fp;
1046
1047   free (g->qemu_help);
1048   g->qemu_help = NULL;
1049   free (g->qemu_version);
1050   g->qemu_version = NULL;
1051
1052   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1053
1054   /* qemu -help should always work (qemu -version OTOH wasn't
1055    * supported by qemu 0.9).  If this command doesn't work then it
1056    * probably indicates that the qemu binary is missing.
1057    */
1058   if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1059     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1060     return -1;
1061   }
1062
1063   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1064             g->qemu);
1065
1066   /* Intentionally ignore errors from qemu -version. */
1067   ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1068
1069   return 0;
1070 }
1071
1072 static int
1073 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1074 {
1075   FILE *fp;
1076
1077   fp = popen (cmd, "r");
1078   if (fp == NULL)
1079     return -1;
1080
1081   if (read_all (g, fp, ret) == -1) {
1082     pclose (fp);
1083     return -1;
1084   }
1085
1086   if (pclose (fp) == -1)
1087     return -1;
1088
1089   return 0;
1090 }
1091
1092 static int
1093 read_all (guestfs_h *g, FILE *fp, char **ret)
1094 {
1095   int r, n = 0;
1096   char *p;
1097
1098  again:
1099   if (feof (fp)) {
1100     *ret = safe_realloc (g, *ret, n + 1);
1101     (*ret)[n] = '\0';
1102     return n;
1103   }
1104
1105   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1106   p = &(*ret)[n];
1107   r = fread (p, 1, BUFSIZ, fp);
1108   if (ferror (fp)) {
1109     perrorf (g, "read");
1110     return -1;
1111   }
1112   n += r;
1113   goto again;
1114 }
1115
1116 /* Test if option is supported by qemu command line (just by grepping
1117  * the help text).
1118  *
1119  * The first time this is used, it has to run the external qemu
1120  * binary.  If that fails, it returns -1.
1121  *
1122  * To just do the first-time run of the qemu binary, call this with
1123  * option == NULL, in which case it will return -1 if there was an
1124  * error doing that.
1125  */
1126 static int
1127 qemu_supports (guestfs_h *g, const char *option)
1128 {
1129   if (!g->qemu_help) {
1130     if (test_qemu (g) == -1)
1131       return -1;
1132   }
1133
1134   if (option == NULL)
1135     return 1;
1136
1137   return strstr (g->qemu_help, option) != NULL;
1138 }
1139
1140 /* Check if a file can be opened. */
1141 static int
1142 is_openable (guestfs_h *g, const char *path, int flags)
1143 {
1144   int fd = open (path, flags);
1145   if (fd == -1) {
1146     debug (g, "is_openable: %s: %m", path);
1147     return 0;
1148   }
1149   close (fd);
1150   return 1;
1151 }
1152
1153 /* You had to call this function after launch in versions <= 1.0.70,
1154  * but it is now a no-op.
1155  */
1156 int
1157 guestfs__wait_ready (guestfs_h *g)
1158 {
1159   if (g->state != READY)  {
1160     error (g, _("qemu has not been launched yet"));
1161     return -1;
1162   }
1163
1164   return 0;
1165 }
1166
1167 int
1168 guestfs__kill_subprocess (guestfs_h *g)
1169 {
1170   if (g->state == CONFIG) {
1171     error (g, _("no subprocess to kill"));
1172     return -1;
1173   }
1174
1175   debug (g, "sending SIGTERM to process %d", g->pid);
1176
1177   if (g->pid > 0) kill (g->pid, SIGTERM);
1178   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1179
1180   return 0;
1181 }
1182
1183 /* Access current state. */
1184 int
1185 guestfs__is_config (guestfs_h *g)
1186 {
1187   return g->state == CONFIG;
1188 }
1189
1190 int
1191 guestfs__is_launching (guestfs_h *g)
1192 {
1193   return g->state == LAUNCHING;
1194 }
1195
1196 int
1197 guestfs__is_ready (guestfs_h *g)
1198 {
1199   return g->state == READY;
1200 }
1201
1202 int
1203 guestfs__is_busy (guestfs_h *g)
1204 {
1205   return g->state == BUSY;
1206 }
1207
1208 int
1209 guestfs__get_state (guestfs_h *g)
1210 {
1211   return g->state;
1212 }