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