lib: Add guestfs___remove_tmpdir helper function.
[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 <sys/types.h>
36 #include <sys/wait.h>
37 #include <dirent.h>
38 #include <signal.h>
39 #include <assert.h>
40
41 #include <rpc/types.h>
42 #include <rpc/xdr.h>
43
44 #ifdef HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47
48 #ifdef HAVE_SYS_TYPES_H
49 #include <sys/types.h>
50 #endif
51
52 #ifdef HAVE_SYS_WAIT_H
53 #include <sys/wait.h>
54 #endif
55
56 #ifdef HAVE_SYS_SOCKET_H
57 #include <sys/socket.h>
58 #endif
59
60 #ifdef HAVE_SYS_UN_H
61 #include <sys/un.h>
62 #endif
63
64 #include <arpa/inet.h>
65 #include <netinet/in.h>
66
67 #include "c-ctype.h"
68 #include "ignore-value.h"
69 #include "glthread/lock.h"
70
71 #include "guestfs.h"
72 #include "guestfs-internal.h"
73 #include "guestfs-internal-actions.h"
74 #include "guestfs_protocol.h"
75
76 static int launch_appliance (guestfs_h *g);
77 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
78 static void print_qemu_command_line (guestfs_h *g, char **argv);
79 static int connect_unix_socket (guestfs_h *g, const char *sock);
80 static int qemu_supports (guestfs_h *g, const char *option);
81 static char *qemu_drive_param (guestfs_h *g, const struct drive *drv);
82
83 #if 0
84 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
85
86 static void compile_regexps (void) __attribute__((constructor));
87 static void free_regexps (void) __attribute__((destructor));
88
89 static void
90 compile_regexps (void)
91 {
92   const char *err;
93   int offset;
94
95 #define COMPILE(re,pattern,options)                                     \
96   do {                                                                  \
97     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
98     if (re == NULL) {                                                   \
99       ignore_value (write (2, err, strlen (err)));                      \
100       abort ();                                                         \
101     }                                                                   \
102   } while (0)
103 }
104
105 static void
106 free_regexps (void)
107 {
108 }
109 #endif
110
111 /* Functions to add a string to the current command line. */
112 static void
113 alloc_cmdline (guestfs_h *g)
114 {
115   if (g->cmdline == NULL) {
116     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
117     g->cmdline_size = 1;
118     g->cmdline = safe_malloc (g, sizeof (char *));
119     g->cmdline[0] = NULL;
120   }
121 }
122
123 static void
124 incr_cmdline_size (guestfs_h *g)
125 {
126   alloc_cmdline (g);
127   g->cmdline_size++;
128   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
129 }
130
131 static int
132 add_cmdline (guestfs_h *g, const char *str)
133 {
134   if (g->state != CONFIG) {
135     error (g,
136         _("command line cannot be altered after qemu subprocess launched"));
137     return -1;
138   }
139
140   incr_cmdline_size (g);
141   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
142   return 0;
143 }
144
145 struct drive **
146 guestfs___checkpoint_drives (guestfs_h *g)
147 {
148   struct drive **i = &g->drives;
149   while (*i != NULL) i = &((*i)->next);
150   return i;
151 }
152
153 void
154 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
155 {
156   guestfs___free_drives(i);
157 }
158
159 /* Internal command to return the command line. */
160 char **
161 guestfs__debug_cmdline (guestfs_h *g)
162 {
163   size_t i;
164   char **r;
165
166   alloc_cmdline (g);
167
168   r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
169   r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
170
171   for (i = 1; i < g->cmdline_size; ++i)
172     r[i] = safe_strdup (g, g->cmdline[i]);
173
174   r[g->cmdline_size] = NULL;
175
176   return r;                     /* caller frees */
177 }
178
179 /* Internal command to return the list of drives. */
180 char **
181 guestfs__debug_drives (guestfs_h *g)
182 {
183   size_t i, count;
184   char **ret;
185   struct drive *drv;
186
187   for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
188     ;
189
190   ret = safe_malloc (g, sizeof (char *) * (count + 1));
191
192   for (i = 0, drv = g->drives; drv; i++, drv = drv->next)
193     ret[i] = qemu_drive_param (g, drv);
194
195   ret[count] = NULL;
196
197   return ret;                   /* caller frees */
198 }
199
200 int
201 guestfs__config (guestfs_h *g,
202                  const char *qemu_param, const char *qemu_value)
203 {
204   if (qemu_param[0] != '-') {
205     error (g, _("guestfs_config: parameter must begin with '-' character"));
206     return -1;
207   }
208
209   /* A bit fascist, but the user will probably break the extra
210    * parameters that we add if they try to set any of these.
211    */
212   if (STREQ (qemu_param, "-kernel") ||
213       STREQ (qemu_param, "-initrd") ||
214       STREQ (qemu_param, "-nographic") ||
215       STREQ (qemu_param, "-serial") ||
216       STREQ (qemu_param, "-full-screen") ||
217       STREQ (qemu_param, "-std-vga") ||
218       STREQ (qemu_param, "-vnc")) {
219     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
220     return -1;
221   }
222
223   if (add_cmdline (g, qemu_param) != 0) return -1;
224
225   if (qemu_value != NULL) {
226     if (add_cmdline (g, qemu_value) != 0) return -1;
227   }
228
229   return 0;
230 }
231
232 /* cache=off improves reliability in the event of a host crash.
233  *
234  * However this option causes qemu to try to open the file with
235  * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
236  * So we check if we can open the file with or without O_DIRECT,
237  * and use cache=off (or not) accordingly.
238  *
239  * NB: This function is only called on the !readonly path.  We must
240  * try to open with O_RDWR to test that the file is readable and
241  * writable here.
242  */
243 static int
244 test_cache_off (guestfs_h *g, const char *filename)
245 {
246   int fd = open (filename, O_RDWR|O_DIRECT);
247   if (fd >= 0) {
248     close (fd);
249     return 1;
250   }
251
252   fd = open (filename, O_RDWR);
253   if (fd >= 0) {
254     close (fd);
255     return 0;
256   }
257
258   perrorf (g, "%s", filename);
259   return -1;
260 }
261
262 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
263 static int
264 valid_format_iface (const char *str)
265 {
266   size_t len = strlen (str);
267
268   if (len == 0)
269     return 0;
270
271   while (len > 0) {
272     char c = *str++;
273     len--;
274     if (c != '-' && c != '_' && !c_isalnum (c))
275       return 0;
276   }
277   return 1;
278 }
279
280 int
281 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
282                          const struct guestfs_add_drive_opts_argv *optargs)
283 {
284   int readonly;
285   char *format;
286   char *iface;
287   char *name;
288   int use_cache_off;
289
290   if (strchr (filename, ',') != NULL) {
291     error (g, _("filename cannot contain ',' (comma) character"));
292     return -1;
293   }
294
295   readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
296              ? optargs->readonly : 0;
297   format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
298            ? safe_strdup (g, optargs->format) : NULL;
299   iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
300           ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
301   name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
302           ? safe_strdup (g, optargs->name) : NULL;
303
304   if (format && !valid_format_iface (format)) {
305     error (g, _("%s parameter is empty or contains disallowed characters"),
306            "format");
307     free (format);
308     free (iface);
309     free (name);
310     return -1;
311   }
312   if (!valid_format_iface (iface)) {
313     error (g, _("%s parameter is empty or contains disallowed characters"),
314            "iface");
315     free (format);
316     free (iface);
317     free (name);
318     return -1;
319   }
320
321   /* For writable files, see if we can use cache=off.  This also
322    * checks for the existence of the file.  For readonly we have
323    * to do the check explicitly.
324    */
325   use_cache_off = readonly ? 0 : test_cache_off (g, filename);
326   if (use_cache_off == -1) {
327     free (format);
328     free (iface);
329     free (name);
330     return -1;
331   }
332
333   if (readonly) {
334     if (access (filename, R_OK) == -1) {
335       perrorf (g, "%s", filename);
336       free (format);
337       free (iface);
338       free (name);
339       return -1;
340     }
341   }
342
343   struct drive **i = &(g->drives);
344   while (*i != NULL) i = &((*i)->next);
345
346   *i = safe_malloc (g, sizeof (struct drive));
347   (*i)->next = NULL;
348   (*i)->path = safe_strdup (g, filename);
349   (*i)->readonly = readonly;
350   (*i)->format = format;
351   (*i)->iface = iface;
352   (*i)->name = name;
353   (*i)->use_cache_off = use_cache_off;
354
355   return 0;
356 }
357
358 int
359 guestfs__add_drive (guestfs_h *g, const char *filename)
360 {
361   struct guestfs_add_drive_opts_argv optargs = {
362     .bitmask = 0,
363   };
364
365   return guestfs__add_drive_opts (g, filename, &optargs);
366 }
367
368 int
369 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
370 {
371   struct guestfs_add_drive_opts_argv optargs = {
372     .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
373     .readonly = 1,
374   };
375
376   return guestfs__add_drive_opts (g, filename, &optargs);
377 }
378
379 int
380 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
381                             const char *iface)
382 {
383   struct guestfs_add_drive_opts_argv optargs = {
384     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
385     .iface = iface,
386   };
387
388   return guestfs__add_drive_opts (g, filename, &optargs);
389 }
390
391 int
392 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
393                                const char *iface)
394 {
395   struct guestfs_add_drive_opts_argv optargs = {
396     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
397              | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
398     .iface = iface,
399     .readonly = 1,
400   };
401
402   return guestfs__add_drive_opts (g, filename, &optargs);
403 }
404
405 int
406 guestfs__add_cdrom (guestfs_h *g, const char *filename)
407 {
408   if (strchr (filename, ',') != NULL) {
409     error (g, _("filename cannot contain ',' (comma) character"));
410     return -1;
411   }
412
413   if (access (filename, F_OK) == -1) {
414     perrorf (g, "%s", filename);
415     return -1;
416   }
417
418   return guestfs__config (g, "-cdrom", filename);
419 }
420
421 static int is_openable (guestfs_h *g, const char *path, int flags);
422
423 int
424 guestfs__launch (guestfs_h *g)
425 {
426   /* Configured? */
427   if (g->state != CONFIG) {
428     error (g, _("the libguestfs handle has already been launched"));
429     return -1;
430   }
431
432   TRACE0 (launch_start);
433
434   /* Make the temporary directory. */
435   if (!g->tmpdir) {
436     TMP_TEMPLATE_ON_STACK (dir_template);
437     g->tmpdir = safe_strdup (g, dir_template);
438     if (mkdtemp (g->tmpdir) == NULL) {
439       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
440       return -1;
441     }
442   }
443
444   /* Allow anyone to read the temporary directory.  The socket in this
445    * directory won't be readable but anyone can see it exists if they
446    * want. (RHBZ#610880).
447    */
448   if (chmod (g->tmpdir, 0755) == -1)
449     warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
450
451   /* Launch the appliance or attach to an existing daemon. */
452   switch (g->attach_method) {
453   case ATTACH_METHOD_APPLIANCE:
454     return launch_appliance (g);
455
456   case ATTACH_METHOD_UNIX:
457     return connect_unix_socket (g, g->attach_method_arg);
458
459   default:
460     abort ();
461   }
462 }
463
464 static int
465 launch_appliance (guestfs_h *g)
466 {
467   int r;
468   int wfd[2], rfd[2];
469   char guestfsd_sock[256];
470   struct sockaddr_un addr;
471
472   /* At present you must add drives before starting the appliance.  In
473    * future when we enable hotplugging you won't need to do this.
474    */
475   if (!g->drives) {
476     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
477     return -1;
478   }
479
480   /* Start the clock ... */
481   gettimeofday (&g->launch_t, NULL);
482   guestfs___launch_send_progress (g, 0);
483
484   TRACE0 (launch_build_appliance_start);
485
486   /* Locate and/or build the appliance. */
487   char *kernel = NULL, *initrd = NULL, *appliance = NULL;
488   if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
489     return -1;
490
491   TRACE0 (launch_build_appliance_end);
492
493   guestfs___launch_send_progress (g, 3);
494
495   if (g->verbose)
496     guestfs___print_timestamped_message (g, "begin testing qemu features");
497
498   /* Get qemu help text and version. */
499   if (qemu_supports (g, NULL) == -1)
500     goto cleanup0;
501
502   /* Using virtio-serial, we need to create a local Unix domain socket
503    * for qemu to connect to.
504    */
505   snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
506   unlink (guestfsd_sock);
507
508   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
509   if (g->sock == -1) {
510     perrorf (g, "socket");
511     goto cleanup0;
512   }
513
514   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
515     perrorf (g, "fcntl");
516     goto cleanup0;
517   }
518
519   addr.sun_family = AF_UNIX;
520   strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
521   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
522
523   if (bind (g->sock, &addr, sizeof addr) == -1) {
524     perrorf (g, "bind");
525     goto cleanup0;
526   }
527
528   if (listen (g->sock, 1) == -1) {
529     perrorf (g, "listen");
530     goto cleanup0;
531   }
532
533   if (!g->direct) {
534     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
535       perrorf (g, "pipe");
536       goto cleanup0;
537     }
538   }
539
540   if (g->verbose)
541     guestfs___print_timestamped_message (g, "finished testing qemu features");
542
543   r = fork ();
544   if (r == -1) {
545     perrorf (g, "fork");
546     if (!g->direct) {
547       close (wfd[0]);
548       close (wfd[1]);
549       close (rfd[0]);
550       close (rfd[1]);
551     }
552     goto cleanup0;
553   }
554
555   if (r == 0) {                 /* Child (qemu). */
556     char buf[256];
557
558     /* Set up the full command line.  Do this in the subprocess so we
559      * don't need to worry about cleaning up.
560      */
561
562     /* Set g->cmdline[0] to the name of the qemu process.  However
563      * it is possible that no g->cmdline has been allocated yet so
564      * we must do that first.
565      */
566     alloc_cmdline (g);
567     g->cmdline[0] = g->qemu;
568
569     /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
570      * devices.  The -global option must exist, but you can pass any
571      * strings to it so we don't need to check for the specific virtio
572      * feature.
573      */
574     if (qemu_supports (g, "-global")) {
575       add_cmdline (g, "-global");
576       add_cmdline (g, "virtio-blk-pci.scsi=off");
577     }
578
579     /* Add drives */
580     struct drive *drv = g->drives;
581     while (drv != NULL) {
582       /* Construct the final -drive parameter. */
583       char *buf = qemu_drive_param (g, drv);
584
585       add_cmdline (g, "-drive");
586       add_cmdline (g, buf);
587       free (buf);
588
589       drv = drv->next;
590     }
591
592     if (qemu_supports (g, "-nodefconfig"))
593       add_cmdline (g, "-nodefconfig");
594
595     /* The qemu -machine option (added 2010-12) is a bit more sane
596      * since it falls back through various different acceleration
597      * modes, so try that first (thanks Markus Armbruster).
598      */
599     if (qemu_supports (g, "-machine")) {
600       add_cmdline (g, "-machine");
601 #if QEMU_MACHINE_TYPE_IS_BROKEN
602       /* Workaround for qemu 0.15: We have to add the '[type=]pc'
603        * since there is no default.  This is not a permanent solution
604        * because this only works on PC-like hardware.  Other platforms
605        * like ppc would need a different machine type.
606        *
607        * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
608        * not a problem in qemu < 0.15.
609        */
610       add_cmdline (g, "pc,accel=kvm:tcg");
611 #else
612       add_cmdline (g, "accel=kvm:tcg");
613 #endif
614     } else {
615       /* qemu sometimes needs this option to enable hardware
616        * virtualization, but some versions of 'qemu-kvm' will use KVM
617        * regardless (even where this option appears in the help text).
618        * It is rumoured that there are versions of qemu where supplying
619        * this option when hardware virtualization is not available will
620        * cause qemu to fail, so we we have to check at least that
621        * /dev/kvm is openable.  That's not reliable, since /dev/kvm
622        * might be openable by qemu but not by us (think: SELinux) in
623        * which case the user would not get hardware virtualization,
624        * although at least shouldn't fail.  A giant clusterfuck with the
625        * qemu command line, again.
626        */
627       if (qemu_supports (g, "-enable-kvm") &&
628           is_openable (g, "/dev/kvm", O_RDWR))
629         add_cmdline (g, "-enable-kvm");
630     }
631
632     /* Newer versions of qemu (from around 2009/12) changed the
633      * behaviour of monitors so that an implicit '-monitor stdio' is
634      * assumed if we are in -nographic mode and there is no other
635      * -monitor option.  Only a single stdio device is allowed, so
636      * this broke the '-serial stdio' option.  There is a new flag
637      * called -nodefaults which gets rid of all this default crud, so
638      * let's use that to avoid this and any future surprises.
639      */
640     if (qemu_supports (g, "-nodefaults"))
641       add_cmdline (g, "-nodefaults");
642
643     add_cmdline (g, "-nographic");
644
645     if (g->smp > 1) {
646       snprintf (buf, sizeof buf, "%d", g->smp);
647       add_cmdline (g, "-smp");
648       add_cmdline (g, buf);
649     }
650
651     snprintf (buf, sizeof buf, "%d", g->memsize);
652     add_cmdline (g, "-m");
653     add_cmdline (g, buf);
654
655     /* Force exit instead of reboot on panic */
656     add_cmdline (g, "-no-reboot");
657
658     /* These options recommended by KVM developers to improve reliability. */
659     if (qemu_supports (g, "-no-hpet"))
660       add_cmdline (g, "-no-hpet");
661
662     if (qemu_supports (g, "-rtc-td-hack"))
663       add_cmdline (g, "-rtc-td-hack");
664
665     /* Create the virtio serial bus. */
666     add_cmdline (g, "-device");
667     add_cmdline (g, "virtio-serial");
668
669 #if 0
670     /* Use virtio-console (a variant form of virtio-serial) for the
671      * guest's serial console.
672      */
673     add_cmdline (g, "-chardev");
674     add_cmdline (g, "stdio,id=console");
675     add_cmdline (g, "-device");
676     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
677 #else
678     /* When the above works ...  until then: */
679     add_cmdline (g, "-serial");
680     add_cmdline (g, "stdio");
681 #endif
682
683     /* Set up virtio-serial for the communications channel. */
684     add_cmdline (g, "-chardev");
685     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
686     add_cmdline (g, buf);
687     add_cmdline (g, "-device");
688     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
689
690     /* Enable user networking. */
691     if (g->enable_network) {
692       add_cmdline (g, "-netdev");
693       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
694       add_cmdline (g, "-device");
695       add_cmdline (g, NET_IF ",netdev=usernet");
696     }
697
698 #define LINUX_CMDLINE                                                   \
699     "panic=1 "         /* force kernel to panic if daemon exits */      \
700     "console=ttyS0 "   /* serial console */                             \
701     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
702     "no_timer_check "  /* fix for RHBZ#502058 */                        \
703     "acpi=off "        /* we don't need ACPI, turn it off */            \
704     "printk.time=1 "   /* display timestamp before kernel messages */   \
705     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
706
707     /* Linux kernel command line. */
708     snprintf (buf, sizeof buf,
709               LINUX_CMDLINE
710               "%s "             /* (selinux) */
711               "%s "             /* (verbose) */
712               "TERM=%s "        /* (TERM environment variable) */
713               "%s",             /* (append) */
714               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
715               g->verbose ? "guestfs_verbose=1" : "",
716               getenv ("TERM") ? : "linux",
717               g->append ? g->append : "");
718
719     add_cmdline (g, "-kernel");
720     add_cmdline (g, kernel);
721     add_cmdline (g, "-initrd");
722     add_cmdline (g, initrd);
723     add_cmdline (g, "-append");
724     add_cmdline (g, buf);
725
726     /* Add the ext2 appliance drive (last of all). */
727     if (appliance) {
728       const char *cachemode = "";
729       if (qemu_supports (g, "cache=")) {
730         if (qemu_supports (g, "unsafe"))
731           cachemode = ",cache=unsafe";
732         else if (qemu_supports (g, "writeback"))
733           cachemode = ",cache=writeback";
734       }
735
736       char buf2[PATH_MAX + 64];
737       add_cmdline (g, "-drive");
738       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
739                 appliance, cachemode);
740       add_cmdline (g, buf2);
741     }
742
743     /* Finish off the command line. */
744     incr_cmdline_size (g);
745     g->cmdline[g->cmdline_size-1] = NULL;
746
747     if (!g->direct) {
748       /* Set up stdin, stdout, stderr. */
749       close (0);
750       close (1);
751       close (wfd[1]);
752       close (rfd[0]);
753
754       /* Stdin. */
755       if (dup (wfd[0]) == -1) {
756       dup_failed:
757         perror ("dup failed");
758         _exit (EXIT_FAILURE);
759       }
760       /* Stdout. */
761       if (dup (rfd[1]) == -1)
762         goto dup_failed;
763
764       /* Particularly since qemu 0.15, qemu spews all sorts of debug
765        * information on stderr.  It is useful to both capture this and
766        * not confuse casual users, so send stderr to the pipe as well.
767        */
768       close (2);
769       if (dup (rfd[1]) == -1)
770         goto dup_failed;
771
772       close (wfd[0]);
773       close (rfd[1]);
774     }
775
776     /* Dump the command line (after setting up stderr above). */
777     if (g->verbose)
778       print_qemu_command_line (g, g->cmdline);
779
780     /* Put qemu in a new process group. */
781     if (g->pgroup)
782       setpgid (0, 0);
783
784     setenv ("LC_ALL", "C", 1);
785
786     TRACE0 (launch_run_qemu);
787
788     execv (g->qemu, g->cmdline); /* Run qemu. */
789     perror (g->qemu);
790     _exit (EXIT_FAILURE);
791   }
792
793   /* Parent (library). */
794   g->pid = r;
795
796   free (kernel);
797   kernel = NULL;
798   free (initrd);
799   initrd = NULL;
800   free (appliance);
801   appliance = NULL;
802
803   /* Fork the recovery process off which will kill qemu if the parent
804    * process fails to do so (eg. if the parent segfaults).
805    */
806   g->recoverypid = -1;
807   if (g->recovery_proc) {
808     r = fork ();
809     if (r == 0) {
810       pid_t qemu_pid = g->pid;
811       pid_t parent_pid = getppid ();
812
813       /* It would be nice to be able to put this in the same process
814        * group as qemu (ie. setpgid (0, qemu_pid)).  However this is
815        * not possible because we don't have any guarantee here that
816        * the qemu process has started yet.
817        */
818       if (g->pgroup)
819         setpgid (0, 0);
820
821       /* Writing to argv is hideously complicated and error prone.  See:
822        * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
823        */
824
825       /* Loop around waiting for one or both of the other processes to
826        * disappear.  It's fair to say this is very hairy.  The PIDs that
827        * we are looking at might be reused by another process.  We are
828        * effectively polling.  Is the cure worse than the disease?
829        */
830       for (;;) {
831         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
832           _exit (EXIT_SUCCESS);
833         if (kill (parent_pid, 0) == -1) {
834           /* Parent's gone away, qemu still around, so kill qemu. */
835           kill (qemu_pid, 9);
836           _exit (EXIT_SUCCESS);
837         }
838         sleep (2);
839       }
840     }
841
842     /* Don't worry, if the fork failed, this will be -1.  The recovery
843      * process isn't essential.
844      */
845     g->recoverypid = r;
846   }
847
848   if (!g->direct) {
849     /* Close the other ends of the pipe. */
850     close (wfd[0]);
851     close (rfd[1]);
852
853     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
854         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
855       perrorf (g, "fcntl");
856       goto cleanup1;
857     }
858
859     g->fd[0] = wfd[1];          /* stdin of child */
860     g->fd[1] = rfd[0];          /* stdout of child */
861   } else {
862     g->fd[0] = open ("/dev/null", O_RDWR);
863     if (g->fd[0] == -1) {
864       perrorf (g, "open /dev/null");
865       goto cleanup1;
866     }
867     g->fd[1] = dup (g->fd[0]);
868     if (g->fd[1] == -1) {
869       perrorf (g, "dup");
870       close (g->fd[0]);
871       goto cleanup1;
872     }
873   }
874
875   g->state = LAUNCHING;
876
877   /* Wait for qemu to start and to connect back to us via
878    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
879    */
880   r = guestfs___accept_from_daemon (g);
881   if (r == -1)
882     goto cleanup1;
883
884   /* NB: We reach here just because qemu has opened the socket.  It
885    * does not mean the daemon is up until we read the
886    * GUESTFS_LAUNCH_FLAG below.  Failures in qemu startup can still
887    * happen even if we reach here, even early failures like not being
888    * able to open a drive.
889    */
890
891   close (g->sock); /* Close the listening socket. */
892   g->sock = r; /* This is the accepted data socket. */
893
894   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
895     perrorf (g, "fcntl");
896     goto cleanup1;
897   }
898
899   uint32_t size;
900   void *buf = NULL;
901   r = guestfs___recv_from_daemon (g, &size, &buf);
902   free (buf);
903
904   if (r == -1) return -1;
905
906   if (size != GUESTFS_LAUNCH_FLAG) {
907     error (g, _("guestfs_launch failed, see earlier error messages"));
908     goto cleanup1;
909   }
910
911   if (g->verbose)
912     guestfs___print_timestamped_message (g, "appliance is up");
913
914   /* This is possible in some really strange situations, such as
915    * guestfsd starts up OK but then qemu immediately exits.  Check for
916    * it because the caller is probably expecting to be able to send
917    * commands after this function returns.
918    */
919   if (g->state != READY) {
920     error (g, _("qemu launched and contacted daemon, but state != READY"));
921     goto cleanup1;
922   }
923
924   TRACE0 (launch_end);
925
926   guestfs___launch_send_progress (g, 12);
927
928   return 0;
929
930  cleanup1:
931   if (!g->direct) {
932     close (wfd[1]);
933     close (rfd[0]);
934   }
935   if (g->pid > 0) kill (g->pid, 9);
936   if (g->recoverypid > 0) kill (g->recoverypid, 9);
937   if (g->pid > 0) waitpid (g->pid, NULL, 0);
938   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
939   g->fd[0] = -1;
940   g->fd[1] = -1;
941   g->pid = 0;
942   g->recoverypid = 0;
943   memset (&g->launch_t, 0, sizeof g->launch_t);
944
945  cleanup0:
946   if (g->sock >= 0) {
947     close (g->sock);
948     g->sock = -1;
949   }
950   g->state = CONFIG;
951   free (kernel);
952   free (initrd);
953   free (appliance);
954   return -1;
955 }
956
957 /* Alternate attach method: instead of launching the appliance,
958  * connect to an existing unix socket.
959  */
960 static int
961 connect_unix_socket (guestfs_h *g, const char *sockpath)
962 {
963   int r;
964   struct sockaddr_un addr;
965
966   /* Start the clock ... */
967   gettimeofday (&g->launch_t, NULL);
968
969   /* Set these to nothing so we don't try to kill random processes or
970    * read from random file descriptors.
971    */
972   g->pid = 0;
973   g->recoverypid = 0;
974   g->fd[0] = -1;
975   g->fd[1] = -1;
976
977   if (g->verbose)
978     guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
979
980   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
981   if (g->sock == -1) {
982     perrorf (g, "socket");
983     return -1;
984   }
985
986   addr.sun_family = AF_UNIX;
987   strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
988   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
989
990   g->state = LAUNCHING;
991
992   if (connect (g->sock, &addr, sizeof addr) == -1) {
993     perrorf (g, "bind");
994     goto cleanup;
995   }
996
997   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
998     perrorf (g, "fcntl");
999     goto cleanup;
1000   }
1001
1002   uint32_t size;
1003   void *buf = NULL;
1004   r = guestfs___recv_from_daemon (g, &size, &buf);
1005   free (buf);
1006
1007   if (r == -1) return -1;
1008
1009   if (size != GUESTFS_LAUNCH_FLAG) {
1010     error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1011     goto cleanup;
1012   }
1013
1014   if (g->verbose)
1015     guestfs___print_timestamped_message (g, "connected");
1016
1017   if (g->state != READY) {
1018     error (g, _("contacted guestfsd, but state != READY"));
1019     goto cleanup;
1020   }
1021
1022   return 0;
1023
1024  cleanup:
1025   close (g->sock);
1026   return -1;
1027 }
1028
1029 /* launch (of the ordinary appliance) generates approximate progress
1030  * messages.  Currently these are defined as follows:
1031  *
1032  *    0 / 12: launch clock starts
1033  *    3 / 12: appliance created
1034  *    6 / 12: detected that guest kernel started
1035  *    9 / 12: detected that /init script is running
1036  *   12 / 12: launch completed successfully
1037  *
1038  * Notes:
1039  * (1) This is not a documented ABI and the behaviour may be changed
1040  * or removed in future.
1041  * (2) Messages are only sent if more than 5 seconds has elapsed
1042  * since the launch clock started.
1043  * (3) There is a gross hack in proto.c to make this work.
1044  */
1045 void
1046 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1047 {
1048   struct timeval tv;
1049
1050   gettimeofday (&tv, NULL);
1051   if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1052     guestfs_progress progress_message =
1053       { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1054
1055     guestfs___progress_message_callback (g, &progress_message);
1056   }
1057 }
1058
1059 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1060  * to override it at runtime using $TMPDIR.
1061  * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1062  */
1063 const char *
1064 guestfs_tmpdir (void)
1065 {
1066   const char *tmpdir;
1067
1068 #ifdef P_tmpdir
1069   tmpdir = P_tmpdir;
1070 #else
1071   tmpdir = "/tmp";
1072 #endif
1073
1074   const char *t = getenv ("TMPDIR");
1075   if (t) tmpdir = t;
1076
1077   return tmpdir;
1078 }
1079
1080 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1081  * allow users to override it at runtime using $TMPDIR.
1082  * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1083  */
1084 const char *
1085 guestfs___persistent_tmpdir (void)
1086 {
1087   const char *tmpdir;
1088
1089   tmpdir = "/var/tmp";
1090
1091   const char *t = getenv ("TMPDIR");
1092   if (t) tmpdir = t;
1093
1094   return tmpdir;
1095 }
1096
1097 /* Recursively remove a temporary directory.  If removal fails, just
1098  * return (it's a temporary directory so it'll eventually be cleaned
1099  * up by a temp cleaner).  This is done using "rm -rf" because that's
1100  * simpler and safer, but we have to exec to ensure that paths don't
1101  * need to be quoted.
1102  */
1103 void
1104 guestfs___remove_tmpdir (const char *dir)
1105 {
1106   pid_t pid = fork ();
1107
1108   if (pid == -1) {
1109     perror ("remove tmpdir: fork");
1110     return;
1111   }
1112   if (pid == 0) {
1113     execlp ("rm", "rm", "-rf", dir, NULL);
1114     perror ("remove tmpdir: exec: rm");
1115     _exit (EXIT_FAILURE);
1116   }
1117
1118   /* Parent. */
1119   if (waitpid (pid, NULL, 0) == -1) {
1120     perror ("remove tmpdir: waitpid");
1121     return;
1122   }
1123 }
1124
1125 /* Compute Y - X and return the result in milliseconds.
1126  * Approximately the same as this code:
1127  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1128  */
1129 static int64_t
1130 timeval_diff (const struct timeval *x, const struct timeval *y)
1131 {
1132   int64_t msec;
1133
1134   msec = (y->tv_sec - x->tv_sec) * 1000;
1135   msec += (y->tv_usec - x->tv_usec) / 1000;
1136   return msec;
1137 }
1138
1139 /* Note that since this calls 'debug' it should only be called
1140  * from the parent process.
1141  */
1142 void
1143 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1144 {
1145   va_list args;
1146   char *msg;
1147   int err;
1148   struct timeval tv;
1149
1150   va_start (args, fs);
1151   err = vasprintf (&msg, fs, args);
1152   va_end (args);
1153
1154   if (err < 0) return;
1155
1156   gettimeofday (&tv, NULL);
1157
1158   debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1159
1160   free (msg);
1161 }
1162
1163 /* This is called from the forked subprocess just before qemu runs, so
1164  * it can just print the message straight to stderr, where it will be
1165  * picked up and funnelled through the usual appliance event API.
1166  */
1167 static void
1168 print_qemu_command_line (guestfs_h *g, char **argv)
1169 {
1170   int i = 0;
1171   int needs_quote;
1172
1173   struct timeval tv;
1174   gettimeofday (&tv, NULL);
1175   fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1176
1177   while (argv[i]) {
1178     if (argv[i][0] == '-') /* -option starts a new line */
1179       fprintf (stderr, " \\\n   ");
1180
1181     if (i > 0) fputc (' ', stderr);
1182
1183     /* Does it need shell quoting?  This only deals with simple cases. */
1184     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1185
1186     if (needs_quote) fputc ('\'', stderr);
1187     fprintf (stderr, "%s", argv[i]);
1188     if (needs_quote) fputc ('\'', stderr);
1189     i++;
1190   }
1191 }
1192
1193 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1194 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1195
1196 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1197  * 'qemu -version' so we know what options this qemu supports and
1198  * the version.
1199  */
1200 static int
1201 test_qemu (guestfs_h *g)
1202 {
1203   char cmd[1024];
1204   FILE *fp;
1205
1206   free (g->qemu_help);
1207   g->qemu_help = NULL;
1208   free (g->qemu_version);
1209   g->qemu_version = NULL;
1210
1211   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1212
1213   /* qemu -help should always work (qemu -version OTOH wasn't
1214    * supported by qemu 0.9).  If this command doesn't work then it
1215    * probably indicates that the qemu binary is missing.
1216    */
1217   if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1218     error (g, _("command failed: %s\n\nIf qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU\nenvironment variable.  There may also be errors printed above."),
1219            cmd);
1220     return -1;
1221   }
1222
1223   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1224             g->qemu);
1225
1226   /* Intentionally ignore errors from qemu -version. */
1227   ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1228
1229   return 0;
1230 }
1231
1232 static int
1233 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1234 {
1235   FILE *fp;
1236
1237   fp = popen (cmd, "r");
1238   if (fp == NULL)
1239     return -1;
1240
1241   if (read_all (g, fp, ret) == -1) {
1242     pclose (fp);
1243     return -1;
1244   }
1245
1246   if (pclose (fp) != 0)
1247     return -1;
1248
1249   return 0;
1250 }
1251
1252 static int
1253 read_all (guestfs_h *g, FILE *fp, char **ret)
1254 {
1255   int r, n = 0;
1256   char *p;
1257
1258  again:
1259   if (feof (fp)) {
1260     *ret = safe_realloc (g, *ret, n + 1);
1261     (*ret)[n] = '\0';
1262     return n;
1263   }
1264
1265   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1266   p = &(*ret)[n];
1267   r = fread (p, 1, BUFSIZ, fp);
1268   if (ferror (fp)) {
1269     perrorf (g, "read");
1270     return -1;
1271   }
1272   n += r;
1273   goto again;
1274 }
1275
1276 /* Test if option is supported by qemu command line (just by grepping
1277  * the help text).
1278  *
1279  * The first time this is used, it has to run the external qemu
1280  * binary.  If that fails, it returns -1.
1281  *
1282  * To just do the first-time run of the qemu binary, call this with
1283  * option == NULL, in which case it will return -1 if there was an
1284  * error doing that.
1285  */
1286 static int
1287 qemu_supports (guestfs_h *g, const char *option)
1288 {
1289   if (!g->qemu_help) {
1290     if (test_qemu (g) == -1)
1291       return -1;
1292   }
1293
1294   if (option == NULL)
1295     return 1;
1296
1297   return strstr (g->qemu_help, option) != NULL;
1298 }
1299
1300 #if 0
1301 /* As above but using a regex instead of a fixed string. */
1302 static int
1303 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1304 {
1305   if (!g->qemu_help) {
1306     if (test_qemu (g) == -1)
1307       return -1;
1308   }
1309
1310   return match (g, g->qemu_help, option_regex);
1311 }
1312 #endif
1313
1314 /* Check if a file can be opened. */
1315 static int
1316 is_openable (guestfs_h *g, const char *path, int flags)
1317 {
1318   int fd = open (path, flags);
1319   if (fd == -1) {
1320     debug (g, "is_openable: %s: %m", path);
1321     return 0;
1322   }
1323   close (fd);
1324   return 1;
1325 }
1326
1327 static char *
1328 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1329 {
1330   size_t len = 64;
1331   char *r;
1332
1333   len += strlen (drv->path);
1334   len += strlen (drv->iface);
1335   if (drv->format)
1336     len += strlen (drv->format);
1337
1338   r = safe_malloc (g, len);
1339
1340   snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1341             drv->path,
1342             drv->readonly ? ",snapshot=on" : "",
1343             drv->use_cache_off ? ",cache=off" : "",
1344             drv->format ? ",format=" : "",
1345             drv->format ? drv->format : "",
1346             drv->iface);
1347
1348   return r;                     /* caller frees */
1349 }
1350
1351 /* You had to call this function after launch in versions <= 1.0.70,
1352  * but it is now a no-op.
1353  */
1354 int
1355 guestfs__wait_ready (guestfs_h *g)
1356 {
1357   if (g->state != READY)  {
1358     error (g, _("qemu has not been launched yet"));
1359     return -1;
1360   }
1361
1362   return 0;
1363 }
1364
1365 int
1366 guestfs__kill_subprocess (guestfs_h *g)
1367 {
1368   if (g->state == CONFIG) {
1369     error (g, _("no subprocess to kill"));
1370     return -1;
1371   }
1372
1373   debug (g, "sending SIGTERM to process %d", g->pid);
1374
1375   if (g->pid > 0) kill (g->pid, SIGTERM);
1376   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1377
1378   return 0;
1379 }
1380
1381 /* Access current state. */
1382 int
1383 guestfs__is_config (guestfs_h *g)
1384 {
1385   return g->state == CONFIG;
1386 }
1387
1388 int
1389 guestfs__is_launching (guestfs_h *g)
1390 {
1391   return g->state == LAUNCHING;
1392 }
1393
1394 int
1395 guestfs__is_ready (guestfs_h *g)
1396 {
1397   return g->state == READY;
1398 }
1399
1400 int
1401 guestfs__is_busy (guestfs_h *g)
1402 {
1403   return g->state == BUSY;
1404 }
1405
1406 int
1407 guestfs__get_state (guestfs_h *g)
1408 {
1409   return g->state;
1410 }