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