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