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