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