inspect: Refuse to download software hive if it is huge.
[libguestfs.git] / src / launch.c
1 /* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #include <sys/select.h>
35 #include <dirent.h>
36 #include <signal.h>
37 #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
68 #include "guestfs.h"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
72
73 static int qemu_supports (guestfs_h *g, const char *option);
74
75 /* Add a string to the current command line. */
76 static void
77 incr_cmdline_size (guestfs_h *g)
78 {
79   if (g->cmdline == NULL) {
80     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
81     g->cmdline_size = 1;
82     g->cmdline = safe_malloc (g, sizeof (char *));
83     g->cmdline[0] = NULL;
84   }
85
86   g->cmdline_size++;
87   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
88 }
89
90 static int
91 add_cmdline (guestfs_h *g, const char *str)
92 {
93   if (g->state != CONFIG) {
94     error (g,
95         _("command line cannot be altered after qemu subprocess launched"));
96     return -1;
97   }
98
99   incr_cmdline_size (g);
100   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
101   return 0;
102 }
103
104 int
105 guestfs___checkpoint_cmdline (guestfs_h *g)
106 {
107   return g->cmdline_size;
108 }
109
110 void
111 guestfs___rollback_cmdline (guestfs_h *g, int pos)
112 {
113   int i;
114
115   assert (g->cmdline_size >= pos);
116
117   for (i = g->cmdline_size - 1; i >= pos; --i)
118     free (g->cmdline[i]);
119
120   g->cmdline_size = pos;
121 }
122
123 /* Internal command to return the command line. */
124 char **
125 guestfs__debug_cmdline (guestfs_h *g)
126 {
127   int i;
128   char **r;
129
130   if (g->cmdline == NULL) {
131     r = safe_malloc (g, sizeof (char *) * 1);
132     r[0] = NULL;
133     return r;
134   }
135
136   r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
137   r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
138
139   for (i = 1; i < g->cmdline_size; ++i)
140     r[i] = safe_strdup (g, g->cmdline[i]);
141
142   r[g->cmdline_size] = NULL;
143
144   return r;                     /* caller frees */
145 }
146
147 int
148 guestfs__config (guestfs_h *g,
149                  const char *qemu_param, const char *qemu_value)
150 {
151   if (qemu_param[0] != '-') {
152     error (g, _("guestfs_config: parameter must begin with '-' character"));
153     return -1;
154   }
155
156   /* A bit fascist, but the user will probably break the extra
157    * parameters that we add if they try to set any of these.
158    */
159   if (STREQ (qemu_param, "-kernel") ||
160       STREQ (qemu_param, "-initrd") ||
161       STREQ (qemu_param, "-nographic") ||
162       STREQ (qemu_param, "-serial") ||
163       STREQ (qemu_param, "-full-screen") ||
164       STREQ (qemu_param, "-std-vga") ||
165       STREQ (qemu_param, "-vnc")) {
166     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
167     return -1;
168   }
169
170   if (add_cmdline (g, qemu_param) != 0) return -1;
171
172   if (qemu_value != NULL) {
173     if (add_cmdline (g, qemu_value) != 0) return -1;
174   }
175
176   return 0;
177 }
178
179 /* cache=off improves reliability in the event of a host crash.
180  *
181  * However this option causes qemu to try to open the file with
182  * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
183  * So we check if we can open the file with or without O_DIRECT,
184  * and use cache=off (or not) accordingly.
185  */
186 static int
187 test_cache_off (guestfs_h *g, const char *filename)
188 {
189   int fd = open (filename, O_RDONLY|O_DIRECT);
190   if (fd >= 0) {
191     close (fd);
192     return 1;
193   }
194
195   fd = open (filename, O_RDONLY);
196   if (fd >= 0) {
197     close (fd);
198     return 0;
199   }
200
201   perrorf (g, "%s", filename);
202   return -1;
203 }
204
205 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
206 static int
207 valid_format_iface (const char *str)
208 {
209   size_t len = strlen (str);
210
211   if (len == 0)
212     return 0;
213
214   while (len > 0) {
215     char c = *str++;
216     len--;
217     if (c != '-' && c != '_' && !c_isalnum (c))
218       return 0;
219   }
220   return 1;
221 }
222
223 int
224 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
225                          const struct guestfs_add_drive_opts_argv *optargs)
226 {
227   int readonly;
228   const char *format;
229   const char *iface;
230
231   if (strchr (filename, ',') != NULL) {
232     error (g, _("filename cannot contain ',' (comma) character"));
233     return -1;
234   }
235
236   readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
237              ? optargs->readonly : 0;
238   format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
239            ? optargs->format : NULL;
240   iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
241           ? optargs->iface : DRIVE_IF;
242
243   if (format && !valid_format_iface (format)) {
244     error (g, _("%s parameter is empty or contains disallowed characters"),
245            "format");
246     return -1;
247   }
248   if (!valid_format_iface (iface)) {
249     error (g, _("%s parameter is empty or contains disallowed characters"),
250            "iface");
251     return -1;
252   }
253
254   /* For writable files, see if we can use cache=off.  This also
255    * checks for the existence of the file.  For readonly we have
256    * to do the check explicitly.
257    */
258   int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
259   if (use_cache_off == -1)
260     return -1;
261
262   if (readonly) {
263     if (access (filename, F_OK) == -1) {
264       perrorf (g, "%s", filename);
265       return -1;
266     }
267   }
268
269   /* Construct the final -drive parameter. */
270   size_t len = 64 + strlen (filename) + strlen (iface);
271   if (format) len += strlen (format);
272   char buf[len];
273
274   snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
275             filename,
276             readonly ? ",snapshot=on" : "",
277             use_cache_off ? ",cache=off" : "",
278             format ? ",format=" : "",
279             format ? format : "",
280             iface);
281
282   return guestfs__config (g, "-drive", buf);
283 }
284
285 int
286 guestfs__add_drive (guestfs_h *g, const char *filename)
287 {
288   struct guestfs_add_drive_opts_argv optargs = {
289     .bitmask = 0,
290   };
291
292   return guestfs__add_drive_opts (g, filename, &optargs);
293 }
294
295 int
296 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
297 {
298   struct guestfs_add_drive_opts_argv optargs = {
299     .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
300     .readonly = 1,
301   };
302
303   return guestfs__add_drive_opts (g, filename, &optargs);
304 }
305
306 int
307 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
308                             const char *iface)
309 {
310   struct guestfs_add_drive_opts_argv optargs = {
311     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
312     .iface = iface,
313   };
314
315   return guestfs__add_drive_opts (g, filename, &optargs);
316 }
317
318 int
319 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
320                                const char *iface)
321 {
322   struct guestfs_add_drive_opts_argv optargs = {
323     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
324              | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
325     .iface = iface,
326     .readonly = 1,
327   };
328
329   return guestfs__add_drive_opts (g, filename, &optargs);
330 }
331
332 int
333 guestfs__add_cdrom (guestfs_h *g, const char *filename)
334 {
335   if (strchr (filename, ',') != NULL) {
336     error (g, _("filename cannot contain ',' (comma) character"));
337     return -1;
338   }
339
340   if (access (filename, F_OK) == -1) {
341     perrorf (g, "%s", filename);
342     return -1;
343   }
344
345   return guestfs__config (g, "-cdrom", filename);
346 }
347
348 static int is_openable (guestfs_h *g, const char *path, int flags);
349
350 int
351 guestfs__launch (guestfs_h *g)
352 {
353   int r;
354   int wfd[2], rfd[2];
355   int tries;
356   char unixsock[256];
357   struct sockaddr_un addr;
358
359   /* Configured? */
360   if (!g->cmdline) {
361     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
362     return -1;
363   }
364
365   if (g->state != CONFIG) {
366     error (g, _("the libguestfs handle has already been launched"));
367     return -1;
368   }
369
370   /* Start the clock ... */
371   gettimeofday (&g->launch_t, NULL);
372
373   /* Make the temporary directory. */
374   if (!g->tmpdir) {
375     TMP_TEMPLATE_ON_STACK (dir_template);
376     g->tmpdir = safe_strdup (g, dir_template);
377     if (mkdtemp (g->tmpdir) == NULL) {
378       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
379       goto cleanup0;
380     }
381   }
382
383   /* Allow anyone to read the temporary directory.  The socket in this
384    * directory won't be readable but anyone can see it exists if they
385    * want. (RHBZ#610880).
386    */
387   if (chmod (g->tmpdir, 0755) == -1)
388     fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
389
390   /* Locate and/or build the appliance. */
391   char *kernel = NULL, *initrd = NULL, *appliance = NULL;
392   if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
393     return -1;
394
395   if (g->verbose)
396     guestfs___print_timestamped_message (g, "begin testing qemu features");
397
398   /* Get qemu help text and version. */
399   if (qemu_supports (g, NULL) == -1)
400     goto cleanup0;
401
402   /* Using virtio-serial, we need to create a local Unix domain socket
403    * for qemu to connect to.
404    */
405   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
406   unlink (unixsock);
407
408   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
409   if (g->sock == -1) {
410     perrorf (g, "socket");
411     goto cleanup0;
412   }
413
414   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
415     perrorf (g, "fcntl");
416     goto cleanup0;
417   }
418
419   addr.sun_family = AF_UNIX;
420   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
421   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
422
423   if (bind (g->sock, &addr, sizeof addr) == -1) {
424     perrorf (g, "bind");
425     goto cleanup0;
426   }
427
428   if (listen (g->sock, 1) == -1) {
429     perrorf (g, "listen");
430     goto cleanup0;
431   }
432
433   if (!g->direct) {
434     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
435       perrorf (g, "pipe");
436       goto cleanup0;
437     }
438   }
439
440   if (g->verbose)
441     guestfs___print_timestamped_message (g, "finished testing qemu features");
442
443   r = fork ();
444   if (r == -1) {
445     perrorf (g, "fork");
446     if (!g->direct) {
447       close (wfd[0]);
448       close (wfd[1]);
449       close (rfd[0]);
450       close (rfd[1]);
451     }
452     goto cleanup0;
453   }
454
455   if (r == 0) {                 /* Child (qemu). */
456     char buf[256];
457
458     /* Set up the full command line.  Do this in the subprocess so we
459      * don't need to worry about cleaning up.
460      */
461     g->cmdline[0] = g->qemu;
462
463     if (qemu_supports (g, "-nodefconfig"))
464       add_cmdline (g, "-nodefconfig");
465
466     /* qemu sometimes needs this option to enable hardware
467      * virtualization, but some versions of 'qemu-kvm' will use KVM
468      * regardless (even where this option appears in the help text).
469      * It is rumoured that there are versions of qemu where supplying
470      * this option when hardware virtualization is not available will
471      * cause qemu to fail, so we we have to check at least that
472      * /dev/kvm is openable.  That's not reliable, since /dev/kvm
473      * might be openable by qemu but not by us (think: SELinux) in
474      * which case the user would not get hardware virtualization,
475      * although at least shouldn't fail.  A giant clusterfuck with the
476      * qemu command line, again.
477      */
478     if (qemu_supports (g, "-enable-kvm") &&
479         is_openable (g, "/dev/kvm", O_RDWR))
480       add_cmdline (g, "-enable-kvm");
481
482     /* Newer versions of qemu (from around 2009/12) changed the
483      * behaviour of monitors so that an implicit '-monitor stdio' is
484      * assumed if we are in -nographic mode and there is no other
485      * -monitor option.  Only a single stdio device is allowed, so
486      * this broke the '-serial stdio' option.  There is a new flag
487      * called -nodefaults which gets rid of all this default crud, so
488      * let's use that to avoid this and any future surprises.
489      */
490     if (qemu_supports (g, "-nodefaults"))
491       add_cmdline (g, "-nodefaults");
492
493     add_cmdline (g, "-nographic");
494
495     snprintf (buf, sizeof buf, "%d", g->memsize);
496     add_cmdline (g, "-m");
497     add_cmdline (g, buf);
498
499     /* Force exit instead of reboot on panic */
500     add_cmdline (g, "-no-reboot");
501
502     /* These options recommended by KVM developers to improve reliability. */
503     if (qemu_supports (g, "-no-hpet"))
504       add_cmdline (g, "-no-hpet");
505
506     if (qemu_supports (g, "-rtc-td-hack"))
507       add_cmdline (g, "-rtc-td-hack");
508
509     /* Create the virtio serial bus. */
510     add_cmdline (g, "-device");
511     add_cmdline (g, "virtio-serial");
512
513 #if 0
514     /* Use virtio-console (a variant form of virtio-serial) for the
515      * guest's serial console.
516      */
517     add_cmdline (g, "-chardev");
518     add_cmdline (g, "stdio,id=console");
519     add_cmdline (g, "-device");
520     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
521 #else
522     /* When the above works ...  until then: */
523     add_cmdline (g, "-serial");
524     add_cmdline (g, "stdio");
525 #endif
526
527     /* Set up virtio-serial for the communications channel. */
528     add_cmdline (g, "-chardev");
529     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
530     add_cmdline (g, buf);
531     add_cmdline (g, "-device");
532     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
533
534     /* Enable user networking. */
535     if (g->enable_network) {
536       add_cmdline (g, "-netdev");
537       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
538       add_cmdline (g, "-device");
539       add_cmdline (g, NET_IF ",netdev=usernet");
540     }
541
542 #define LINUX_CMDLINE                                                   \
543     "panic=1 "         /* force kernel to panic if daemon exits */      \
544     "console=ttyS0 "   /* serial console */                             \
545     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
546     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
547     "acpi=off "        /* we don't need ACPI, turn it off */            \
548     "printk.time=1 "   /* display timestamp before kernel messages */   \
549     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
550
551     /* Linux kernel command line. */
552     snprintf (buf, sizeof buf,
553               LINUX_CMDLINE
554               "%s "             /* (selinux) */
555               "%s "             /* (verbose) */
556               "TERM=%s "        /* (TERM environment variable) */
557               "%s",             /* (append) */
558               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
559               g->verbose ? "guestfs_verbose=1" : "",
560               getenv ("TERM") ? : "linux",
561               g->append ? g->append : "");
562
563     add_cmdline (g, "-kernel");
564     add_cmdline (g, kernel);
565     add_cmdline (g, "-initrd");
566     add_cmdline (g, initrd);
567     add_cmdline (g, "-append");
568     add_cmdline (g, buf);
569
570     /* Add the ext2 appliance drive (last of all). */
571     if (appliance) {
572       const char *cachemode = "";
573       if (qemu_supports (g, "cache=")) {
574         if (qemu_supports (g, "unsafe"))
575           cachemode = ",cache=unsafe";
576         else if (qemu_supports (g, "writeback"))
577           cachemode = ",cache=writeback";
578       }
579
580       char buf2[PATH_MAX + 64];
581       add_cmdline (g, "-drive");
582       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
583                 appliance, cachemode);
584       add_cmdline (g, buf2);
585     }
586
587     /* Finish off the command line. */
588     incr_cmdline_size (g);
589     g->cmdline[g->cmdline_size-1] = NULL;
590
591     if (g->verbose)
592       guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
593
594     if (!g->direct) {
595       /* Set up stdin, stdout. */
596       close (0);
597       close (1);
598       close (wfd[1]);
599       close (rfd[0]);
600
601       if (dup (wfd[0]) == -1) {
602       dup_failed:
603         perror ("dup failed");
604         _exit (EXIT_FAILURE);
605       }
606       if (dup (rfd[1]) == -1)
607         goto dup_failed;
608
609       close (wfd[0]);
610       close (rfd[1]);
611     }
612
613 #if 0
614     /* Set up a new process group, so we can signal this process
615      * and all subprocesses (eg. if qemu is really a shell script).
616      */
617     setpgid (0, 0);
618 #endif
619
620     setenv ("LC_ALL", "C", 1);
621
622     execv (g->qemu, g->cmdline); /* Run qemu. */
623     perror (g->qemu);
624     _exit (EXIT_FAILURE);
625   }
626
627   /* Parent (library). */
628   g->pid = r;
629
630   free (kernel);
631   kernel = NULL;
632   free (initrd);
633   initrd = NULL;
634   free (appliance);
635   appliance = NULL;
636
637   /* Fork the recovery process off which will kill qemu if the parent
638    * process fails to do so (eg. if the parent segfaults).
639    */
640   g->recoverypid = -1;
641   if (g->recovery_proc) {
642     r = fork ();
643     if (r == 0) {
644       pid_t qemu_pid = g->pid;
645       pid_t parent_pid = getppid ();
646
647       /* Writing to argv is hideously complicated and error prone.  See:
648        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
649        */
650
651       /* Loop around waiting for one or both of the other processes to
652        * disappear.  It's fair to say this is very hairy.  The PIDs that
653        * we are looking at might be reused by another process.  We are
654        * effectively polling.  Is the cure worse than the disease?
655        */
656       for (;;) {
657         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
658           _exit (EXIT_SUCCESS);
659         if (kill (parent_pid, 0) == -1) {
660           /* Parent's gone away, qemu still around, so kill qemu. */
661           kill (qemu_pid, 9);
662           _exit (EXIT_SUCCESS);
663         }
664         sleep (2);
665       }
666     }
667
668     /* Don't worry, if the fork failed, this will be -1.  The recovery
669      * process isn't essential.
670      */
671     g->recoverypid = r;
672   }
673
674   if (!g->direct) {
675     /* Close the other ends of the pipe. */
676     close (wfd[0]);
677     close (rfd[1]);
678
679     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
680         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
681       perrorf (g, "fcntl");
682       goto cleanup1;
683     }
684
685     g->fd[0] = wfd[1];          /* stdin of child */
686     g->fd[1] = rfd[0];          /* stdout of child */
687   } else {
688     g->fd[0] = open ("/dev/null", O_RDWR);
689     if (g->fd[0] == -1) {
690       perrorf (g, "open /dev/null");
691       goto cleanup1;
692     }
693     g->fd[1] = dup (g->fd[0]);
694     if (g->fd[1] == -1) {
695       perrorf (g, "dup");
696       close (g->fd[0]);
697       goto cleanup1;
698     }
699   }
700
701   g->state = LAUNCHING;
702
703   /* Wait for qemu to start and to connect back to us via
704    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
705    */
706   r = guestfs___accept_from_daemon (g);
707   if (r == -1)
708     goto cleanup1;
709
710   close (g->sock); /* Close the listening socket. */
711   g->sock = r; /* This is the accepted data socket. */
712
713   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
714     perrorf (g, "fcntl");
715     goto cleanup1;
716   }
717
718   uint32_t size;
719   void *buf = NULL;
720   r = guestfs___recv_from_daemon (g, &size, &buf);
721   free (buf);
722
723   if (r == -1) return -1;
724
725   if (size != GUESTFS_LAUNCH_FLAG) {
726     error (g, _("guestfs_launch failed, see earlier error messages"));
727     goto cleanup1;
728   }
729
730   if (g->verbose)
731     guestfs___print_timestamped_message (g, "appliance is up");
732
733   /* This is possible in some really strange situations, such as
734    * guestfsd starts up OK but then qemu immediately exits.  Check for
735    * it because the caller is probably expecting to be able to send
736    * commands after this function returns.
737    */
738   if (g->state != READY) {
739     error (g, _("qemu launched and contacted daemon, but state != READY"));
740     goto cleanup1;
741   }
742
743   return 0;
744
745  cleanup1:
746   if (!g->direct) {
747     close (wfd[1]);
748     close (rfd[0]);
749   }
750   if (g->pid > 0) kill (g->pid, 9);
751   if (g->recoverypid > 0) kill (g->recoverypid, 9);
752   waitpid (g->pid, NULL, 0);
753   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
754   g->fd[0] = -1;
755   g->fd[1] = -1;
756   g->pid = 0;
757   g->recoverypid = 0;
758   memset (&g->launch_t, 0, sizeof g->launch_t);
759
760  cleanup0:
761   if (g->sock >= 0) {
762     close (g->sock);
763     g->sock = -1;
764   }
765   g->state = CONFIG;
766   free (kernel);
767   free (initrd);
768   free (appliance);
769   return -1;
770 }
771
772 /* Return the location of the tmpdir (eg. "/tmp") and allow users
773  * to override it at runtime using $TMPDIR.
774  */
775 const char *
776 guestfs_tmpdir (void)
777 {
778   const char *tmpdir;
779
780 #ifdef P_tmpdir
781   tmpdir = P_tmpdir;
782 #else
783   tmpdir = "/tmp";
784 #endif
785
786   const char *t = getenv ("TMPDIR");
787   if (t) tmpdir = t;
788
789   return tmpdir;
790 }
791
792 /* Compute Y - X and return the result in milliseconds.
793  * Approximately the same as this code:
794  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
795  */
796 static int64_t
797 timeval_diff (const struct timeval *x, const struct timeval *y)
798 {
799   int64_t msec;
800
801   msec = (y->tv_sec - x->tv_sec) * 1000;
802   msec += (y->tv_usec - x->tv_usec) / 1000;
803   return msec;
804 }
805
806 void
807 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
808 {
809   int i = 0;
810   int needs_quote;
811
812   struct timeval tv;
813   gettimeofday (&tv, NULL);
814   fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
815
816   while (argv[i]) {
817     if (argv[i][0] == '-') /* -option starts a new line */
818       fprintf (stderr, " \\\n   ");
819
820     if (i > 0) fputc (' ', stderr);
821
822     /* Does it need shell quoting?  This only deals with simple cases. */
823     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
824
825     if (needs_quote) fputc ('\'', stderr);
826     fprintf (stderr, "%s", argv[i]);
827     if (needs_quote) fputc ('\'', stderr);
828     i++;
829   }
830
831   fputc ('\n', stderr);
832 }
833
834 void
835 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
836 {
837   va_list args;
838   char *msg;
839   int err;
840   struct timeval tv;
841
842   va_start (args, fs);
843   err = vasprintf (&msg, fs, args);
844   va_end (args);
845
846   if (err < 0) return;
847
848   gettimeofday (&tv, NULL);
849
850   fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
851            timeval_diff (&g->launch_t, &tv), msg);
852
853   free (msg);
854 }
855
856 static int read_all (guestfs_h *g, FILE *fp, char **ret);
857
858 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
859  * 'qemu -version' so we know what options this qemu supports and
860  * the version.
861  */
862 static int
863 test_qemu (guestfs_h *g)
864 {
865   char cmd[1024];
866   FILE *fp;
867
868   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
869
870   fp = popen (cmd, "r");
871   /* qemu -help should always work (qemu -version OTOH wasn't
872    * supported by qemu 0.9).  If this command doesn't work then it
873    * probably indicates that the qemu binary is missing.
874    */
875   if (!fp) {
876     /* XXX This error is never printed, even if the qemu binary
877      * doesn't exist.  Why?
878      */
879   error:
880     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
881     return -1;
882   }
883
884   if (read_all (g, fp, &g->qemu_help) == -1)
885     goto error;
886
887   if (pclose (fp) == -1)
888     goto error;
889
890   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
891             g->qemu);
892
893   fp = popen (cmd, "r");
894   if (fp) {
895     /* Intentionally ignore errors. */
896     read_all (g, fp, &g->qemu_version);
897     pclose (fp);
898   }
899
900   return 0;
901 }
902
903 static int
904 read_all (guestfs_h *g, FILE *fp, char **ret)
905 {
906   int r, n = 0;
907   char *p;
908
909  again:
910   if (feof (fp)) {
911     *ret = safe_realloc (g, *ret, n + 1);
912     (*ret)[n] = '\0';
913     return n;
914   }
915
916   *ret = safe_realloc (g, *ret, n + BUFSIZ);
917   p = &(*ret)[n];
918   r = fread (p, 1, BUFSIZ, fp);
919   if (ferror (fp)) {
920     perrorf (g, "read");
921     return -1;
922   }
923   n += r;
924   goto again;
925 }
926
927 /* Test if option is supported by qemu command line (just by grepping
928  * the help text).
929  *
930  * The first time this is used, it has to run the external qemu
931  * binary.  If that fails, it returns -1.
932  *
933  * To just do the first-time run of the qemu binary, call this with
934  * option == NULL, in which case it will return -1 if there was an
935  * error doing that.
936  */
937 static int
938 qemu_supports (guestfs_h *g, const char *option)
939 {
940   if (!g->qemu_help) {
941     if (test_qemu (g) == -1)
942       return -1;
943   }
944
945   if (option == NULL)
946     return 1;
947
948   return strstr (g->qemu_help, option) != NULL;
949 }
950
951 /* Check if a file can be opened. */
952 static int
953 is_openable (guestfs_h *g, const char *path, int flags)
954 {
955   int fd = open (path, flags);
956   if (fd == -1) {
957     if (g->verbose)
958       perror (path);
959     return 0;
960   }
961   close (fd);
962   return 1;
963 }
964
965 /* You had to call this function after launch in versions <= 1.0.70,
966  * but it is now a no-op.
967  */
968 int
969 guestfs__wait_ready (guestfs_h *g)
970 {
971   if (g->state != READY)  {
972     error (g, _("qemu has not been launched yet"));
973     return -1;
974   }
975
976   return 0;
977 }
978
979 int
980 guestfs__kill_subprocess (guestfs_h *g)
981 {
982   if (g->state == CONFIG) {
983     error (g, _("no subprocess to kill"));
984     return -1;
985   }
986
987   if (g->verbose)
988     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
989
990   if (g->pid > 0) kill (g->pid, SIGTERM);
991   if (g->recoverypid > 0) kill (g->recoverypid, 9);
992
993   return 0;
994 }
995
996 /* Access current state. */
997 int
998 guestfs__is_config (guestfs_h *g)
999 {
1000   return g->state == CONFIG;
1001 }
1002
1003 int
1004 guestfs__is_launching (guestfs_h *g)
1005 {
1006   return g->state == LAUNCHING;
1007 }
1008
1009 int
1010 guestfs__is_ready (guestfs_h *g)
1011 {
1012   return g->state == READY;
1013 }
1014
1015 int
1016 guestfs__is_busy (guestfs_h *g)
1017 {
1018   return g->state == BUSY;
1019 }
1020
1021 int
1022 guestfs__get_state (guestfs_h *g)
1023 {
1024   return g->state;
1025 }