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