Security: Mitigate possible privilege escalation via SG_IO ioctl (CVE-2011-4127,...
[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   /* Make the temporary directory. */
394   if (!g->tmpdir) {
395     TMP_TEMPLATE_ON_STACK (dir_template);
396     g->tmpdir = safe_strdup (g, dir_template);
397     if (mkdtemp (g->tmpdir) == NULL) {
398       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
399       return -1;
400     }
401   }
402
403   /* Allow anyone to read the temporary directory.  The socket in this
404    * directory won't be readable but anyone can see it exists if they
405    * want. (RHBZ#610880).
406    */
407   if (chmod (g->tmpdir, 0755) == -1)
408     warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
409
410   /* Launch the appliance or attach to an existing daemon. */
411   switch (g->attach_method) {
412   case ATTACH_METHOD_APPLIANCE:
413     return launch_appliance (g);
414
415   case ATTACH_METHOD_UNIX:
416     return connect_unix_socket (g, g->attach_method_arg);
417
418   default:
419     abort ();
420   }
421 }
422
423 static int
424 launch_appliance (guestfs_h *g)
425 {
426   int r;
427   int wfd[2], rfd[2];
428   char guestfsd_sock[256];
429   struct sockaddr_un addr;
430
431   /* At present you must add drives before starting the appliance.  In
432    * future when we enable hotplugging you won't need to do this.
433    */
434   if (!g->cmdline) {
435     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
436     return -1;
437   }
438
439   /* Start the clock ... */
440   gettimeofday (&g->launch_t, NULL);
441   guestfs___launch_send_progress (g, 0);
442
443   /* Locate and/or build the appliance. */
444   char *kernel = NULL, *initrd = NULL, *appliance = NULL;
445   if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
446     return -1;
447
448   guestfs___launch_send_progress (g, 3);
449
450   if (g->verbose)
451     guestfs___print_timestamped_message (g, "begin testing qemu features");
452
453   /* Get qemu help text and version. */
454   if (qemu_supports (g, NULL) == -1)
455     goto cleanup0;
456
457   /* Using virtio-serial, we need to create a local Unix domain socket
458    * for qemu to connect to.
459    */
460   snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
461   unlink (guestfsd_sock);
462
463   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
464   if (g->sock == -1) {
465     perrorf (g, "socket");
466     goto cleanup0;
467   }
468
469   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
470     perrorf (g, "fcntl");
471     goto cleanup0;
472   }
473
474   addr.sun_family = AF_UNIX;
475   strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
476   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
477
478   if (bind (g->sock, &addr, sizeof addr) == -1) {
479     perrorf (g, "bind");
480     goto cleanup0;
481   }
482
483   if (listen (g->sock, 1) == -1) {
484     perrorf (g, "listen");
485     goto cleanup0;
486   }
487
488   if (!g->direct) {
489     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
490       perrorf (g, "pipe");
491       goto cleanup0;
492     }
493   }
494
495   if (g->verbose)
496     guestfs___print_timestamped_message (g, "finished testing qemu features");
497
498   r = fork ();
499   if (r == -1) {
500     perrorf (g, "fork");
501     if (!g->direct) {
502       close (wfd[0]);
503       close (wfd[1]);
504       close (rfd[0]);
505       close (rfd[1]);
506     }
507     goto cleanup0;
508   }
509
510   if (r == 0) {                 /* Child (qemu). */
511     char buf[256];
512
513     /* Set up the full command line.  Do this in the subprocess so we
514      * don't need to worry about cleaning up.
515      */
516
517     /* Set g->cmdline[0] to the name of the qemu process.  However
518      * it is possible that no g->cmdline has been allocated yet so
519      * we must do that first.
520      */
521     alloc_cmdline (g);
522     g->cmdline[0] = g->qemu;
523
524     /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
525      * devices.  The -global option must exist, but you can pass any
526      * strings to it so we don't need to check for the specific virtio
527      * feature.
528      */
529     if (qemu_supports (g, "-global")) {
530       add_cmdline (g, "-global");
531       add_cmdline (g, "virtio-blk-pci.scsi=off");
532     }
533
534     if (qemu_supports (g, "-nodefconfig"))
535       add_cmdline (g, "-nodefconfig");
536
537     /* The qemu -machine option (added 2010-12) is a bit more sane
538      * since it falls back through various different acceleration
539      * modes, so try that first (thanks Markus Armbruster).
540      */
541     if (qemu_supports (g, "-machine")) {
542       add_cmdline (g, "-machine");
543 #if QEMU_MACHINE_TYPE_IS_BROKEN
544       /* Workaround for qemu 0.15: We have to add the '[type=]pc'
545        * since there is no default.  This is not a permanent solution
546        * because this only works on PC-like hardware.  Other platforms
547        * like ppc would need a different machine type.
548        *
549        * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
550        * not a problem in qemu < 0.15.
551        */
552       add_cmdline (g, "pc,accel=kvm:tcg");
553 #else
554       add_cmdline (g, "accel=kvm:tcg");
555 #endif
556     } else {
557       /* qemu sometimes needs this option to enable hardware
558        * virtualization, but some versions of 'qemu-kvm' will use KVM
559        * regardless (even where this option appears in the help text).
560        * It is rumoured that there are versions of qemu where supplying
561        * this option when hardware virtualization is not available will
562        * cause qemu to fail, so we we have to check at least that
563        * /dev/kvm is openable.  That's not reliable, since /dev/kvm
564        * might be openable by qemu but not by us (think: SELinux) in
565        * which case the user would not get hardware virtualization,
566        * although at least shouldn't fail.  A giant clusterfuck with the
567        * qemu command line, again.
568        */
569       if (qemu_supports (g, "-enable-kvm") &&
570           is_openable (g, "/dev/kvm", O_RDWR))
571         add_cmdline (g, "-enable-kvm");
572     }
573
574     /* Newer versions of qemu (from around 2009/12) changed the
575      * behaviour of monitors so that an implicit '-monitor stdio' is
576      * assumed if we are in -nographic mode and there is no other
577      * -monitor option.  Only a single stdio device is allowed, so
578      * this broke the '-serial stdio' option.  There is a new flag
579      * called -nodefaults which gets rid of all this default crud, so
580      * let's use that to avoid this and any future surprises.
581      */
582     if (qemu_supports (g, "-nodefaults"))
583       add_cmdline (g, "-nodefaults");
584
585     add_cmdline (g, "-nographic");
586
587     snprintf (buf, sizeof buf, "%d", g->memsize);
588     add_cmdline (g, "-m");
589     add_cmdline (g, buf);
590
591     /* Force exit instead of reboot on panic */
592     add_cmdline (g, "-no-reboot");
593
594     /* These options recommended by KVM developers to improve reliability. */
595     if (qemu_supports (g, "-no-hpet"))
596       add_cmdline (g, "-no-hpet");
597
598     if (qemu_supports (g, "-rtc-td-hack"))
599       add_cmdline (g, "-rtc-td-hack");
600
601     /* Create the virtio serial bus. */
602     add_cmdline (g, "-device");
603     add_cmdline (g, "virtio-serial");
604
605 #if 0
606     /* Use virtio-console (a variant form of virtio-serial) for the
607      * guest's serial console.
608      */
609     add_cmdline (g, "-chardev");
610     add_cmdline (g, "stdio,id=console");
611     add_cmdline (g, "-device");
612     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
613 #else
614     /* When the above works ...  until then: */
615     add_cmdline (g, "-serial");
616     add_cmdline (g, "stdio");
617 #endif
618
619     /* Set up virtio-serial for the communications channel. */
620     add_cmdline (g, "-chardev");
621     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
622     add_cmdline (g, buf);
623     add_cmdline (g, "-device");
624     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
625
626     /* Enable user networking. */
627     if (g->enable_network) {
628       add_cmdline (g, "-netdev");
629       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
630       add_cmdline (g, "-device");
631       add_cmdline (g, NET_IF ",netdev=usernet");
632     }
633
634 #define LINUX_CMDLINE                                                   \
635     "panic=1 "         /* force kernel to panic if daemon exits */      \
636     "console=ttyS0 "   /* serial console */                             \
637     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
638     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
639     "no_timer_check "  /* fix for RHBZ#502058 */                        \
640     "acpi=off "        /* we don't need ACPI, turn it off */            \
641     "printk.time=1 "   /* display timestamp before kernel messages */   \
642     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
643
644     /* Linux kernel command line. */
645     snprintf (buf, sizeof buf,
646               LINUX_CMDLINE
647               "%s "             /* (selinux) */
648               "%s "             /* (verbose) */
649               "TERM=%s "        /* (TERM environment variable) */
650               "%s",             /* (append) */
651               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
652               g->verbose ? "guestfs_verbose=1" : "",
653               getenv ("TERM") ? : "linux",
654               g->append ? g->append : "");
655
656     add_cmdline (g, "-kernel");
657     add_cmdline (g, kernel);
658     add_cmdline (g, "-initrd");
659     add_cmdline (g, initrd);
660     add_cmdline (g, "-append");
661     add_cmdline (g, buf);
662
663     /* Add the ext2 appliance drive (last of all). */
664     if (appliance) {
665       const char *cachemode = "";
666       if (qemu_supports (g, "cache=")) {
667         if (qemu_supports (g, "unsafe"))
668           cachemode = ",cache=unsafe";
669         else if (qemu_supports (g, "writeback"))
670           cachemode = ",cache=writeback";
671       }
672
673       char buf2[PATH_MAX + 64];
674       add_cmdline (g, "-drive");
675       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
676                 appliance, cachemode);
677       add_cmdline (g, buf2);
678     }
679
680     /* Finish off the command line. */
681     incr_cmdline_size (g);
682     g->cmdline[g->cmdline_size-1] = NULL;
683
684     if (!g->direct) {
685       /* Set up stdin, stdout, stderr. */
686       close (0);
687       close (1);
688       close (wfd[1]);
689       close (rfd[0]);
690
691       /* Stdin. */
692       if (dup (wfd[0]) == -1) {
693       dup_failed:
694         perror ("dup failed");
695         _exit (EXIT_FAILURE);
696       }
697       /* Stdout. */
698       if (dup (rfd[1]) == -1)
699         goto dup_failed;
700
701       /* Particularly since qemu 0.15, qemu spews all sorts of debug
702        * information on stderr.  It is useful to both capture this and
703        * not confuse casual users, so send stderr to the pipe as well.
704        */
705       close (2);
706       if (dup (rfd[1]) == -1)
707         goto dup_failed;
708
709       close (wfd[0]);
710       close (rfd[1]);
711     }
712
713     /* Dump the command line (after setting up stderr above). */
714     if (g->verbose)
715       print_qemu_command_line (g, g->cmdline);
716
717     /* Put qemu in a new process group. */
718     if (g->pgroup)
719       setpgid (0, 0);
720
721     setenv ("LC_ALL", "C", 1);
722
723     execv (g->qemu, g->cmdline); /* Run qemu. */
724     perror (g->qemu);
725     _exit (EXIT_FAILURE);
726   }
727
728   /* Parent (library). */
729   g->pid = r;
730
731   free (kernel);
732   kernel = NULL;
733   free (initrd);
734   initrd = NULL;
735   free (appliance);
736   appliance = NULL;
737
738   /* Fork the recovery process off which will kill qemu if the parent
739    * process fails to do so (eg. if the parent segfaults).
740    */
741   g->recoverypid = -1;
742   if (g->recovery_proc) {
743     r = fork ();
744     if (r == 0) {
745       pid_t qemu_pid = g->pid;
746       pid_t parent_pid = getppid ();
747
748       /* It would be nice to be able to put this in the same process
749        * group as qemu (ie. setpgid (0, qemu_pid)).  However this is
750        * not possible because we don't have any guarantee here that
751        * the qemu process has started yet.
752        */
753       if (g->pgroup)
754         setpgid (0, 0);
755
756       /* Writing to argv is hideously complicated and error prone.  See:
757        * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
758        */
759
760       /* Loop around waiting for one or both of the other processes to
761        * disappear.  It's fair to say this is very hairy.  The PIDs that
762        * we are looking at might be reused by another process.  We are
763        * effectively polling.  Is the cure worse than the disease?
764        */
765       for (;;) {
766         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
767           _exit (EXIT_SUCCESS);
768         if (kill (parent_pid, 0) == -1) {
769           /* Parent's gone away, qemu still around, so kill qemu. */
770           kill (qemu_pid, 9);
771           _exit (EXIT_SUCCESS);
772         }
773         sleep (2);
774       }
775     }
776
777     /* Don't worry, if the fork failed, this will be -1.  The recovery
778      * process isn't essential.
779      */
780     g->recoverypid = r;
781   }
782
783   if (!g->direct) {
784     /* Close the other ends of the pipe. */
785     close (wfd[0]);
786     close (rfd[1]);
787
788     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
789         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
790       perrorf (g, "fcntl");
791       goto cleanup1;
792     }
793
794     g->fd[0] = wfd[1];          /* stdin of child */
795     g->fd[1] = rfd[0];          /* stdout of child */
796   } else {
797     g->fd[0] = open ("/dev/null", O_RDWR);
798     if (g->fd[0] == -1) {
799       perrorf (g, "open /dev/null");
800       goto cleanup1;
801     }
802     g->fd[1] = dup (g->fd[0]);
803     if (g->fd[1] == -1) {
804       perrorf (g, "dup");
805       close (g->fd[0]);
806       goto cleanup1;
807     }
808   }
809
810   g->state = LAUNCHING;
811
812   /* Wait for qemu to start and to connect back to us via
813    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
814    */
815   r = guestfs___accept_from_daemon (g);
816   if (r == -1)
817     goto cleanup1;
818
819   close (g->sock); /* Close the listening socket. */
820   g->sock = r; /* This is the accepted data socket. */
821
822   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
823     perrorf (g, "fcntl");
824     goto cleanup1;
825   }
826
827   uint32_t size;
828   void *buf = NULL;
829   r = guestfs___recv_from_daemon (g, &size, &buf);
830   free (buf);
831
832   if (r == -1) return -1;
833
834   if (size != GUESTFS_LAUNCH_FLAG) {
835     error (g, _("guestfs_launch failed, see earlier error messages"));
836     goto cleanup1;
837   }
838
839   if (g->verbose)
840     guestfs___print_timestamped_message (g, "appliance is up");
841
842   /* This is possible in some really strange situations, such as
843    * guestfsd starts up OK but then qemu immediately exits.  Check for
844    * it because the caller is probably expecting to be able to send
845    * commands after this function returns.
846    */
847   if (g->state != READY) {
848     error (g, _("qemu launched and contacted daemon, but state != READY"));
849     goto cleanup1;
850   }
851
852   guestfs___launch_send_progress (g, 12);
853
854   return 0;
855
856  cleanup1:
857   if (!g->direct) {
858     close (wfd[1]);
859     close (rfd[0]);
860   }
861   if (g->pid > 0) kill (g->pid, 9);
862   if (g->recoverypid > 0) kill (g->recoverypid, 9);
863   if (g->pid > 0) waitpid (g->pid, NULL, 0);
864   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
865   g->fd[0] = -1;
866   g->fd[1] = -1;
867   g->pid = 0;
868   g->recoverypid = 0;
869   memset (&g->launch_t, 0, sizeof g->launch_t);
870
871  cleanup0:
872   if (g->sock >= 0) {
873     close (g->sock);
874     g->sock = -1;
875   }
876   g->state = CONFIG;
877   free (kernel);
878   free (initrd);
879   free (appliance);
880   return -1;
881 }
882
883 /* Alternate attach method: instead of launching the appliance,
884  * connect to an existing unix socket.
885  */
886 static int
887 connect_unix_socket (guestfs_h *g, const char *sockpath)
888 {
889   int r;
890   struct sockaddr_un addr;
891
892   /* Start the clock ... */
893   gettimeofday (&g->launch_t, NULL);
894
895   /* Set these to nothing so we don't try to kill random processes or
896    * read from random file descriptors.
897    */
898   g->pid = 0;
899   g->recoverypid = 0;
900   g->fd[0] = -1;
901   g->fd[1] = -1;
902
903   if (g->verbose)
904     guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
905
906   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
907   if (g->sock == -1) {
908     perrorf (g, "socket");
909     return -1;
910   }
911
912   addr.sun_family = AF_UNIX;
913   strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
914   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
915
916   g->state = LAUNCHING;
917
918   if (connect (g->sock, &addr, sizeof addr) == -1) {
919     perrorf (g, "bind");
920     goto cleanup;
921   }
922
923   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
924     perrorf (g, "fcntl");
925     goto cleanup;
926   }
927
928   uint32_t size;
929   void *buf = NULL;
930   r = guestfs___recv_from_daemon (g, &size, &buf);
931   free (buf);
932
933   if (r == -1) return -1;
934
935   if (size != GUESTFS_LAUNCH_FLAG) {
936     error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
937     goto cleanup;
938   }
939
940   if (g->verbose)
941     guestfs___print_timestamped_message (g, "connected");
942
943   if (g->state != READY) {
944     error (g, _("contacted guestfsd, but state != READY"));
945     goto cleanup;
946   }
947
948   return 0;
949
950  cleanup:
951   close (g->sock);
952   return -1;
953 }
954
955 /* launch (of the ordinary appliance) generates approximate progress
956  * messages.  Currently these are defined as follows:
957  *
958  *    0 / 12: launch clock starts
959  *    3 / 12: appliance created
960  *    6 / 12: detected that guest kernel started
961  *    9 / 12: detected that /init script is running
962  *   12 / 12: launch completed successfully
963  *
964  * Notes:
965  * (1) This is not a documented ABI and the behaviour may be changed
966  * or removed in future.
967  * (2) Messages are only sent if more than 5 seconds has elapsed
968  * since the launch clock started.
969  * (3) There is a gross hack in proto.c to make this work.
970  */
971 void
972 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
973 {
974   struct timeval tv;
975
976   gettimeofday (&tv, NULL);
977   if (timeval_diff (&g->launch_t, &tv) >= 5000) {
978     guestfs_progress progress_message =
979       { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
980
981     guestfs___progress_message_callback (g, &progress_message);
982   }
983 }
984
985 /* Return the location of the tmpdir (eg. "/tmp") and allow users
986  * to override it at runtime using $TMPDIR.
987  * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
988  */
989 const char *
990 guestfs_tmpdir (void)
991 {
992   const char *tmpdir;
993
994 #ifdef P_tmpdir
995   tmpdir = P_tmpdir;
996 #else
997   tmpdir = "/tmp";
998 #endif
999
1000   const char *t = getenv ("TMPDIR");
1001   if (t) tmpdir = t;
1002
1003   return tmpdir;
1004 }
1005
1006 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1007  * allow users to override it at runtime using $TMPDIR.
1008  * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1009  */
1010 const char *
1011 guestfs___persistent_tmpdir (void)
1012 {
1013   const char *tmpdir;
1014
1015   tmpdir = "/var/tmp";
1016
1017   const char *t = getenv ("TMPDIR");
1018   if (t) tmpdir = t;
1019
1020   return tmpdir;
1021 }
1022
1023 /* Compute Y - X and return the result in milliseconds.
1024  * Approximately the same as this code:
1025  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1026  */
1027 static int64_t
1028 timeval_diff (const struct timeval *x, const struct timeval *y)
1029 {
1030   int64_t msec;
1031
1032   msec = (y->tv_sec - x->tv_sec) * 1000;
1033   msec += (y->tv_usec - x->tv_usec) / 1000;
1034   return msec;
1035 }
1036
1037 /* Note that since this calls 'debug' it should only be called
1038  * from the parent process.
1039  */
1040 void
1041 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1042 {
1043   va_list args;
1044   char *msg;
1045   int err;
1046   struct timeval tv;
1047
1048   va_start (args, fs);
1049   err = vasprintf (&msg, fs, args);
1050   va_end (args);
1051
1052   if (err < 0) return;
1053
1054   gettimeofday (&tv, NULL);
1055
1056   debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1057
1058   free (msg);
1059 }
1060
1061 /* This is called from the forked subprocess just before qemu runs, so
1062  * it can just print the message straight to stderr, where it will be
1063  * picked up and funnelled through the usual appliance event API.
1064  */
1065 static void
1066 print_qemu_command_line (guestfs_h *g, char **argv)
1067 {
1068   int i = 0;
1069   int needs_quote;
1070
1071   struct timeval tv;
1072   gettimeofday (&tv, NULL);
1073   fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1074
1075   while (argv[i]) {
1076     if (argv[i][0] == '-') /* -option starts a new line */
1077       fprintf (stderr, " \\\n   ");
1078
1079     if (i > 0) fputc (' ', stderr);
1080
1081     /* Does it need shell quoting?  This only deals with simple cases. */
1082     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1083
1084     if (needs_quote) fputc ('\'', stderr);
1085     fprintf (stderr, "%s", argv[i]);
1086     if (needs_quote) fputc ('\'', stderr);
1087     i++;
1088   }
1089 }
1090
1091 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1092 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1093
1094 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1095  * 'qemu -version' so we know what options this qemu supports and
1096  * the version.
1097  */
1098 static int
1099 test_qemu (guestfs_h *g)
1100 {
1101   char cmd[1024];
1102   FILE *fp;
1103
1104   free (g->qemu_help);
1105   g->qemu_help = NULL;
1106   free (g->qemu_version);
1107   g->qemu_version = NULL;
1108
1109   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1110
1111   /* qemu -help should always work (qemu -version OTOH wasn't
1112    * supported by qemu 0.9).  If this command doesn't work then it
1113    * probably indicates that the qemu binary is missing.
1114    */
1115   if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1116     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."),
1117            cmd);
1118     return -1;
1119   }
1120
1121   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1122             g->qemu);
1123
1124   /* Intentionally ignore errors from qemu -version. */
1125   ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1126
1127   return 0;
1128 }
1129
1130 static int
1131 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1132 {
1133   FILE *fp;
1134
1135   fp = popen (cmd, "r");
1136   if (fp == NULL)
1137     return -1;
1138
1139   if (read_all (g, fp, ret) == -1) {
1140     pclose (fp);
1141     return -1;
1142   }
1143
1144   if (pclose (fp) != 0)
1145     return -1;
1146
1147   return 0;
1148 }
1149
1150 static int
1151 read_all (guestfs_h *g, FILE *fp, char **ret)
1152 {
1153   int r, n = 0;
1154   char *p;
1155
1156  again:
1157   if (feof (fp)) {
1158     *ret = safe_realloc (g, *ret, n + 1);
1159     (*ret)[n] = '\0';
1160     return n;
1161   }
1162
1163   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1164   p = &(*ret)[n];
1165   r = fread (p, 1, BUFSIZ, fp);
1166   if (ferror (fp)) {
1167     perrorf (g, "read");
1168     return -1;
1169   }
1170   n += r;
1171   goto again;
1172 }
1173
1174 /* Test if option is supported by qemu command line (just by grepping
1175  * the help text).
1176  *
1177  * The first time this is used, it has to run the external qemu
1178  * binary.  If that fails, it returns -1.
1179  *
1180  * To just do the first-time run of the qemu binary, call this with
1181  * option == NULL, in which case it will return -1 if there was an
1182  * error doing that.
1183  */
1184 static int
1185 qemu_supports (guestfs_h *g, const char *option)
1186 {
1187   if (!g->qemu_help) {
1188     if (test_qemu (g) == -1)
1189       return -1;
1190   }
1191
1192   if (option == NULL)
1193     return 1;
1194
1195   return strstr (g->qemu_help, option) != NULL;
1196 }
1197
1198 #if 0
1199 /* As above but using a regex instead of a fixed string. */
1200 static int
1201 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1202 {
1203   if (!g->qemu_help) {
1204     if (test_qemu (g) == -1)
1205       return -1;
1206   }
1207
1208   return match (g, g->qemu_help, option_regex);
1209 }
1210 #endif
1211
1212 /* Check if a file can be opened. */
1213 static int
1214 is_openable (guestfs_h *g, const char *path, int flags)
1215 {
1216   int fd = open (path, flags);
1217   if (fd == -1) {
1218     debug (g, "is_openable: %s: %m", path);
1219     return 0;
1220   }
1221   close (fd);
1222   return 1;
1223 }
1224
1225 /* You had to call this function after launch in versions <= 1.0.70,
1226  * but it is now a no-op.
1227  */
1228 int
1229 guestfs__wait_ready (guestfs_h *g)
1230 {
1231   if (g->state != READY)  {
1232     error (g, _("qemu has not been launched yet"));
1233     return -1;
1234   }
1235
1236   return 0;
1237 }
1238
1239 int
1240 guestfs__kill_subprocess (guestfs_h *g)
1241 {
1242   if (g->state == CONFIG) {
1243     error (g, _("no subprocess to kill"));
1244     return -1;
1245   }
1246
1247   debug (g, "sending SIGTERM to process %d", g->pid);
1248
1249   if (g->pid > 0) kill (g->pid, SIGTERM);
1250   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1251
1252   return 0;
1253 }
1254
1255 /* Access current state. */
1256 int
1257 guestfs__is_config (guestfs_h *g)
1258 {
1259   return g->state == CONFIG;
1260 }
1261
1262 int
1263 guestfs__is_launching (guestfs_h *g)
1264 {
1265   return g->state == LAUNCHING;
1266 }
1267
1268 int
1269 guestfs__is_ready (guestfs_h *g)
1270 {
1271   return g->state == READY;
1272 }
1273
1274 int
1275 guestfs__is_busy (guestfs_h *g)
1276 {
1277   return g->state == BUSY;
1278 }
1279
1280 int
1281 guestfs__get_state (guestfs_h *g)
1282 {
1283   return g->state;
1284 }