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