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