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