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