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