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