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