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