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