Revert "Remove ocaml/.depend from git."
[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
306 int
307 guestfs__launch (guestfs_h *g)
308 {
309   int r;
310   int wfd[2], rfd[2];
311   int tries;
312   char unixsock[256];
313   struct sockaddr_un addr;
314
315   /* Configured? */
316   if (!g->cmdline) {
317     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
318     return -1;
319   }
320
321   if (g->state != CONFIG) {
322     error (g, _("the libguestfs handle has already been launched"));
323     return -1;
324   }
325
326   /* Start the clock ... */
327   gettimeofday (&g->launch_t, NULL);
328
329   /* Make the temporary directory. */
330   if (!g->tmpdir) {
331     TMP_TEMPLATE_ON_STACK (dir_template);
332     g->tmpdir = safe_strdup (g, dir_template);
333     if (mkdtemp (g->tmpdir) == NULL) {
334       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
335       goto cleanup0;
336     }
337   }
338
339   /* Allow anyone to read the temporary directory.  The socket in this
340    * directory won't be readable but anyone can see it exists if they
341    * want. (RHBZ#610880).
342    */
343   if (chmod (g->tmpdir, 0755) == -1)
344     fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
345
346   /* Locate and/or build the appliance. */
347   char *kernel = NULL, *initrd = NULL, *appliance = NULL;
348   if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
349     return -1;
350
351   if (g->verbose)
352     guestfs___print_timestamped_message (g, "begin testing qemu features");
353
354   /* Get qemu help text and version. */
355   if (qemu_supports (g, NULL) == -1)
356     goto cleanup0;
357
358   /* Using virtio-serial, we need to create a local Unix domain socket
359    * for qemu to connect to.
360    */
361   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
362   unlink (unixsock);
363
364   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
365   if (g->sock == -1) {
366     perrorf (g, "socket");
367     goto cleanup0;
368   }
369
370   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
371     perrorf (g, "fcntl");
372     goto cleanup0;
373   }
374
375   addr.sun_family = AF_UNIX;
376   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
377   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
378
379   if (bind (g->sock, &addr, sizeof addr) == -1) {
380     perrorf (g, "bind");
381     goto cleanup0;
382   }
383
384   if (listen (g->sock, 1) == -1) {
385     perrorf (g, "listen");
386     goto cleanup0;
387   }
388
389   if (!g->direct) {
390     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
391       perrorf (g, "pipe");
392       goto cleanup0;
393     }
394   }
395
396   if (g->verbose)
397     guestfs___print_timestamped_message (g, "finished testing qemu features");
398
399   r = fork ();
400   if (r == -1) {
401     perrorf (g, "fork");
402     if (!g->direct) {
403       close (wfd[0]);
404       close (wfd[1]);
405       close (rfd[0]);
406       close (rfd[1]);
407     }
408     goto cleanup0;
409   }
410
411   if (r == 0) {                 /* Child (qemu). */
412     char buf[256];
413
414     /* Set up the full command line.  Do this in the subprocess so we
415      * don't need to worry about cleaning up.
416      */
417     g->cmdline[0] = g->qemu;
418
419     if (qemu_supports (g, "-nodefconfig"))
420       add_cmdline (g, "-nodefconfig");
421
422     /* qemu sometimes needs this option to enable hardware
423      * virtualization, but some versions of 'qemu-kvm' will use KVM
424      * regardless (even where this option appears in the help text).
425      * It is rumoured that there are versions of qemu where supplying
426      * this option when hardware virtualization is not available will
427      * cause qemu to fail, so we we have to check at least that
428      * /dev/kvm is openable.  That's not reliable, since /dev/kvm
429      * might be openable by qemu but not by us (think: SELinux) in
430      * which case the user would not get hardware virtualization,
431      * although at least shouldn't fail.  A giant clusterfuck with the
432      * qemu command line, again.
433      */
434     if (qemu_supports (g, "-enable-kvm") &&
435         is_openable (g, "/dev/kvm", O_RDWR))
436       add_cmdline (g, "-enable-kvm");
437
438     /* Newer versions of qemu (from around 2009/12) changed the
439      * behaviour of monitors so that an implicit '-monitor stdio' is
440      * assumed if we are in -nographic mode and there is no other
441      * -monitor option.  Only a single stdio device is allowed, so
442      * this broke the '-serial stdio' option.  There is a new flag
443      * called -nodefaults which gets rid of all this default crud, so
444      * let's use that to avoid this and any future surprises.
445      */
446     if (qemu_supports (g, "-nodefaults"))
447       add_cmdline (g, "-nodefaults");
448
449     add_cmdline (g, "-nographic");
450
451     snprintf (buf, sizeof buf, "%d", g->memsize);
452     add_cmdline (g, "-m");
453     add_cmdline (g, buf);
454
455     /* Force exit instead of reboot on panic */
456     add_cmdline (g, "-no-reboot");
457
458     /* These options recommended by KVM developers to improve reliability. */
459     if (qemu_supports (g, "-no-hpet"))
460       add_cmdline (g, "-no-hpet");
461
462     if (qemu_supports (g, "-rtc-td-hack"))
463       add_cmdline (g, "-rtc-td-hack");
464
465     /* Create the virtio serial bus. */
466     add_cmdline (g, "-device");
467     add_cmdline (g, "virtio-serial");
468
469 #if 0
470     /* Use virtio-console (a variant form of virtio-serial) for the
471      * guest's serial console.
472      */
473     add_cmdline (g, "-chardev");
474     add_cmdline (g, "stdio,id=console");
475     add_cmdline (g, "-device");
476     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
477 #else
478     /* When the above works ...  until then: */
479     add_cmdline (g, "-serial");
480     add_cmdline (g, "stdio");
481 #endif
482
483     /* Set up virtio-serial for the communications channel. */
484     add_cmdline (g, "-chardev");
485     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
486     add_cmdline (g, buf);
487     add_cmdline (g, "-device");
488     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
489
490     /* Enable user networking. */
491     if (g->enable_network) {
492       add_cmdline (g, "-netdev");
493       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
494       add_cmdline (g, "-device");
495       add_cmdline (g, NET_IF ",netdev=usernet");
496     }
497
498 #define LINUX_CMDLINE                                                   \
499     "panic=1 "         /* force kernel to panic if daemon exits */      \
500     "console=ttyS0 "   /* serial console */                             \
501     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
502     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
503     "acpi=off "        /* we don't need ACPI, turn it off */            \
504     "printk.time=1 "   /* display timestamp before kernel messages */   \
505     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
506
507     /* Linux kernel command line. */
508     snprintf (buf, sizeof buf,
509               LINUX_CMDLINE
510               "%s "             /* (selinux) */
511               "%s "             /* (verbose) */
512               "TERM=%s "        /* (TERM environment variable) */
513               "%s",             /* (append) */
514               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
515               g->verbose ? "guestfs_verbose=1" : "",
516               getenv ("TERM") ? : "linux",
517               g->append ? g->append : "");
518
519     add_cmdline (g, "-kernel");
520     add_cmdline (g, kernel);
521     add_cmdline (g, "-initrd");
522     add_cmdline (g, initrd);
523     add_cmdline (g, "-append");
524     add_cmdline (g, buf);
525
526     /* Add the ext2 appliance drive (last of all). */
527     if (appliance) {
528       const char *cachemode = "";
529       if (qemu_supports (g, "cache=")) {
530         if (qemu_supports (g, "unsafe"))
531           cachemode = ",cache=unsafe";
532         else if (qemu_supports (g, "writeback"))
533           cachemode = ",cache=writeback";
534       }
535
536       char buf2[PATH_MAX + 64];
537       add_cmdline (g, "-drive");
538       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
539                 appliance, cachemode);
540       add_cmdline (g, buf2);
541     }
542
543     /* Finish off the command line. */
544     incr_cmdline_size (g);
545     g->cmdline[g->cmdline_size-1] = NULL;
546
547     if (g->verbose)
548       guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
549
550     if (!g->direct) {
551       /* Set up stdin, stdout. */
552       close (0);
553       close (1);
554       close (wfd[1]);
555       close (rfd[0]);
556
557       if (dup (wfd[0]) == -1) {
558       dup_failed:
559         perror ("dup failed");
560         _exit (EXIT_FAILURE);
561       }
562       if (dup (rfd[1]) == -1)
563         goto dup_failed;
564
565       close (wfd[0]);
566       close (rfd[1]);
567     }
568
569 #if 0
570     /* Set up a new process group, so we can signal this process
571      * and all subprocesses (eg. if qemu is really a shell script).
572      */
573     setpgid (0, 0);
574 #endif
575
576     setenv ("LC_ALL", "C", 1);
577
578     execv (g->qemu, g->cmdline); /* Run qemu. */
579     perror (g->qemu);
580     _exit (EXIT_FAILURE);
581   }
582
583   /* Parent (library). */
584   g->pid = r;
585
586   free (kernel);
587   kernel = NULL;
588   free (initrd);
589   initrd = NULL;
590   free (appliance);
591   appliance = NULL;
592
593   /* Fork the recovery process off which will kill qemu if the parent
594    * process fails to do so (eg. if the parent segfaults).
595    */
596   g->recoverypid = -1;
597   if (g->recovery_proc) {
598     r = fork ();
599     if (r == 0) {
600       pid_t qemu_pid = g->pid;
601       pid_t parent_pid = getppid ();
602
603       /* Writing to argv is hideously complicated and error prone.  See:
604        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
605        */
606
607       /* Loop around waiting for one or both of the other processes to
608        * disappear.  It's fair to say this is very hairy.  The PIDs that
609        * we are looking at might be reused by another process.  We are
610        * effectively polling.  Is the cure worse than the disease?
611        */
612       for (;;) {
613         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
614           _exit (EXIT_SUCCESS);
615         if (kill (parent_pid, 0) == -1) {
616           /* Parent's gone away, qemu still around, so kill qemu. */
617           kill (qemu_pid, 9);
618           _exit (EXIT_SUCCESS);
619         }
620         sleep (2);
621       }
622     }
623
624     /* Don't worry, if the fork failed, this will be -1.  The recovery
625      * process isn't essential.
626      */
627     g->recoverypid = r;
628   }
629
630   if (!g->direct) {
631     /* Close the other ends of the pipe. */
632     close (wfd[0]);
633     close (rfd[1]);
634
635     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
636         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
637       perrorf (g, "fcntl");
638       goto cleanup1;
639     }
640
641     g->fd[0] = wfd[1];          /* stdin of child */
642     g->fd[1] = rfd[0];          /* stdout of child */
643   } else {
644     g->fd[0] = open ("/dev/null", O_RDWR);
645     if (g->fd[0] == -1) {
646       perrorf (g, "open /dev/null");
647       goto cleanup1;
648     }
649     g->fd[1] = dup (g->fd[0]);
650     if (g->fd[1] == -1) {
651       perrorf (g, "dup");
652       close (g->fd[0]);
653       goto cleanup1;
654     }
655   }
656
657   g->state = LAUNCHING;
658
659   /* Wait for qemu to start and to connect back to us via
660    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
661    */
662   r = guestfs___accept_from_daemon (g);
663   if (r == -1)
664     goto cleanup1;
665
666   close (g->sock); /* Close the listening socket. */
667   g->sock = r; /* This is the accepted data socket. */
668
669   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
670     perrorf (g, "fcntl");
671     goto cleanup1;
672   }
673
674   uint32_t size;
675   void *buf = NULL;
676   r = guestfs___recv_from_daemon (g, &size, &buf);
677   free (buf);
678
679   if (r == -1) return -1;
680
681   if (size != GUESTFS_LAUNCH_FLAG) {
682     error (g, _("guestfs_launch failed, see earlier error messages"));
683     goto cleanup1;
684   }
685
686   if (g->verbose)
687     guestfs___print_timestamped_message (g, "appliance is up");
688
689   /* This is possible in some really strange situations, such as
690    * guestfsd starts up OK but then qemu immediately exits.  Check for
691    * it because the caller is probably expecting to be able to send
692    * commands after this function returns.
693    */
694   if (g->state != READY) {
695     error (g, _("qemu launched and contacted daemon, but state != READY"));
696     goto cleanup1;
697   }
698
699   return 0;
700
701  cleanup1:
702   if (!g->direct) {
703     close (wfd[1]);
704     close (rfd[0]);
705   }
706   if (g->pid > 0) kill (g->pid, 9);
707   if (g->recoverypid > 0) kill (g->recoverypid, 9);
708   waitpid (g->pid, NULL, 0);
709   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
710   g->fd[0] = -1;
711   g->fd[1] = -1;
712   g->pid = 0;
713   g->recoverypid = 0;
714   memset (&g->launch_t, 0, sizeof g->launch_t);
715
716  cleanup0:
717   if (g->sock >= 0) {
718     close (g->sock);
719     g->sock = -1;
720   }
721   g->state = CONFIG;
722   free (kernel);
723   free (initrd);
724   free (appliance);
725   return -1;
726 }
727
728 /* Return the location of the tmpdir (eg. "/tmp") and allow users
729  * to override it at runtime using $TMPDIR.
730  */
731 const char *
732 guestfs_tmpdir (void)
733 {
734   const char *tmpdir;
735
736 #ifdef P_tmpdir
737   tmpdir = P_tmpdir;
738 #else
739   tmpdir = "/tmp";
740 #endif
741
742   const char *t = getenv ("TMPDIR");
743   if (t) tmpdir = t;
744
745   return tmpdir;
746 }
747
748 /* Compute Y - X and return the result in milliseconds.
749  * Approximately the same as this code:
750  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
751  */
752 static int64_t
753 timeval_diff (const struct timeval *x, const struct timeval *y)
754 {
755   int64_t msec;
756
757   msec = (y->tv_sec - x->tv_sec) * 1000;
758   msec += (y->tv_usec - x->tv_usec) / 1000;
759   return msec;
760 }
761
762 void
763 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
764 {
765   int i = 0;
766   int needs_quote;
767
768   struct timeval tv;
769   gettimeofday (&tv, NULL);
770   fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
771
772   while (argv[i]) {
773     if (argv[i][0] == '-') /* -option starts a new line */
774       fprintf (stderr, " \\\n   ");
775
776     if (i > 0) fputc (' ', stderr);
777
778     /* Does it need shell quoting?  This only deals with simple cases. */
779     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
780
781     if (needs_quote) fputc ('\'', stderr);
782     fprintf (stderr, "%s", argv[i]);
783     if (needs_quote) fputc ('\'', stderr);
784     i++;
785   }
786
787   fputc ('\n', stderr);
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 }