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