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