0d7a3f344db2fd3302a80f0b9073002ff8e4c16c
[libguestfs.git] / src / launch.c
1 /* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #include <sys/select.h>
35 #include <dirent.h>
36 #include <signal.h>
37
38 #include <rpc/types.h>
39 #include <rpc/xdr.h>
40
41 #ifdef HAVE_ERRNO_H
42 #include <errno.h>
43 #endif
44
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
47 #endif
48
49 #ifdef HAVE_SYS_WAIT_H
50 #include <sys/wait.h>
51 #endif
52
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
55 #endif
56
57 #ifdef HAVE_SYS_UN_H
58 #include <sys/un.h>
59 #endif
60
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
63
64 #include "c-ctype.h"
65 #include "glthread/lock.h"
66 #include "ignore-value.h"
67
68 #include "guestfs.h"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
72
73 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
74 static int qemu_supports (guestfs_h *g, const char *option);
75
76 /* Add a string to the current command line. */
77 static void
78 incr_cmdline_size (guestfs_h *g)
79 {
80   if (g->cmdline == NULL) {
81     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
82     g->cmdline_size = 1;
83     g->cmdline = safe_malloc (g, sizeof (char *));
84     g->cmdline[0] = NULL;
85   }
86
87   g->cmdline_size++;
88   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
89 }
90
91 static int
92 add_cmdline (guestfs_h *g, const char *str)
93 {
94   if (g->state != CONFIG) {
95     error (g,
96         _("command line cannot be altered after qemu subprocess launched"));
97     return -1;
98   }
99
100   incr_cmdline_size (g);
101   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
102   return 0;
103 }
104
105 int
106 guestfs__config (guestfs_h *g,
107                  const char *qemu_param, const char *qemu_value)
108 {
109   if (qemu_param[0] != '-') {
110     error (g, _("guestfs_config: parameter must begin with '-' character"));
111     return -1;
112   }
113
114   /* A bit fascist, but the user will probably break the extra
115    * parameters that we add if they try to set any of these.
116    */
117   if (STREQ (qemu_param, "-kernel") ||
118       STREQ (qemu_param, "-initrd") ||
119       STREQ (qemu_param, "-nographic") ||
120       STREQ (qemu_param, "-serial") ||
121       STREQ (qemu_param, "-full-screen") ||
122       STREQ (qemu_param, "-std-vga") ||
123       STREQ (qemu_param, "-vnc")) {
124     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
125     return -1;
126   }
127
128   if (add_cmdline (g, qemu_param) != 0) return -1;
129
130   if (qemu_value != NULL) {
131     if (add_cmdline (g, qemu_value) != 0) return -1;
132   }
133
134   return 0;
135 }
136
137 int
138 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
139                             const char *drive_if)
140 {
141   size_t len = strlen (filename) + 64;
142   char buf[len];
143
144   if (strchr (filename, ',') != NULL) {
145     error (g, _("filename cannot contain ',' (comma) character"));
146     return -1;
147   }
148
149   /* cache=off improves reliability in the event of a host crash.
150    *
151    * However this option causes qemu to try to open the file with
152    * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
153    * So we check if we can open the file with or without O_DIRECT,
154    * and use cache=off (or not) accordingly.
155    *
156    * This test also checks for the presence of the file, which
157    * is a documented semantic of this interface.
158    */
159   int fd = open (filename, O_RDONLY|O_DIRECT);
160   if (fd >= 0) {
161     close (fd);
162     snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
163   } else {
164     fd = open (filename, O_RDONLY);
165     if (fd >= 0) {
166       close (fd);
167       snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
168     } else {
169       perrorf (g, "%s", filename);
170       return -1;
171     }
172   }
173
174   return guestfs__config (g, "-drive", buf);
175 }
176
177 int
178 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
179                                const char *drive_if)
180 {
181   if (strchr (filename, ',') != NULL) {
182     error (g, _("filename cannot contain ',' (comma) character"));
183     return -1;
184   }
185
186   if (access (filename, F_OK) == -1) {
187     perrorf (g, "%s", filename);
188     return -1;
189   }
190
191   size_t len = strlen (filename) + 64;
192   char buf[len];
193
194   snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
195
196   return guestfs__config (g, "-drive", buf);
197 }
198
199 int
200 guestfs__add_drive (guestfs_h *g, const char *filename)
201 {
202   return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
203 }
204
205 int
206 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
207 {
208   return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
209 }
210
211 int
212 guestfs__add_cdrom (guestfs_h *g, const char *filename)
213 {
214   if (strchr (filename, ',') != NULL) {
215     error (g, _("filename cannot contain ',' (comma) character"));
216     return -1;
217   }
218
219   if (access (filename, F_OK) == -1) {
220     perrorf (g, "%s", filename);
221     return -1;
222   }
223
224   return guestfs__config (g, "-cdrom", filename);
225 }
226
227 /* Returns true iff file is contained in dir. */
228 static int
229 dir_contains_file (const char *dir, const char *file)
230 {
231   int dirlen = strlen (dir);
232   int filelen = strlen (file);
233   int len = dirlen+filelen+2;
234   char path[len];
235
236   snprintf (path, len, "%s/%s", dir, file);
237   return access (path, F_OK) == 0;
238 }
239
240 /* Returns true iff every listed file is contained in 'dir'. */
241 static int
242 dir_contains_files (const char *dir, ...)
243 {
244   va_list args;
245   const char *file;
246
247   va_start (args, dir);
248   while ((file = va_arg (args, const char *)) != NULL) {
249     if (!dir_contains_file (dir, file)) {
250       va_end (args);
251       return 0;
252     }
253   }
254   va_end (args);
255   return 1;
256 }
257
258 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
259 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
260 static int is_openable (guestfs_h *g, const char *path, int flags);
261 static void print_cmdline (guestfs_h *g);
262
263 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
264 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
265
266 int
267 guestfs__launch (guestfs_h *g)
268 {
269   const char *tmpdir;
270   char dir_template[PATH_MAX];
271   int r, pmore;
272   size_t len;
273   int wfd[2], rfd[2];
274   int tries;
275   char *path, *pelem, *pend;
276   char *kernel = NULL, *initrd = NULL;
277   int null_vmchannel_sock;
278   char unixsock[256];
279   struct sockaddr_un addr;
280
281   /* Configured? */
282   if (!g->cmdline) {
283     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
284     return -1;
285   }
286
287   if (g->state != CONFIG) {
288     error (g, _("the libguestfs handle has already been launched"));
289     return -1;
290   }
291
292   /* Start the clock ... */
293   gettimeofday (&g->launch_t, NULL);
294
295   /* Make the temporary directory. */
296 #ifdef P_tmpdir
297   tmpdir = P_tmpdir;
298 #else
299   tmpdir = "/tmp";
300 #endif
301
302   tmpdir = getenv ("TMPDIR") ? : tmpdir;
303   snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
304
305   if (!g->tmpdir) {
306     g->tmpdir = safe_strdup (g, dir_template);
307     if (mkdtemp (g->tmpdir) == NULL) {
308       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
309       goto cleanup0;
310     }
311   }
312
313   /* Allow anyone to read the temporary directory.  There are no
314    * secrets in the kernel or initrd files.  The socket in this
315    * directory won't be readable but anyone can see it exists if they
316    * want. (RHBZ#610880).
317    */
318   if (chmod (g->tmpdir, 0755) == -1)
319     fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
320
321   /* First search g->path for the supermin appliance, and try to
322    * synthesize a kernel and initrd from that.  If it fails, we
323    * try the path search again looking for a backup ordinary
324    * appliance.
325    */
326   pelem = path = safe_strdup (g, g->path);
327   do {
328     pend = strchrnul (pelem, ':');
329     pmore = *pend == ':';
330     *pend = '\0';
331     len = pend - pelem;
332
333     /* Empty element of "." means cwd. */
334     if (len == 0 || (len == 1 && *pelem == '.')) {
335       if (g->verbose)
336         fprintf (stderr,
337                  "looking for supermin appliance in current directory\n");
338       if (dir_contains_files (".",
339                               "supermin.d", "kmod.whitelist", NULL)) {
340         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
341           return -1;
342         break;
343       }
344     }
345     /* Look at <path>/supermin* etc. */
346     else {
347       if (g->verbose)
348         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
349
350       if (dir_contains_files (pelem,
351                               "supermin.d", "kmod.whitelist", NULL)) {
352         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
353           return -1;
354         break;
355       }
356     }
357
358     pelem = pend + 1;
359   } while (pmore);
360
361   free (path);
362
363   if (kernel == NULL || initrd == NULL) {
364     /* Search g->path for the kernel and initrd. */
365     pelem = path = safe_strdup (g, g->path);
366     do {
367       pend = strchrnul (pelem, ':');
368       pmore = *pend == ':';
369       *pend = '\0';
370       len = pend - pelem;
371
372       /* Empty element or "." means cwd. */
373       if (len == 0 || (len == 1 && *pelem == '.')) {
374         if (g->verbose)
375           fprintf (stderr,
376                    "looking for appliance in current directory\n");
377         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
378           kernel = safe_strdup (g, kernel_name);
379           initrd = safe_strdup (g, initrd_name);
380           break;
381         }
382       }
383       /* Look at <path>/kernel etc. */
384       else {
385         if (g->verbose)
386           fprintf (stderr, "looking for appliance in %s\n", pelem);
387
388         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
389           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
390           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
391           sprintf (kernel, "%s/%s", pelem, kernel_name);
392           sprintf (initrd, "%s/%s", pelem, initrd_name);
393           break;
394         }
395       }
396
397       pelem = pend + 1;
398     } while (pmore);
399
400     free (path);
401   }
402
403   if (kernel == NULL || initrd == NULL) {
404     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
405            kernel_name, initrd_name, g->path);
406     goto cleanup0;
407   }
408
409   if (g->verbose)
410     print_timestamped_message (g, "begin testing qemu features");
411
412   /* Get qemu help text and version. */
413   if (qemu_supports (g, NULL) == -1)
414     goto cleanup0;
415
416   /* Choose which vmchannel implementation to use. */
417   if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
418     /* The "null vmchannel" implementation.  Requires SLIRP (user mode
419      * networking in qemu) but no other vmchannel support.  The daemon
420      * will connect back to a random port number on localhost.
421      */
422     struct sockaddr_in addr;
423     socklen_t addrlen = sizeof addr;
424
425     g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
426     if (g->sock == -1) {
427       perrorf (g, "socket");
428       goto cleanup0;
429     }
430     addr.sin_family = AF_INET;
431     addr.sin_port = htons (0);
432     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
433     if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
434       perrorf (g, "bind");
435       goto cleanup0;
436     }
437
438     if (listen (g->sock, 256) == -1) {
439       perrorf (g, "listen");
440       goto cleanup0;
441     }
442
443     if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
444       perrorf (g, "getsockname");
445       goto cleanup0;
446     }
447
448     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
449       perrorf (g, "fcntl");
450       goto cleanup0;
451     }
452
453     null_vmchannel_sock = ntohs (addr.sin_port);
454     if (g->verbose)
455       fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
456   } else {
457     /* Using some vmchannel impl.  We need to create a local Unix
458      * domain socket for qemu to use.
459      */
460     snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
461     unlink (unixsock);
462     null_vmchannel_sock = 0;
463   }
464
465   if (!g->direct) {
466     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
467       perrorf (g, "pipe");
468       goto cleanup0;
469     }
470   }
471
472   if (g->verbose)
473     print_timestamped_message (g, "finished testing qemu features");
474
475   r = fork ();
476   if (r == -1) {
477     perrorf (g, "fork");
478     if (!g->direct) {
479       close (wfd[0]);
480       close (wfd[1]);
481       close (rfd[0]);
482       close (rfd[1]);
483     }
484     goto cleanup0;
485   }
486
487   if (r == 0) {                 /* Child (qemu). */
488     char buf[256];
489     const char *vmchannel = NULL;
490
491     /* Set up the full command line.  Do this in the subprocess so we
492      * don't need to worry about cleaning up.
493      */
494     g->cmdline[0] = g->qemu;
495
496     /* qemu sometimes needs this option to enable hardware
497      * virtualization, but some versions of 'qemu-kvm' will use KVM
498      * regardless (even where this option appears in the help text).
499      * It is rumoured that there are versions of qemu where supplying
500      * this option when hardware virtualization is not available will
501      * cause qemu to fail, so we we have to check at least that
502      * /dev/kvm is openable.  That's not reliable, since /dev/kvm
503      * might be openable by qemu but not by us (think: SELinux) in
504      * which case the user would not get hardware virtualization,
505      * although at least shouldn't fail.  A giant clusterfuck with the
506      * qemu command line, again.
507      */
508     if (qemu_supports (g, "-enable-kvm") &&
509         is_openable (g, "/dev/kvm", O_RDWR))
510       add_cmdline (g, "-enable-kvm");
511
512     /* Newer versions of qemu (from around 2009/12) changed the
513      * behaviour of monitors so that an implicit '-monitor stdio' is
514      * assumed if we are in -nographic mode and there is no other
515      * -monitor option.  Only a single stdio device is allowed, so
516      * this broke the '-serial stdio' option.  There is a new flag
517      * called -nodefaults which gets rid of all this default crud, so
518      * let's use that to avoid this and any future surprises.
519      */
520     if (qemu_supports (g, "-nodefaults"))
521       add_cmdline (g, "-nodefaults");
522
523     add_cmdline (g, "-nographic");
524     add_cmdline (g, "-serial");
525     add_cmdline (g, "stdio");
526
527     snprintf (buf, sizeof buf, "%d", g->memsize);
528     add_cmdline (g, "-m");
529     add_cmdline (g, buf);
530
531     /* Force exit instead of reboot on panic */
532     add_cmdline (g, "-no-reboot");
533
534     /* These options recommended by KVM developers to improve reliability. */
535     if (qemu_supports (g, "-no-hpet"))
536       add_cmdline (g, "-no-hpet");
537
538     if (qemu_supports (g, "-rtc-td-hack"))
539       add_cmdline (g, "-rtc-td-hack");
540
541     /* If qemu has SLIRP (user mode network) enabled then we can get
542      * away with "no vmchannel", where we just connect back to a random
543      * host port.
544      */
545     if (null_vmchannel_sock) {
546       add_cmdline (g, "-net");
547       add_cmdline (g, "user,vlan=0,net=" NETWORK);
548
549       snprintf (buf, sizeof buf,
550                 "guestfs_vmchannel=tcp:" ROUTER ":%d",
551                 null_vmchannel_sock);
552       vmchannel = strdup (buf);
553     }
554
555     /* New-style -net user,guestfwd=... syntax for guestfwd.  See:
556      *
557      * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
558      *
559      * The original suggested format doesn't work, see:
560      *
561      * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
562      *
563      * However Gerd Hoffman privately suggested to me using -chardev
564      * instead, which does work.
565      */
566     else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
567       snprintf (buf, sizeof buf,
568                 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
569
570       add_cmdline (g, "-chardev");
571       add_cmdline (g, buf);
572
573       snprintf (buf, sizeof buf,
574                 "user,vlan=0,net=" NETWORK ","
575                 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
576                 "-chardev:guestfsvmc");
577
578       add_cmdline (g, "-net");
579       add_cmdline (g, buf);
580
581       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
582     }
583
584     /* Not guestfwd.  HOPEFULLY this qemu uses the older -net channel
585      * syntax, or if not then we'll get a quick failure.
586      */
587     else {
588       snprintf (buf, sizeof buf,
589                 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
590
591       add_cmdline (g, "-net");
592       add_cmdline (g, buf);
593       add_cmdline (g, "-net");
594       add_cmdline (g, "user,vlan=0,net=" NETWORK);
595
596       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
597     }
598     add_cmdline (g, "-net");
599     add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
600
601 #define LINUX_CMDLINE                                                   \
602     "panic=1 "         /* force kernel to panic if daemon exits */      \
603     "console=ttyS0 "   /* serial console */                             \
604     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
605     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
606     "acpi=off "        /* we don't need ACPI, turn it off */            \
607     "printk.time=1 "   /* display timestamp before kernel messages */   \
608     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
609
610     /* Linux kernel command line. */
611     snprintf (buf, sizeof buf,
612               LINUX_CMDLINE
613               "%s "             /* (selinux) */
614               "%s "             /* (vmchannel) */
615               "%s "             /* (verbose) */
616               "TERM=%s "        /* (TERM environment variable) */
617               "%s",             /* (append) */
618               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
619               vmchannel ? vmchannel : "",
620               g->verbose ? "guestfs_verbose=1" : "",
621               getenv ("TERM") ? : "linux",
622               g->append ? g->append : "");
623
624     add_cmdline (g, "-kernel");
625     add_cmdline (g, (char *) kernel);
626     add_cmdline (g, "-initrd");
627     add_cmdline (g, (char *) initrd);
628     add_cmdline (g, "-append");
629     add_cmdline (g, buf);
630
631     /* Finish off the command line. */
632     incr_cmdline_size (g);
633     g->cmdline[g->cmdline_size-1] = NULL;
634
635     if (g->verbose)
636       print_cmdline (g);
637
638     if (!g->direct) {
639       /* Set up stdin, stdout. */
640       close (0);
641       close (1);
642       close (wfd[1]);
643       close (rfd[0]);
644
645       if (dup (wfd[0]) == -1) {
646       dup_failed:
647         perror ("dup failed");
648         _exit (EXIT_FAILURE);
649       }
650       if (dup (rfd[1]) == -1)
651         goto dup_failed;
652
653       close (wfd[0]);
654       close (rfd[1]);
655     }
656
657 #if 0
658     /* Set up a new process group, so we can signal this process
659      * and all subprocesses (eg. if qemu is really a shell script).
660      */
661     setpgid (0, 0);
662 #endif
663
664     setenv ("LC_ALL", "C", 1);
665
666     execv (g->qemu, g->cmdline); /* Run qemu. */
667     perror (g->qemu);
668     _exit (EXIT_FAILURE);
669   }
670
671   /* Parent (library). */
672   g->pid = r;
673
674   free (kernel);
675   kernel = NULL;
676   free (initrd);
677   initrd = NULL;
678
679   /* Fork the recovery process off which will kill qemu if the parent
680    * process fails to do so (eg. if the parent segfaults).
681    */
682   g->recoverypid = -1;
683   if (g->recovery_proc) {
684     r = fork ();
685     if (r == 0) {
686       pid_t qemu_pid = g->pid;
687       pid_t parent_pid = getppid ();
688
689       /* Writing to argv is hideously complicated and error prone.  See:
690        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
691        */
692
693       /* Loop around waiting for one or both of the other processes to
694        * disappear.  It's fair to say this is very hairy.  The PIDs that
695        * we are looking at might be reused by another process.  We are
696        * effectively polling.  Is the cure worse than the disease?
697        */
698       for (;;) {
699         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
700           _exit (EXIT_SUCCESS);
701         if (kill (parent_pid, 0) == -1) {
702           /* Parent's gone away, qemu still around, so kill qemu. */
703           kill (qemu_pid, 9);
704           _exit (EXIT_SUCCESS);
705         }
706         sleep (2);
707       }
708     }
709
710     /* Don't worry, if the fork failed, this will be -1.  The recovery
711      * process isn't essential.
712      */
713     g->recoverypid = r;
714   }
715
716   if (!g->direct) {
717     /* Close the other ends of the pipe. */
718     close (wfd[0]);
719     close (rfd[1]);
720
721     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
722         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
723       perrorf (g, "fcntl");
724       goto cleanup1;
725     }
726
727     g->fd[0] = wfd[1];          /* stdin of child */
728     g->fd[1] = rfd[0];          /* stdout of child */
729   } else {
730     g->fd[0] = open ("/dev/null", O_RDWR);
731     if (g->fd[0] == -1) {
732       perrorf (g, "open /dev/null");
733       goto cleanup1;
734     }
735     g->fd[1] = dup (g->fd[0]);
736     if (g->fd[1] == -1) {
737       perrorf (g, "dup");
738       close (g->fd[0]);
739       goto cleanup1;
740     }
741   }
742
743   if (null_vmchannel_sock) {
744     int sock = -1;
745     uid_t uid;
746
747     /* Null vmchannel implementation: We listen on g->sock for a
748      * connection.  The connection could come from any local process
749      * so we must check it comes from the appliance (or at least
750      * from our UID) for security reasons.
751      */
752     while (sock == -1) {
753       sock = guestfs___accept_from_daemon (g);
754       if (sock == -1)
755         goto cleanup1;
756
757       if (check_peer_euid (g, sock, &uid) == -1)
758         goto cleanup1;
759       if (uid != geteuid ()) {
760         fprintf (stderr,
761                  "libguestfs: warning: unexpected connection from UID %d to port %d\n",
762                  uid, null_vmchannel_sock);
763         close (sock);
764         sock = -1;
765         continue;
766       }
767     }
768
769     if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
770       perrorf (g, "fcntl");
771       goto cleanup1;
772     }
773
774     close (g->sock);
775     g->sock = sock;
776   } else {
777     /* Other vmchannel.  Open the Unix socket.
778      *
779      * The vmchannel implementation that got merged with qemu sucks in
780      * a number of ways.  Both ends do connect(2), which means that no
781      * one knows what, if anything, is connected to the other end, or
782      * if it becomes disconnected.  Even worse, we have to wait some
783      * indeterminate time for qemu to create the socket and connect to
784      * it (which happens very early in qemu's start-up), so any code
785      * that uses vmchannel is inherently racy.  Hence this silly loop.
786      */
787     g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
788     if (g->sock == -1) {
789       perrorf (g, "socket");
790       goto cleanup1;
791     }
792
793     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
794       perrorf (g, "fcntl");
795       goto cleanup1;
796     }
797
798     addr.sun_family = AF_UNIX;
799     strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
800     addr.sun_path[UNIX_PATH_MAX-1] = '\0';
801
802     tries = 100;
803     /* Always sleep at least once to give qemu a small chance to start up. */
804     usleep (10000);
805     while (tries > 0) {
806       r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
807       if ((r == -1 && errno == EINPROGRESS) || r == 0)
808         goto connected;
809
810       if (errno != ENOENT)
811         perrorf (g, "connect");
812       tries--;
813       usleep (100000);
814     }
815
816     error (g, _("failed to connect to vmchannel socket"));
817     goto cleanup1;
818
819   connected: ;
820   }
821
822   g->state = LAUNCHING;
823
824   /* Wait for qemu to start and to connect back to us via vmchannel and
825    * send the GUESTFS_LAUNCH_FLAG message.
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     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   return 0;
853
854  cleanup1:
855   if (!g->direct) {
856     close (wfd[1]);
857     close (rfd[0]);
858   }
859   if (g->pid > 0) kill (g->pid, 9);
860   if (g->recoverypid > 0) kill (g->recoverypid, 9);
861   waitpid (g->pid, NULL, 0);
862   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
863   g->fd[0] = -1;
864   g->fd[1] = -1;
865   g->pid = 0;
866   g->recoverypid = 0;
867   memset (&g->launch_t, 0, sizeof g->launch_t);
868
869  cleanup0:
870   if (g->sock >= 0) {
871     close (g->sock);
872     g->sock = -1;
873   }
874   g->state = CONFIG;
875   free (kernel);
876   free (initrd);
877   return -1;
878 }
879
880 /* This function is used to print the qemu command line before it gets
881  * executed, when in verbose mode.
882  */
883 static void
884 print_cmdline (guestfs_h *g)
885 {
886   int i = 0;
887   int needs_quote;
888
889   while (g->cmdline[i]) {
890     if (g->cmdline[i][0] == '-') /* -option starts a new line */
891       fprintf (stderr, " \\\n   ");
892
893     if (i > 0) fputc (' ', stderr);
894
895     /* Does it need shell quoting?  This only deals with simple cases. */
896     needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
897
898     if (needs_quote) fputc ('\'', stderr);
899     fprintf (stderr, "%s", g->cmdline[i]);
900     if (needs_quote) fputc ('\'', stderr);
901     i++;
902   }
903
904   fputc ('\n', stderr);
905 }
906
907 /* This function does the hard work of building the supermin appliance
908  * on the fly.  'path' is the directory containing the control files.
909  * 'kernel' and 'initrd' are where we will return the names of the
910  * kernel and initrd (only initrd is built).  The work is done by
911  * an external script.  We just tell it where to put the result.
912  */
913 static int
914 build_supermin_appliance (guestfs_h *g, const char *path,
915                           char **kernel, char **initrd)
916 {
917   char cmd[4096];
918   int r, len;
919
920   if (g->verbose)
921     print_timestamped_message (g, "begin building supermin appliance");
922
923   len = strlen (g->tmpdir);
924   *kernel = safe_malloc (g, len + 8);
925   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
926   *initrd = safe_malloc (g, len + 8);
927   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
928
929   /* Set a sensible umask in the subprocess, so kernel and initrd
930    * output files are world-readable (RHBZ#610880).
931    */
932   snprintf (cmd, sizeof cmd,
933             "umask 0002; "
934             "febootstrap-supermin-helper%s "
935             "-k '%s/kmod.whitelist' "
936             "'%s/supermin.d' "
937             host_cpu " "
938             "%s %s",
939             g->verbose ? " --verbose" : "",
940             path,
941             path,
942             *kernel, *initrd);
943   if (g->verbose)
944     print_timestamped_message (g, "%s", cmd);
945
946   r = system (cmd);
947   if (r == -1 || WEXITSTATUS(r) != 0) {
948     error (g, _("external command failed: %s"), cmd);
949     free (*kernel);
950     free (*initrd);
951     *kernel = *initrd = NULL;
952     return -1;
953   }
954
955   if (g->verbose)
956     print_timestamped_message (g, "finished building supermin appliance");
957
958   return 0;
959 }
960
961 /* Compute Y - X and return the result in milliseconds.
962  * Approximately the same as this code:
963  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
964  */
965 static int64_t
966 timeval_diff (const struct timeval *x, const struct timeval *y)
967 {
968   int64_t msec;
969
970   msec = (y->tv_sec - x->tv_sec) * 1000;
971   msec += (y->tv_usec - x->tv_usec) / 1000;
972   return msec;
973 }
974
975 static void
976 print_timestamped_message (guestfs_h *g, const char *fs, ...)
977 {
978   va_list args;
979   char *msg;
980   int err;
981   struct timeval tv;
982
983   va_start (args, fs);
984   err = vasprintf (&msg, fs, args);
985   va_end (args);
986
987   if (err < 0) return;
988
989   gettimeofday (&tv, NULL);
990
991   fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
992            timeval_diff (&g->launch_t, &tv), msg);
993
994   free (msg);
995 }
996
997 static int read_all (guestfs_h *g, FILE *fp, char **ret);
998
999 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1000  * 'qemu -version' so we know what options this qemu supports and
1001  * the version.
1002  */
1003 static int
1004 test_qemu (guestfs_h *g)
1005 {
1006   char cmd[1024];
1007   FILE *fp;
1008
1009   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1010
1011   fp = popen (cmd, "r");
1012   /* qemu -help should always work (qemu -version OTOH wasn't
1013    * supported by qemu 0.9).  If this command doesn't work then it
1014    * probably indicates that the qemu binary is missing.
1015    */
1016   if (!fp) {
1017     /* XXX This error is never printed, even if the qemu binary
1018      * doesn't exist.  Why?
1019      */
1020   error:
1021     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1022     return -1;
1023   }
1024
1025   if (read_all (g, fp, &g->qemu_help) == -1)
1026     goto error;
1027
1028   if (pclose (fp) == -1)
1029     goto error;
1030
1031   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1032             g->qemu);
1033
1034   fp = popen (cmd, "r");
1035   if (fp) {
1036     /* Intentionally ignore errors. */
1037     read_all (g, fp, &g->qemu_version);
1038     pclose (fp);
1039   }
1040
1041   return 0;
1042 }
1043
1044 static int
1045 read_all (guestfs_h *g, FILE *fp, char **ret)
1046 {
1047   int r, n = 0;
1048   char *p;
1049
1050  again:
1051   if (feof (fp)) {
1052     *ret = safe_realloc (g, *ret, n + 1);
1053     (*ret)[n] = '\0';
1054     return n;
1055   }
1056
1057   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1058   p = &(*ret)[n];
1059   r = fread (p, 1, BUFSIZ, fp);
1060   if (ferror (fp)) {
1061     perrorf (g, "read");
1062     return -1;
1063   }
1064   n += r;
1065   goto again;
1066 }
1067
1068 /* Test if option is supported by qemu command line (just by grepping
1069  * the help text).
1070  *
1071  * The first time this is used, it has to run the external qemu
1072  * binary.  If that fails, it returns -1.
1073  *
1074  * To just do the first-time run of the qemu binary, call this with
1075  * option == NULL, in which case it will return -1 if there was an
1076  * error doing that.
1077  */
1078 static int
1079 qemu_supports (guestfs_h *g, const char *option)
1080 {
1081   if (!g->qemu_help) {
1082     if (test_qemu (g) == -1)
1083       return -1;
1084   }
1085
1086   if (option == NULL)
1087     return 1;
1088
1089   return strstr (g->qemu_help, option) != NULL;
1090 }
1091
1092 /* Check if a file can be opened. */
1093 static int
1094 is_openable (guestfs_h *g, const char *path, int flags)
1095 {
1096   int fd = open (path, flags);
1097   if (fd == -1) {
1098     if (g->verbose)
1099       perror (path);
1100     return 0;
1101   }
1102   close (fd);
1103   return 1;
1104 }
1105
1106 /* Check the peer effective UID for a TCP socket.  Ideally we'd like
1107  * SO_PEERCRED for a loopback TCP socket.  This isn't possible on
1108  * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1109  */
1110 static int
1111 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1112 {
1113 #if CAN_CHECK_PEER_EUID
1114   struct sockaddr_in peer;
1115   socklen_t addrlen = sizeof peer;
1116
1117   if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1118     perrorf (g, "getpeername");
1119     return -1;
1120   }
1121
1122   if (peer.sin_family != AF_INET ||
1123       ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1124     error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1125            peer.sin_family, inet_ntoa (peer.sin_addr));
1126     return -1;
1127   }
1128
1129   struct sockaddr_in our;
1130   addrlen = sizeof our;
1131   if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1132     perrorf (g, "getsockname");
1133     return -1;
1134   }
1135
1136   FILE *fp = fopen ("/proc/net/tcp", "r");
1137   if (fp == NULL) {
1138     perrorf (g, "/proc/net/tcp");
1139     return -1;
1140   }
1141
1142   char line[256];
1143   if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1144     error (g, "unexpected end of file in /proc/net/tcp");
1145     fclose (fp);
1146     return -1;
1147   }
1148
1149   while (fgets (line, sizeof line, fp) != NULL) {
1150     unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1151     int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1152     int line_uid;
1153
1154     if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1155                 &dummy0,
1156                 &line_our_addr, &line_our_port,
1157                 &line_peer_addr, &line_peer_port,
1158                 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1159                 &line_uid) == 12) {
1160       /* Note about /proc/net/tcp: local_address and rem_address are
1161        * always in network byte order.  However the port part is
1162        * always in host byte order.
1163        *
1164        * The sockname and peername that we got above are in network
1165        * byte order.  So we have to byte swap the port but not the
1166        * address part.
1167        */
1168       if (line_our_addr == our.sin_addr.s_addr &&
1169           line_our_port == ntohs (our.sin_port) &&
1170           line_peer_addr == peer.sin_addr.s_addr &&
1171           line_peer_port == ntohs (peer.sin_port)) {
1172         *rtn = line_uid;
1173         fclose (fp);
1174         return 0;
1175       }
1176     }
1177   }
1178
1179   error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1180   fclose (fp);
1181   return -1;
1182 #else /* !CAN_CHECK_PEER_EUID */
1183   /* This function exists but should never be called in this
1184    * configuration.
1185    */
1186   abort ();
1187 #endif /* !CAN_CHECK_PEER_EUID */
1188 }
1189
1190 /* You had to call this function after launch in versions <= 1.0.70,
1191  * but it is now a no-op.
1192  */
1193 int
1194 guestfs__wait_ready (guestfs_h *g)
1195 {
1196   if (g->state != READY)  {
1197     error (g, _("qemu has not been launched yet"));
1198     return -1;
1199   }
1200
1201   return 0;
1202 }
1203
1204 int
1205 guestfs__kill_subprocess (guestfs_h *g)
1206 {
1207   if (g->state == CONFIG) {
1208     error (g, _("no subprocess to kill"));
1209     return -1;
1210   }
1211
1212   if (g->verbose)
1213     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1214
1215   if (g->pid > 0) kill (g->pid, SIGTERM);
1216   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1217
1218   return 0;
1219 }
1220
1221 /* Access current state. */
1222 int
1223 guestfs__is_config (guestfs_h *g)
1224 {
1225   return g->state == CONFIG;
1226 }
1227
1228 int
1229 guestfs__is_launching (guestfs_h *g)
1230 {
1231   return g->state == LAUNCHING;
1232 }
1233
1234 int
1235 guestfs__is_ready (guestfs_h *g)
1236 {
1237   return g->state == READY;
1238 }
1239
1240 int
1241 guestfs__is_busy (guestfs_h *g)
1242 {
1243   return g->state == BUSY;
1244 }
1245
1246 int
1247 guestfs__get_state (guestfs_h *g)
1248 {
1249   return g->state;
1250 }