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