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