Make print_timestamped_message into a cross-module function.
[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 int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
259 static int is_openable (guestfs_h *g, const char *path, int flags);
260 static void print_cmdline (guestfs_h *g);
261
262 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
263 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
264
265 int
266 guestfs__launch (guestfs_h *g)
267 {
268   int r, pmore;
269   size_t len;
270   int wfd[2], rfd[2];
271   int tries;
272   char *path, *pelem, *pend;
273   char *kernel = NULL, *initrd = NULL;
274   int null_vmchannel_sock;
275   char unixsock[256];
276   struct sockaddr_un addr;
277
278   /* Configured? */
279   if (!g->cmdline) {
280     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
281     return -1;
282   }
283
284   if (g->state != CONFIG) {
285     error (g, _("the libguestfs handle has already been launched"));
286     return -1;
287   }
288
289   /* Start the clock ... */
290   gettimeofday (&g->launch_t, NULL);
291
292   /* Make the temporary directory. */
293   if (!g->tmpdir) {
294     const char *tmpdir = guestfs___tmpdir ();
295     char dir_template[strlen (tmpdir) + 32];
296     sprintf (dir_template, "%s/libguestfsXXXXXX", tmpdir);
297
298     g->tmpdir = safe_strdup (g, dir_template);
299     if (mkdtemp (g->tmpdir) == NULL) {
300       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
301       goto cleanup0;
302     }
303   }
304
305   /* Allow anyone to read the temporary directory.  There are no
306    * secrets in the kernel or initrd files.  The socket in this
307    * directory won't be readable but anyone can see it exists if they
308    * want. (RHBZ#610880).
309    */
310   if (chmod (g->tmpdir, 0755) == -1)
311     fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
312
313   /* First search g->path for the supermin appliance, and try to
314    * synthesize a kernel and initrd from that.  If it fails, we
315    * try the path search again looking for a backup ordinary
316    * appliance.
317    */
318   pelem = path = safe_strdup (g, g->path);
319   do {
320     pend = strchrnul (pelem, ':');
321     pmore = *pend == ':';
322     *pend = '\0';
323     len = pend - pelem;
324
325     /* Empty element of "." means cwd. */
326     if (len == 0 || (len == 1 && *pelem == '.')) {
327       if (g->verbose)
328         fprintf (stderr,
329                  "looking for supermin appliance in current directory\n");
330       if (dir_contains_files (".",
331                               "supermin.d", "kmod.whitelist", NULL)) {
332         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
333           return -1;
334         break;
335       }
336     }
337     /* Look at <path>/supermin* etc. */
338     else {
339       if (g->verbose)
340         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
341
342       if (dir_contains_files (pelem,
343                               "supermin.d", "kmod.whitelist", NULL)) {
344         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
345           return -1;
346         break;
347       }
348     }
349
350     pelem = pend + 1;
351   } while (pmore);
352
353   free (path);
354
355   if (kernel == NULL || initrd == NULL) {
356     /* Search g->path for the kernel and initrd. */
357     pelem = path = safe_strdup (g, g->path);
358     do {
359       pend = strchrnul (pelem, ':');
360       pmore = *pend == ':';
361       *pend = '\0';
362       len = pend - pelem;
363
364       /* Empty element or "." means cwd. */
365       if (len == 0 || (len == 1 && *pelem == '.')) {
366         if (g->verbose)
367           fprintf (stderr,
368                    "looking for appliance in current directory\n");
369         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
370           kernel = safe_strdup (g, kernel_name);
371           initrd = safe_strdup (g, initrd_name);
372           break;
373         }
374       }
375       /* Look at <path>/kernel etc. */
376       else {
377         if (g->verbose)
378           fprintf (stderr, "looking for appliance in %s\n", pelem);
379
380         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
381           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
382           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
383           sprintf (kernel, "%s/%s", pelem, kernel_name);
384           sprintf (initrd, "%s/%s", pelem, initrd_name);
385           break;
386         }
387       }
388
389       pelem = pend + 1;
390     } while (pmore);
391
392     free (path);
393   }
394
395   if (kernel == NULL || initrd == NULL) {
396     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
397            kernel_name, initrd_name, g->path);
398     goto cleanup0;
399   }
400
401   if (g->verbose)
402     guestfs___print_timestamped_message (g, "begin testing qemu features");
403
404   /* Get qemu help text and version. */
405   if (qemu_supports (g, NULL) == -1)
406     goto cleanup0;
407
408   /* Choose which vmchannel implementation to use. */
409   if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
410     /* The "null vmchannel" implementation.  Requires SLIRP (user mode
411      * networking in qemu) but no other vmchannel support.  The daemon
412      * will connect back to a random port number on localhost.
413      */
414     struct sockaddr_in addr;
415     socklen_t addrlen = sizeof addr;
416
417     g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
418     if (g->sock == -1) {
419       perrorf (g, "socket");
420       goto cleanup0;
421     }
422     addr.sin_family = AF_INET;
423     addr.sin_port = htons (0);
424     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
425     if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
426       perrorf (g, "bind");
427       goto cleanup0;
428     }
429
430     if (listen (g->sock, 256) == -1) {
431       perrorf (g, "listen");
432       goto cleanup0;
433     }
434
435     if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
436       perrorf (g, "getsockname");
437       goto cleanup0;
438     }
439
440     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
441       perrorf (g, "fcntl");
442       goto cleanup0;
443     }
444
445     null_vmchannel_sock = ntohs (addr.sin_port);
446     if (g->verbose)
447       fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
448   } else {
449     /* Using some vmchannel impl.  We need to create a local Unix
450      * domain socket for qemu to use.
451      */
452     snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
453     unlink (unixsock);
454     null_vmchannel_sock = 0;
455   }
456
457   if (!g->direct) {
458     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
459       perrorf (g, "pipe");
460       goto cleanup0;
461     }
462   }
463
464   if (g->verbose)
465     guestfs___print_timestamped_message (g, "finished testing qemu features");
466
467   r = fork ();
468   if (r == -1) {
469     perrorf (g, "fork");
470     if (!g->direct) {
471       close (wfd[0]);
472       close (wfd[1]);
473       close (rfd[0]);
474       close (rfd[1]);
475     }
476     goto cleanup0;
477   }
478
479   if (r == 0) {                 /* Child (qemu). */
480     char buf[256];
481     const char *vmchannel = NULL;
482
483     /* Set up the full command line.  Do this in the subprocess so we
484      * don't need to worry about cleaning up.
485      */
486     g->cmdline[0] = g->qemu;
487
488     /* qemu sometimes needs this option to enable hardware
489      * virtualization, but some versions of 'qemu-kvm' will use KVM
490      * regardless (even where this option appears in the help text).
491      * It is rumoured that there are versions of qemu where supplying
492      * this option when hardware virtualization is not available will
493      * cause qemu to fail, so we we have to check at least that
494      * /dev/kvm is openable.  That's not reliable, since /dev/kvm
495      * might be openable by qemu but not by us (think: SELinux) in
496      * which case the user would not get hardware virtualization,
497      * although at least shouldn't fail.  A giant clusterfuck with the
498      * qemu command line, again.
499      */
500     if (qemu_supports (g, "-enable-kvm") &&
501         is_openable (g, "/dev/kvm", O_RDWR))
502       add_cmdline (g, "-enable-kvm");
503
504     /* Newer versions of qemu (from around 2009/12) changed the
505      * behaviour of monitors so that an implicit '-monitor stdio' is
506      * assumed if we are in -nographic mode and there is no other
507      * -monitor option.  Only a single stdio device is allowed, so
508      * this broke the '-serial stdio' option.  There is a new flag
509      * called -nodefaults which gets rid of all this default crud, so
510      * let's use that to avoid this and any future surprises.
511      */
512     if (qemu_supports (g, "-nodefaults"))
513       add_cmdline (g, "-nodefaults");
514
515     add_cmdline (g, "-nographic");
516     add_cmdline (g, "-serial");
517     add_cmdline (g, "stdio");
518
519     snprintf (buf, sizeof buf, "%d", g->memsize);
520     add_cmdline (g, "-m");
521     add_cmdline (g, buf);
522
523     /* Force exit instead of reboot on panic */
524     add_cmdline (g, "-no-reboot");
525
526     /* These options recommended by KVM developers to improve reliability. */
527     if (qemu_supports (g, "-no-hpet"))
528       add_cmdline (g, "-no-hpet");
529
530     if (qemu_supports (g, "-rtc-td-hack"))
531       add_cmdline (g, "-rtc-td-hack");
532
533     /* If qemu has SLIRP (user mode network) enabled then we can get
534      * away with "no vmchannel", where we just connect back to a random
535      * host port.
536      */
537     if (null_vmchannel_sock) {
538       add_cmdline (g, "-net");
539       add_cmdline (g, "user,vlan=0,net=" NETWORK);
540
541       snprintf (buf, sizeof buf,
542                 "guestfs_vmchannel=tcp:" ROUTER ":%d",
543                 null_vmchannel_sock);
544       vmchannel = strdup (buf);
545     }
546
547     /* New-style -net user,guestfwd=... syntax for guestfwd.  See:
548      *
549      * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
550      *
551      * The original suggested format doesn't work, see:
552      *
553      * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
554      *
555      * However Gerd Hoffman privately suggested to me using -chardev
556      * instead, which does work.
557      */
558     else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
559       snprintf (buf, sizeof buf,
560                 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
561
562       add_cmdline (g, "-chardev");
563       add_cmdline (g, buf);
564
565       snprintf (buf, sizeof buf,
566                 "user,vlan=0,net=" NETWORK ","
567                 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
568                 "-chardev:guestfsvmc");
569
570       add_cmdline (g, "-net");
571       add_cmdline (g, buf);
572
573       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
574     }
575
576     /* Not guestfwd.  HOPEFULLY this qemu uses the older -net channel
577      * syntax, or if not then we'll get a quick failure.
578      */
579     else {
580       snprintf (buf, sizeof buf,
581                 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
582
583       add_cmdline (g, "-net");
584       add_cmdline (g, buf);
585       add_cmdline (g, "-net");
586       add_cmdline (g, "user,vlan=0,net=" NETWORK);
587
588       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
589     }
590     add_cmdline (g, "-net");
591     add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
592
593 #define LINUX_CMDLINE                                                   \
594     "panic=1 "         /* force kernel to panic if daemon exits */      \
595     "console=ttyS0 "   /* serial console */                             \
596     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
597     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
598     "acpi=off "        /* we don't need ACPI, turn it off */            \
599     "printk.time=1 "   /* display timestamp before kernel messages */   \
600     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
601
602     /* Linux kernel command line. */
603     snprintf (buf, sizeof buf,
604               LINUX_CMDLINE
605               "%s "             /* (selinux) */
606               "%s "             /* (vmchannel) */
607               "%s "             /* (verbose) */
608               "TERM=%s "        /* (TERM environment variable) */
609               "%s",             /* (append) */
610               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
611               vmchannel ? vmchannel : "",
612               g->verbose ? "guestfs_verbose=1" : "",
613               getenv ("TERM") ? : "linux",
614               g->append ? g->append : "");
615
616     add_cmdline (g, "-kernel");
617     add_cmdline (g, (char *) kernel);
618     add_cmdline (g, "-initrd");
619     add_cmdline (g, (char *) initrd);
620     add_cmdline (g, "-append");
621     add_cmdline (g, buf);
622
623     /* Finish off the command line. */
624     incr_cmdline_size (g);
625     g->cmdline[g->cmdline_size-1] = NULL;
626
627     if (g->verbose)
628       print_cmdline (g);
629
630     if (!g->direct) {
631       /* Set up stdin, stdout. */
632       close (0);
633       close (1);
634       close (wfd[1]);
635       close (rfd[0]);
636
637       if (dup (wfd[0]) == -1) {
638       dup_failed:
639         perror ("dup failed");
640         _exit (EXIT_FAILURE);
641       }
642       if (dup (rfd[1]) == -1)
643         goto dup_failed;
644
645       close (wfd[0]);
646       close (rfd[1]);
647     }
648
649 #if 0
650     /* Set up a new process group, so we can signal this process
651      * and all subprocesses (eg. if qemu is really a shell script).
652      */
653     setpgid (0, 0);
654 #endif
655
656     setenv ("LC_ALL", "C", 1);
657
658     execv (g->qemu, g->cmdline); /* Run qemu. */
659     perror (g->qemu);
660     _exit (EXIT_FAILURE);
661   }
662
663   /* Parent (library). */
664   g->pid = r;
665
666   free (kernel);
667   kernel = NULL;
668   free (initrd);
669   initrd = NULL;
670
671   /* Fork the recovery process off which will kill qemu if the parent
672    * process fails to do so (eg. if the parent segfaults).
673    */
674   g->recoverypid = -1;
675   if (g->recovery_proc) {
676     r = fork ();
677     if (r == 0) {
678       pid_t qemu_pid = g->pid;
679       pid_t parent_pid = getppid ();
680
681       /* Writing to argv is hideously complicated and error prone.  See:
682        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
683        */
684
685       /* Loop around waiting for one or both of the other processes to
686        * disappear.  It's fair to say this is very hairy.  The PIDs that
687        * we are looking at might be reused by another process.  We are
688        * effectively polling.  Is the cure worse than the disease?
689        */
690       for (;;) {
691         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
692           _exit (EXIT_SUCCESS);
693         if (kill (parent_pid, 0) == -1) {
694           /* Parent's gone away, qemu still around, so kill qemu. */
695           kill (qemu_pid, 9);
696           _exit (EXIT_SUCCESS);
697         }
698         sleep (2);
699       }
700     }
701
702     /* Don't worry, if the fork failed, this will be -1.  The recovery
703      * process isn't essential.
704      */
705     g->recoverypid = r;
706   }
707
708   if (!g->direct) {
709     /* Close the other ends of the pipe. */
710     close (wfd[0]);
711     close (rfd[1]);
712
713     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
714         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
715       perrorf (g, "fcntl");
716       goto cleanup1;
717     }
718
719     g->fd[0] = wfd[1];          /* stdin of child */
720     g->fd[1] = rfd[0];          /* stdout of child */
721   } else {
722     g->fd[0] = open ("/dev/null", O_RDWR);
723     if (g->fd[0] == -1) {
724       perrorf (g, "open /dev/null");
725       goto cleanup1;
726     }
727     g->fd[1] = dup (g->fd[0]);
728     if (g->fd[1] == -1) {
729       perrorf (g, "dup");
730       close (g->fd[0]);
731       goto cleanup1;
732     }
733   }
734
735   if (null_vmchannel_sock) {
736     int sock = -1;
737     uid_t uid;
738
739     /* Null vmchannel implementation: We listen on g->sock for a
740      * connection.  The connection could come from any local process
741      * so we must check it comes from the appliance (or at least
742      * from our UID) for security reasons.
743      */
744     while (sock == -1) {
745       sock = guestfs___accept_from_daemon (g);
746       if (sock == -1)
747         goto cleanup1;
748
749       if (check_peer_euid (g, sock, &uid) == -1)
750         goto cleanup1;
751       if (uid != geteuid ()) {
752         fprintf (stderr,
753                  "libguestfs: warning: unexpected connection from UID %d to port %d\n",
754                  uid, null_vmchannel_sock);
755         close (sock);
756         sock = -1;
757         continue;
758       }
759     }
760
761     if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
762       perrorf (g, "fcntl");
763       goto cleanup1;
764     }
765
766     close (g->sock);
767     g->sock = sock;
768   } else {
769     /* Other vmchannel.  Open the Unix socket.
770      *
771      * The vmchannel implementation that got merged with qemu sucks in
772      * a number of ways.  Both ends do connect(2), which means that no
773      * one knows what, if anything, is connected to the other end, or
774      * if it becomes disconnected.  Even worse, we have to wait some
775      * indeterminate time for qemu to create the socket and connect to
776      * it (which happens very early in qemu's start-up), so any code
777      * that uses vmchannel is inherently racy.  Hence this silly loop.
778      */
779     g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
780     if (g->sock == -1) {
781       perrorf (g, "socket");
782       goto cleanup1;
783     }
784
785     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
786       perrorf (g, "fcntl");
787       goto cleanup1;
788     }
789
790     addr.sun_family = AF_UNIX;
791     strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
792     addr.sun_path[UNIX_PATH_MAX-1] = '\0';
793
794     tries = 100;
795     /* Always sleep at least once to give qemu a small chance to start up. */
796     usleep (10000);
797     while (tries > 0) {
798       r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
799       if ((r == -1 && errno == EINPROGRESS) || r == 0)
800         goto connected;
801
802       if (errno != ENOENT)
803         perrorf (g, "connect");
804       tries--;
805       usleep (100000);
806     }
807
808     error (g, _("failed to connect to vmchannel socket"));
809     goto cleanup1;
810
811   connected: ;
812   }
813
814   g->state = LAUNCHING;
815
816   /* Wait for qemu to start and to connect back to us via vmchannel and
817    * send the GUESTFS_LAUNCH_FLAG message.
818    */
819   uint32_t size;
820   void *buf = NULL;
821   r = guestfs___recv_from_daemon (g, &size, &buf);
822   free (buf);
823
824   if (r == -1) return -1;
825
826   if (size != GUESTFS_LAUNCH_FLAG) {
827     error (g, _("guestfs_launch failed, see earlier error messages"));
828     goto cleanup1;
829   }
830
831   if (g->verbose)
832     guestfs___print_timestamped_message (g, "appliance is up");
833
834   /* This is possible in some really strange situations, such as
835    * guestfsd starts up OK but then qemu immediately exits.  Check for
836    * it because the caller is probably expecting to be able to send
837    * commands after this function returns.
838    */
839   if (g->state != READY) {
840     error (g, _("qemu launched and contacted daemon, but state != READY"));
841     goto cleanup1;
842   }
843
844   return 0;
845
846  cleanup1:
847   if (!g->direct) {
848     close (wfd[1]);
849     close (rfd[0]);
850   }
851   if (g->pid > 0) kill (g->pid, 9);
852   if (g->recoverypid > 0) kill (g->recoverypid, 9);
853   waitpid (g->pid, NULL, 0);
854   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
855   g->fd[0] = -1;
856   g->fd[1] = -1;
857   g->pid = 0;
858   g->recoverypid = 0;
859   memset (&g->launch_t, 0, sizeof g->launch_t);
860
861  cleanup0:
862   if (g->sock >= 0) {
863     close (g->sock);
864     g->sock = -1;
865   }
866   g->state = CONFIG;
867   free (kernel);
868   free (initrd);
869   return -1;
870 }
871
872 const char *
873 guestfs___tmpdir (void)
874 {
875   const char *tmpdir;
876
877 #ifdef P_tmpdir
878   tmpdir = P_tmpdir;
879 #else
880   tmpdir = "/tmp";
881 #endif
882
883   const char *t = getenv ("TMPDIR");
884   if (t) tmpdir = t;
885
886   return tmpdir;
887 }
888
889 /* This function is used to print the qemu command line before it gets
890  * executed, when in verbose mode.
891  */
892 static void
893 print_cmdline (guestfs_h *g)
894 {
895   int i = 0;
896   int needs_quote;
897
898   while (g->cmdline[i]) {
899     if (g->cmdline[i][0] == '-') /* -option starts a new line */
900       fprintf (stderr, " \\\n   ");
901
902     if (i > 0) fputc (' ', stderr);
903
904     /* Does it need shell quoting?  This only deals with simple cases. */
905     needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
906
907     if (needs_quote) fputc ('\'', stderr);
908     fprintf (stderr, "%s", g->cmdline[i]);
909     if (needs_quote) fputc ('\'', stderr);
910     i++;
911   }
912
913   fputc ('\n', stderr);
914 }
915
916 /* This function does the hard work of building the supermin appliance
917  * on the fly.  'path' is the directory containing the control files.
918  * 'kernel' and 'initrd' are where we will return the names of the
919  * kernel and initrd (only initrd is built).  The work is done by
920  * an external script.  We just tell it where to put the result.
921  */
922 static int
923 build_supermin_appliance (guestfs_h *g, const char *path,
924                           char **kernel, char **initrd)
925 {
926   char cmd[4096];
927   int r, len;
928
929   if (g->verbose)
930     print_timestamped_message (g, "begin building supermin appliance");
931
932   len = strlen (g->tmpdir);
933   *kernel = safe_malloc (g, len + 8);
934   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
935   *initrd = safe_malloc (g, len + 8);
936   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
937
938   /* Set a sensible umask in the subprocess, so kernel and initrd
939    * output files are world-readable (RHBZ#610880).
940    */
941   snprintf (cmd, sizeof cmd,
942             "umask 0002; "
943             "febootstrap-supermin-helper%s "
944             "-k '%s/kmod.whitelist' "
945             "'%s/supermin.d' "
946             host_cpu " "
947             "%s %s",
948             g->verbose ? " --verbose" : "",
949             path,
950             path,
951             *kernel, *initrd);
952   if (g->verbose)
953     print_timestamped_message (g, "%s", cmd);
954
955   r = system (cmd);
956   if (r == -1 || WEXITSTATUS(r) != 0) {
957     error (g, _("external command failed: %s"), cmd);
958     free (*kernel);
959     free (*initrd);
960     *kernel = *initrd = NULL;
961     return -1;
962   }
963
964   if (g->verbose)
965     print_timestamped_message (g, "finished building supermin appliance");
966
967   return 0;
968 }
969
970 /* Compute Y - X and return the result in milliseconds.
971  * Approximately the same as this code:
972  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
973  */
974 static int64_t
975 timeval_diff (const struct timeval *x, const struct timeval *y)
976 {
977   int64_t msec;
978
979   msec = (y->tv_sec - x->tv_sec) * 1000;
980   msec += (y->tv_usec - x->tv_usec) / 1000;
981   return msec;
982 }
983
984 void
985 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
986 {
987   va_list args;
988   char *msg;
989   int err;
990   struct timeval tv;
991
992   va_start (args, fs);
993   err = vasprintf (&msg, fs, args);
994   va_end (args);
995
996   if (err < 0) return;
997
998   gettimeofday (&tv, NULL);
999
1000   fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1001            timeval_diff (&g->launch_t, &tv), msg);
1002
1003   free (msg);
1004 }
1005
1006 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1007
1008 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1009  * 'qemu -version' so we know what options this qemu supports and
1010  * the version.
1011  */
1012 static int
1013 test_qemu (guestfs_h *g)
1014 {
1015   char cmd[1024];
1016   FILE *fp;
1017
1018   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1019
1020   fp = popen (cmd, "r");
1021   /* qemu -help should always work (qemu -version OTOH wasn't
1022    * supported by qemu 0.9).  If this command doesn't work then it
1023    * probably indicates that the qemu binary is missing.
1024    */
1025   if (!fp) {
1026     /* XXX This error is never printed, even if the qemu binary
1027      * doesn't exist.  Why?
1028      */
1029   error:
1030     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1031     return -1;
1032   }
1033
1034   if (read_all (g, fp, &g->qemu_help) == -1)
1035     goto error;
1036
1037   if (pclose (fp) == -1)
1038     goto error;
1039
1040   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1041             g->qemu);
1042
1043   fp = popen (cmd, "r");
1044   if (fp) {
1045     /* Intentionally ignore errors. */
1046     read_all (g, fp, &g->qemu_version);
1047     pclose (fp);
1048   }
1049
1050   return 0;
1051 }
1052
1053 static int
1054 read_all (guestfs_h *g, FILE *fp, char **ret)
1055 {
1056   int r, n = 0;
1057   char *p;
1058
1059  again:
1060   if (feof (fp)) {
1061     *ret = safe_realloc (g, *ret, n + 1);
1062     (*ret)[n] = '\0';
1063     return n;
1064   }
1065
1066   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1067   p = &(*ret)[n];
1068   r = fread (p, 1, BUFSIZ, fp);
1069   if (ferror (fp)) {
1070     perrorf (g, "read");
1071     return -1;
1072   }
1073   n += r;
1074   goto again;
1075 }
1076
1077 /* Test if option is supported by qemu command line (just by grepping
1078  * the help text).
1079  *
1080  * The first time this is used, it has to run the external qemu
1081  * binary.  If that fails, it returns -1.
1082  *
1083  * To just do the first-time run of the qemu binary, call this with
1084  * option == NULL, in which case it will return -1 if there was an
1085  * error doing that.
1086  */
1087 static int
1088 qemu_supports (guestfs_h *g, const char *option)
1089 {
1090   if (!g->qemu_help) {
1091     if (test_qemu (g) == -1)
1092       return -1;
1093   }
1094
1095   if (option == NULL)
1096     return 1;
1097
1098   return strstr (g->qemu_help, option) != NULL;
1099 }
1100
1101 /* Check if a file can be opened. */
1102 static int
1103 is_openable (guestfs_h *g, const char *path, int flags)
1104 {
1105   int fd = open (path, flags);
1106   if (fd == -1) {
1107     if (g->verbose)
1108       perror (path);
1109     return 0;
1110   }
1111   close (fd);
1112   return 1;
1113 }
1114
1115 /* Check the peer effective UID for a TCP socket.  Ideally we'd like
1116  * SO_PEERCRED for a loopback TCP socket.  This isn't possible on
1117  * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1118  */
1119 static int
1120 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1121 {
1122 #if CAN_CHECK_PEER_EUID
1123   struct sockaddr_in peer;
1124   socklen_t addrlen = sizeof peer;
1125
1126   if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1127     perrorf (g, "getpeername");
1128     return -1;
1129   }
1130
1131   if (peer.sin_family != AF_INET ||
1132       ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1133     error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1134            peer.sin_family, inet_ntoa (peer.sin_addr));
1135     return -1;
1136   }
1137
1138   struct sockaddr_in our;
1139   addrlen = sizeof our;
1140   if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1141     perrorf (g, "getsockname");
1142     return -1;
1143   }
1144
1145   FILE *fp = fopen ("/proc/net/tcp", "r");
1146   if (fp == NULL) {
1147     perrorf (g, "/proc/net/tcp");
1148     return -1;
1149   }
1150
1151   char line[256];
1152   if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1153     error (g, "unexpected end of file in /proc/net/tcp");
1154     fclose (fp);
1155     return -1;
1156   }
1157
1158   while (fgets (line, sizeof line, fp) != NULL) {
1159     unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1160     int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1161     int line_uid;
1162
1163     if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1164                 &dummy0,
1165                 &line_our_addr, &line_our_port,
1166                 &line_peer_addr, &line_peer_port,
1167                 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1168                 &line_uid) == 12) {
1169       /* Note about /proc/net/tcp: local_address and rem_address are
1170        * always in network byte order.  However the port part is
1171        * always in host byte order.
1172        *
1173        * The sockname and peername that we got above are in network
1174        * byte order.  So we have to byte swap the port but not the
1175        * address part.
1176        */
1177       if (line_our_addr == our.sin_addr.s_addr &&
1178           line_our_port == ntohs (our.sin_port) &&
1179           line_peer_addr == peer.sin_addr.s_addr &&
1180           line_peer_port == ntohs (peer.sin_port)) {
1181         *rtn = line_uid;
1182         fclose (fp);
1183         return 0;
1184       }
1185     }
1186   }
1187
1188   error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1189   fclose (fp);
1190   return -1;
1191 #else /* !CAN_CHECK_PEER_EUID */
1192   /* This function exists but should never be called in this
1193    * configuration.
1194    */
1195   abort ();
1196 #endif /* !CAN_CHECK_PEER_EUID */
1197 }
1198
1199 /* You had to call this function after launch in versions <= 1.0.70,
1200  * but it is now a no-op.
1201  */
1202 int
1203 guestfs__wait_ready (guestfs_h *g)
1204 {
1205   if (g->state != READY)  {
1206     error (g, _("qemu has not been launched yet"));
1207     return -1;
1208   }
1209
1210   return 0;
1211 }
1212
1213 int
1214 guestfs__kill_subprocess (guestfs_h *g)
1215 {
1216   if (g->state == CONFIG) {
1217     error (g, _("no subprocess to kill"));
1218     return -1;
1219   }
1220
1221   if (g->verbose)
1222     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1223
1224   if (g->pid > 0) kill (g->pid, SIGTERM);
1225   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1226
1227   return 0;
1228 }
1229
1230 /* Access current state. */
1231 int
1232 guestfs__is_config (guestfs_h *g)
1233 {
1234   return g->state == CONFIG;
1235 }
1236
1237 int
1238 guestfs__is_launching (guestfs_h *g)
1239 {
1240   return g->state == LAUNCHING;
1241 }
1242
1243 int
1244 guestfs__is_ready (guestfs_h *g)
1245 {
1246   return g->state == READY;
1247 }
1248
1249 int
1250 guestfs__is_busy (guestfs_h *g)
1251 {
1252   return g->state == BUSY;
1253 }
1254
1255 int
1256 guestfs__get_state (guestfs_h *g)
1257 {
1258   return g->state;
1259 }