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