775f7a68a2ae69561a4411d9613e5fcfbf953746
[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 #include <assert.h>
38
39 #include <rpc/types.h>
40 #include <rpc/xdr.h>
41
42 #ifdef HAVE_ERRNO_H
43 #include <errno.h>
44 #endif
45
46 #ifdef HAVE_SYS_TYPES_H
47 #include <sys/types.h>
48 #endif
49
50 #ifdef HAVE_SYS_WAIT_H
51 #include <sys/wait.h>
52 #endif
53
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57
58 #ifdef HAVE_SYS_UN_H
59 #include <sys/un.h>
60 #endif
61
62 #include <arpa/inet.h>
63 #include <netinet/in.h>
64
65 #include "c-ctype.h"
66 #include "glthread/lock.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 launch_appliance (guestfs_h *g);
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___checkpoint_cmdline (guestfs_h *g)
107 {
108   return g->cmdline_size;
109 }
110
111 void
112 guestfs___rollback_cmdline (guestfs_h *g, int pos)
113 {
114   int i;
115
116   assert (g->cmdline_size >= pos);
117
118   for (i = g->cmdline_size - 1; i >= pos; --i)
119     free (g->cmdline[i]);
120
121   g->cmdline_size = pos;
122 }
123
124 /* Internal command to return the command line. */
125 char **
126 guestfs__debug_cmdline (guestfs_h *g)
127 {
128   int i;
129   char **r;
130
131   if (g->cmdline == NULL) {
132     r = safe_malloc (g, sizeof (char *) * 1);
133     r[0] = NULL;
134     return r;
135   }
136
137   r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
138   r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
139
140   for (i = 1; i < g->cmdline_size; ++i)
141     r[i] = safe_strdup (g, g->cmdline[i]);
142
143   r[g->cmdline_size] = NULL;
144
145   return r;                     /* caller frees */
146 }
147
148 int
149 guestfs__config (guestfs_h *g,
150                  const char *qemu_param, const char *qemu_value)
151 {
152   if (qemu_param[0] != '-') {
153     error (g, _("guestfs_config: parameter must begin with '-' character"));
154     return -1;
155   }
156
157   /* A bit fascist, but the user will probably break the extra
158    * parameters that we add if they try to set any of these.
159    */
160   if (STREQ (qemu_param, "-kernel") ||
161       STREQ (qemu_param, "-initrd") ||
162       STREQ (qemu_param, "-nographic") ||
163       STREQ (qemu_param, "-serial") ||
164       STREQ (qemu_param, "-full-screen") ||
165       STREQ (qemu_param, "-std-vga") ||
166       STREQ (qemu_param, "-vnc")) {
167     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
168     return -1;
169   }
170
171   if (add_cmdline (g, qemu_param) != 0) return -1;
172
173   if (qemu_value != NULL) {
174     if (add_cmdline (g, qemu_value) != 0) return -1;
175   }
176
177   return 0;
178 }
179
180 /* cache=off improves reliability in the event of a host crash.
181  *
182  * However this option causes qemu to try to open the file with
183  * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
184  * So we check if we can open the file with or without O_DIRECT,
185  * and use cache=off (or not) accordingly.
186  */
187 static int
188 test_cache_off (guestfs_h *g, const char *filename)
189 {
190   int fd = open (filename, O_RDONLY|O_DIRECT);
191   if (fd >= 0) {
192     close (fd);
193     return 1;
194   }
195
196   fd = open (filename, O_RDONLY);
197   if (fd >= 0) {
198     close (fd);
199     return 0;
200   }
201
202   perrorf (g, "%s", filename);
203   return -1;
204 }
205
206 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
207 static int
208 valid_format_iface (const char *str)
209 {
210   size_t len = strlen (str);
211
212   if (len == 0)
213     return 0;
214
215   while (len > 0) {
216     char c = *str++;
217     len--;
218     if (c != '-' && c != '_' && !c_isalnum (c))
219       return 0;
220   }
221   return 1;
222 }
223
224 int
225 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
226                          const struct guestfs_add_drive_opts_argv *optargs)
227 {
228   int readonly;
229   const char *format;
230   const char *iface;
231
232   if (strchr (filename, ',') != NULL) {
233     error (g, _("filename cannot contain ',' (comma) character"));
234     return -1;
235   }
236
237   readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
238              ? optargs->readonly : 0;
239   format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
240            ? optargs->format : NULL;
241   iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
242           ? optargs->iface : DRIVE_IF;
243
244   if (format && !valid_format_iface (format)) {
245     error (g, _("%s parameter is empty or contains disallowed characters"),
246            "format");
247     return -1;
248   }
249   if (!valid_format_iface (iface)) {
250     error (g, _("%s parameter is empty or contains disallowed characters"),
251            "iface");
252     return -1;
253   }
254
255   /* For writable files, see if we can use cache=off.  This also
256    * checks for the existence of the file.  For readonly we have
257    * to do the check explicitly.
258    */
259   int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
260   if (use_cache_off == -1)
261     return -1;
262
263   if (readonly) {
264     if (access (filename, F_OK) == -1) {
265       perrorf (g, "%s", filename);
266       return -1;
267     }
268   }
269
270   /* Construct the final -drive parameter. */
271   size_t len = 64 + strlen (filename) + strlen (iface);
272   if (format) len += strlen (format);
273   char buf[len];
274
275   snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
276             filename,
277             readonly ? ",snapshot=on" : "",
278             use_cache_off ? ",cache=off" : "",
279             format ? ",format=" : "",
280             format ? format : "",
281             iface);
282
283   return guestfs__config (g, "-drive", buf);
284 }
285
286 int
287 guestfs__add_drive (guestfs_h *g, const char *filename)
288 {
289   struct guestfs_add_drive_opts_argv optargs = {
290     .bitmask = 0,
291   };
292
293   return guestfs__add_drive_opts (g, filename, &optargs);
294 }
295
296 int
297 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
298 {
299   struct guestfs_add_drive_opts_argv optargs = {
300     .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
301     .readonly = 1,
302   };
303
304   return guestfs__add_drive_opts (g, filename, &optargs);
305 }
306
307 int
308 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
309                             const char *iface)
310 {
311   struct guestfs_add_drive_opts_argv optargs = {
312     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
313     .iface = iface,
314   };
315
316   return guestfs__add_drive_opts (g, filename, &optargs);
317 }
318
319 int
320 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
321                                const char *iface)
322 {
323   struct guestfs_add_drive_opts_argv optargs = {
324     .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
325              | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
326     .iface = iface,
327     .readonly = 1,
328   };
329
330   return guestfs__add_drive_opts (g, filename, &optargs);
331 }
332
333 int
334 guestfs__add_cdrom (guestfs_h *g, const char *filename)
335 {
336   if (strchr (filename, ',') != NULL) {
337     error (g, _("filename cannot contain ',' (comma) character"));
338     return -1;
339   }
340
341   if (access (filename, F_OK) == -1) {
342     perrorf (g, "%s", filename);
343     return -1;
344   }
345
346   return guestfs__config (g, "-cdrom", filename);
347 }
348
349 static int is_openable (guestfs_h *g, const char *path, int flags);
350
351 int
352 guestfs__launch (guestfs_h *g)
353 {
354   /* Configured? */
355   if (g->state != CONFIG) {
356     error (g, _("the libguestfs handle has already been launched"));
357     return -1;
358   }
359
360   /* Make the temporary directory. */
361   if (!g->tmpdir) {
362     TMP_TEMPLATE_ON_STACK (dir_template);
363     g->tmpdir = safe_strdup (g, dir_template);
364     if (mkdtemp (g->tmpdir) == NULL) {
365       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
366       return -1;
367     }
368   }
369
370   /* Allow anyone to read the temporary directory.  The socket in this
371    * directory won't be readable but anyone can see it exists if they
372    * want. (RHBZ#610880).
373    */
374   if (chmod (g->tmpdir, 0755) == -1)
375     fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
376
377   return launch_appliance (g);
378 }
379
380 static int
381 launch_appliance (guestfs_h *g)
382 {
383   int r;
384   int wfd[2], rfd[2];
385   char unixsock[256];
386   struct sockaddr_un addr;
387
388   /* At present you must add drives before starting the appliance.  In
389    * future when we enable hotplugging you won't need to do this.
390    */
391   if (!g->cmdline) {
392     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
393     return -1;
394   }
395
396   /* Start the clock ... */
397   gettimeofday (&g->launch_t, NULL);
398
399   /* Locate and/or build the appliance. */
400   char *kernel = NULL, *initrd = NULL, *appliance = NULL;
401   if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
402     return -1;
403
404   if (g->verbose)
405     guestfs___print_timestamped_message (g, "begin testing qemu features");
406
407   /* Get qemu help text and version. */
408   if (qemu_supports (g, NULL) == -1)
409     goto cleanup0;
410
411   /* Using virtio-serial, we need to create a local Unix domain socket
412    * for qemu to connect to.
413    */
414   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
415   unlink (unixsock);
416
417   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
418   if (g->sock == -1) {
419     perrorf (g, "socket");
420     goto cleanup0;
421   }
422
423   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
424     perrorf (g, "fcntl");
425     goto cleanup0;
426   }
427
428   addr.sun_family = AF_UNIX;
429   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
430   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
431
432   if (bind (g->sock, &addr, sizeof addr) == -1) {
433     perrorf (g, "bind");
434     goto cleanup0;
435   }
436
437   if (listen (g->sock, 1) == -1) {
438     perrorf (g, "listen");
439     goto cleanup0;
440   }
441
442   if (!g->direct) {
443     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
444       perrorf (g, "pipe");
445       goto cleanup0;
446     }
447   }
448
449   if (g->verbose)
450     guestfs___print_timestamped_message (g, "finished testing qemu features");
451
452   r = fork ();
453   if (r == -1) {
454     perrorf (g, "fork");
455     if (!g->direct) {
456       close (wfd[0]);
457       close (wfd[1]);
458       close (rfd[0]);
459       close (rfd[1]);
460     }
461     goto cleanup0;
462   }
463
464   if (r == 0) {                 /* Child (qemu). */
465     char buf[256];
466
467     /* Set up the full command line.  Do this in the subprocess so we
468      * don't need to worry about cleaning up.
469      */
470     g->cmdline[0] = g->qemu;
471
472     if (qemu_supports (g, "-nodefconfig"))
473       add_cmdline (g, "-nodefconfig");
474
475     /* qemu sometimes needs this option to enable hardware
476      * virtualization, but some versions of 'qemu-kvm' will use KVM
477      * regardless (even where this option appears in the help text).
478      * It is rumoured that there are versions of qemu where supplying
479      * this option when hardware virtualization is not available will
480      * cause qemu to fail, so we we have to check at least that
481      * /dev/kvm is openable.  That's not reliable, since /dev/kvm
482      * might be openable by qemu but not by us (think: SELinux) in
483      * which case the user would not get hardware virtualization,
484      * although at least shouldn't fail.  A giant clusterfuck with the
485      * qemu command line, again.
486      */
487     if (qemu_supports (g, "-enable-kvm") &&
488         is_openable (g, "/dev/kvm", O_RDWR))
489       add_cmdline (g, "-enable-kvm");
490
491     /* Newer versions of qemu (from around 2009/12) changed the
492      * behaviour of monitors so that an implicit '-monitor stdio' is
493      * assumed if we are in -nographic mode and there is no other
494      * -monitor option.  Only a single stdio device is allowed, so
495      * this broke the '-serial stdio' option.  There is a new flag
496      * called -nodefaults which gets rid of all this default crud, so
497      * let's use that to avoid this and any future surprises.
498      */
499     if (qemu_supports (g, "-nodefaults"))
500       add_cmdline (g, "-nodefaults");
501
502     add_cmdline (g, "-nographic");
503
504     snprintf (buf, sizeof buf, "%d", g->memsize);
505     add_cmdline (g, "-m");
506     add_cmdline (g, buf);
507
508     /* Force exit instead of reboot on panic */
509     add_cmdline (g, "-no-reboot");
510
511     /* These options recommended by KVM developers to improve reliability. */
512     if (qemu_supports (g, "-no-hpet"))
513       add_cmdline (g, "-no-hpet");
514
515     if (qemu_supports (g, "-rtc-td-hack"))
516       add_cmdline (g, "-rtc-td-hack");
517
518     /* Create the virtio serial bus. */
519     add_cmdline (g, "-device");
520     add_cmdline (g, "virtio-serial");
521
522 #if 0
523     /* Use virtio-console (a variant form of virtio-serial) for the
524      * guest's serial console.
525      */
526     add_cmdline (g, "-chardev");
527     add_cmdline (g, "stdio,id=console");
528     add_cmdline (g, "-device");
529     add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
530 #else
531     /* When the above works ...  until then: */
532     add_cmdline (g, "-serial");
533     add_cmdline (g, "stdio");
534 #endif
535
536     /* Set up virtio-serial for the communications channel. */
537     add_cmdline (g, "-chardev");
538     snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
539     add_cmdline (g, buf);
540     add_cmdline (g, "-device");
541     add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
542
543     /* Enable user networking. */
544     if (g->enable_network) {
545       add_cmdline (g, "-netdev");
546       add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
547       add_cmdline (g, "-device");
548       add_cmdline (g, NET_IF ",netdev=usernet");
549     }
550
551 #define LINUX_CMDLINE                                                   \
552     "panic=1 "         /* force kernel to panic if daemon exits */      \
553     "console=ttyS0 "   /* serial console */                             \
554     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
555     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
556     "acpi=off "        /* we don't need ACPI, turn it off */            \
557     "printk.time=1 "   /* display timestamp before kernel messages */   \
558     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
559
560     /* Linux kernel command line. */
561     snprintf (buf, sizeof buf,
562               LINUX_CMDLINE
563               "%s "             /* (selinux) */
564               "%s "             /* (verbose) */
565               "TERM=%s "        /* (TERM environment variable) */
566               "%s",             /* (append) */
567               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
568               g->verbose ? "guestfs_verbose=1" : "",
569               getenv ("TERM") ? : "linux",
570               g->append ? g->append : "");
571
572     add_cmdline (g, "-kernel");
573     add_cmdline (g, kernel);
574     add_cmdline (g, "-initrd");
575     add_cmdline (g, initrd);
576     add_cmdline (g, "-append");
577     add_cmdline (g, buf);
578
579     /* Add the ext2 appliance drive (last of all). */
580     if (appliance) {
581       const char *cachemode = "";
582       if (qemu_supports (g, "cache=")) {
583         if (qemu_supports (g, "unsafe"))
584           cachemode = ",cache=unsafe";
585         else if (qemu_supports (g, "writeback"))
586           cachemode = ",cache=writeback";
587       }
588
589       char buf2[PATH_MAX + 64];
590       add_cmdline (g, "-drive");
591       snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
592                 appliance, cachemode);
593       add_cmdline (g, buf2);
594     }
595
596     /* Finish off the command line. */
597     incr_cmdline_size (g);
598     g->cmdline[g->cmdline_size-1] = NULL;
599
600     if (g->verbose)
601       guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
602
603     if (!g->direct) {
604       /* Set up stdin, stdout. */
605       close (0);
606       close (1);
607       close (wfd[1]);
608       close (rfd[0]);
609
610       if (dup (wfd[0]) == -1) {
611       dup_failed:
612         perror ("dup failed");
613         _exit (EXIT_FAILURE);
614       }
615       if (dup (rfd[1]) == -1)
616         goto dup_failed;
617
618       close (wfd[0]);
619       close (rfd[1]);
620     }
621
622 #if 0
623     /* Set up a new process group, so we can signal this process
624      * and all subprocesses (eg. if qemu is really a shell script).
625      */
626     setpgid (0, 0);
627 #endif
628
629     setenv ("LC_ALL", "C", 1);
630
631     execv (g->qemu, g->cmdline); /* Run qemu. */
632     perror (g->qemu);
633     _exit (EXIT_FAILURE);
634   }
635
636   /* Parent (library). */
637   g->pid = r;
638
639   free (kernel);
640   kernel = NULL;
641   free (initrd);
642   initrd = NULL;
643   free (appliance);
644   appliance = NULL;
645
646   /* Fork the recovery process off which will kill qemu if the parent
647    * process fails to do so (eg. if the parent segfaults).
648    */
649   g->recoverypid = -1;
650   if (g->recovery_proc) {
651     r = fork ();
652     if (r == 0) {
653       pid_t qemu_pid = g->pid;
654       pid_t parent_pid = getppid ();
655
656       /* Writing to argv is hideously complicated and error prone.  See:
657        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
658        */
659
660       /* Loop around waiting for one or both of the other processes to
661        * disappear.  It's fair to say this is very hairy.  The PIDs that
662        * we are looking at might be reused by another process.  We are
663        * effectively polling.  Is the cure worse than the disease?
664        */
665       for (;;) {
666         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
667           _exit (EXIT_SUCCESS);
668         if (kill (parent_pid, 0) == -1) {
669           /* Parent's gone away, qemu still around, so kill qemu. */
670           kill (qemu_pid, 9);
671           _exit (EXIT_SUCCESS);
672         }
673         sleep (2);
674       }
675     }
676
677     /* Don't worry, if the fork failed, this will be -1.  The recovery
678      * process isn't essential.
679      */
680     g->recoverypid = r;
681   }
682
683   if (!g->direct) {
684     /* Close the other ends of the pipe. */
685     close (wfd[0]);
686     close (rfd[1]);
687
688     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
689         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
690       perrorf (g, "fcntl");
691       goto cleanup1;
692     }
693
694     g->fd[0] = wfd[1];          /* stdin of child */
695     g->fd[1] = rfd[0];          /* stdout of child */
696   } else {
697     g->fd[0] = open ("/dev/null", O_RDWR);
698     if (g->fd[0] == -1) {
699       perrorf (g, "open /dev/null");
700       goto cleanup1;
701     }
702     g->fd[1] = dup (g->fd[0]);
703     if (g->fd[1] == -1) {
704       perrorf (g, "dup");
705       close (g->fd[0]);
706       goto cleanup1;
707     }
708   }
709
710   g->state = LAUNCHING;
711
712   /* Wait for qemu to start and to connect back to us via
713    * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
714    */
715   r = guestfs___accept_from_daemon (g);
716   if (r == -1)
717     goto cleanup1;
718
719   close (g->sock); /* Close the listening socket. */
720   g->sock = r; /* This is the accepted data socket. */
721
722   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
723     perrorf (g, "fcntl");
724     goto cleanup1;
725   }
726
727   uint32_t size;
728   void *buf = NULL;
729   r = guestfs___recv_from_daemon (g, &size, &buf);
730   free (buf);
731
732   if (r == -1) return -1;
733
734   if (size != GUESTFS_LAUNCH_FLAG) {
735     error (g, _("guestfs_launch failed, see earlier error messages"));
736     goto cleanup1;
737   }
738
739   if (g->verbose)
740     guestfs___print_timestamped_message (g, "appliance is up");
741
742   /* This is possible in some really strange situations, such as
743    * guestfsd starts up OK but then qemu immediately exits.  Check for
744    * it because the caller is probably expecting to be able to send
745    * commands after this function returns.
746    */
747   if (g->state != READY) {
748     error (g, _("qemu launched and contacted daemon, but state != READY"));
749     goto cleanup1;
750   }
751
752   return 0;
753
754  cleanup1:
755   if (!g->direct) {
756     close (wfd[1]);
757     close (rfd[0]);
758   }
759   if (g->pid > 0) kill (g->pid, 9);
760   if (g->recoverypid > 0) kill (g->recoverypid, 9);
761   waitpid (g->pid, NULL, 0);
762   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
763   g->fd[0] = -1;
764   g->fd[1] = -1;
765   g->pid = 0;
766   g->recoverypid = 0;
767   memset (&g->launch_t, 0, sizeof g->launch_t);
768
769  cleanup0:
770   if (g->sock >= 0) {
771     close (g->sock);
772     g->sock = -1;
773   }
774   g->state = CONFIG;
775   free (kernel);
776   free (initrd);
777   free (appliance);
778   return -1;
779 }
780
781 /* Return the location of the tmpdir (eg. "/tmp") and allow users
782  * to override it at runtime using $TMPDIR.
783  * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
784  */
785 const char *
786 guestfs_tmpdir (void)
787 {
788   const char *tmpdir;
789
790 #ifdef P_tmpdir
791   tmpdir = P_tmpdir;
792 #else
793   tmpdir = "/tmp";
794 #endif
795
796   const char *t = getenv ("TMPDIR");
797   if (t) tmpdir = t;
798
799   return tmpdir;
800 }
801
802 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
803  * allow users to override it at runtime using $TMPDIR.
804  * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
805  */
806 const char *
807 guestfs___persistent_tmpdir (void)
808 {
809   const char *tmpdir;
810
811   tmpdir = "/var/tmp";
812
813   const char *t = getenv ("TMPDIR");
814   if (t) tmpdir = t;
815
816   return tmpdir;
817 }
818
819 /* Compute Y - X and return the result in milliseconds.
820  * Approximately the same as this code:
821  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
822  */
823 static int64_t
824 timeval_diff (const struct timeval *x, const struct timeval *y)
825 {
826   int64_t msec;
827
828   msec = (y->tv_sec - x->tv_sec) * 1000;
829   msec += (y->tv_usec - x->tv_usec) / 1000;
830   return msec;
831 }
832
833 void
834 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
835 {
836   int i = 0;
837   int needs_quote;
838
839   struct timeval tv;
840   gettimeofday (&tv, NULL);
841   fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
842
843   while (argv[i]) {
844     if (argv[i][0] == '-') /* -option starts a new line */
845       fprintf (stderr, " \\\n   ");
846
847     if (i > 0) fputc (' ', stderr);
848
849     /* Does it need shell quoting?  This only deals with simple cases. */
850     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
851
852     if (needs_quote) fputc ('\'', stderr);
853     fprintf (stderr, "%s", argv[i]);
854     if (needs_quote) fputc ('\'', stderr);
855     i++;
856   }
857
858   fputc ('\n', stderr);
859 }
860
861 void
862 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
863 {
864   va_list args;
865   char *msg;
866   int err;
867   struct timeval tv;
868
869   va_start (args, fs);
870   err = vasprintf (&msg, fs, args);
871   va_end (args);
872
873   if (err < 0) return;
874
875   gettimeofday (&tv, NULL);
876
877   fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
878            timeval_diff (&g->launch_t, &tv), msg);
879
880   free (msg);
881 }
882
883 static int read_all (guestfs_h *g, FILE *fp, char **ret);
884
885 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
886  * 'qemu -version' so we know what options this qemu supports and
887  * the version.
888  */
889 static int
890 test_qemu (guestfs_h *g)
891 {
892   char cmd[1024];
893   FILE *fp;
894
895   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
896
897   fp = popen (cmd, "r");
898   /* qemu -help should always work (qemu -version OTOH wasn't
899    * supported by qemu 0.9).  If this command doesn't work then it
900    * probably indicates that the qemu binary is missing.
901    */
902   if (!fp) {
903     /* XXX This error is never printed, even if the qemu binary
904      * doesn't exist.  Why?
905      */
906   error:
907     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
908     return -1;
909   }
910
911   if (read_all (g, fp, &g->qemu_help) == -1)
912     goto error;
913
914   if (pclose (fp) == -1)
915     goto error;
916
917   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
918             g->qemu);
919
920   fp = popen (cmd, "r");
921   if (fp) {
922     /* Intentionally ignore errors. */
923     read_all (g, fp, &g->qemu_version);
924     pclose (fp);
925   }
926
927   return 0;
928 }
929
930 static int
931 read_all (guestfs_h *g, FILE *fp, char **ret)
932 {
933   int r, n = 0;
934   char *p;
935
936  again:
937   if (feof (fp)) {
938     *ret = safe_realloc (g, *ret, n + 1);
939     (*ret)[n] = '\0';
940     return n;
941   }
942
943   *ret = safe_realloc (g, *ret, n + BUFSIZ);
944   p = &(*ret)[n];
945   r = fread (p, 1, BUFSIZ, fp);
946   if (ferror (fp)) {
947     perrorf (g, "read");
948     return -1;
949   }
950   n += r;
951   goto again;
952 }
953
954 /* Test if option is supported by qemu command line (just by grepping
955  * the help text).
956  *
957  * The first time this is used, it has to run the external qemu
958  * binary.  If that fails, it returns -1.
959  *
960  * To just do the first-time run of the qemu binary, call this with
961  * option == NULL, in which case it will return -1 if there was an
962  * error doing that.
963  */
964 static int
965 qemu_supports (guestfs_h *g, const char *option)
966 {
967   if (!g->qemu_help) {
968     if (test_qemu (g) == -1)
969       return -1;
970   }
971
972   if (option == NULL)
973     return 1;
974
975   return strstr (g->qemu_help, option) != NULL;
976 }
977
978 /* Check if a file can be opened. */
979 static int
980 is_openable (guestfs_h *g, const char *path, int flags)
981 {
982   int fd = open (path, flags);
983   if (fd == -1) {
984     if (g->verbose)
985       perror (path);
986     return 0;
987   }
988   close (fd);
989   return 1;
990 }
991
992 /* You had to call this function after launch in versions <= 1.0.70,
993  * but it is now a no-op.
994  */
995 int
996 guestfs__wait_ready (guestfs_h *g)
997 {
998   if (g->state != READY)  {
999     error (g, _("qemu has not been launched yet"));
1000     return -1;
1001   }
1002
1003   return 0;
1004 }
1005
1006 int
1007 guestfs__kill_subprocess (guestfs_h *g)
1008 {
1009   if (g->state == CONFIG) {
1010     error (g, _("no subprocess to kill"));
1011     return -1;
1012   }
1013
1014   if (g->verbose)
1015     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1016
1017   if (g->pid > 0) kill (g->pid, SIGTERM);
1018   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1019
1020   return 0;
1021 }
1022
1023 /* Access current state. */
1024 int
1025 guestfs__is_config (guestfs_h *g)
1026 {
1027   return g->state == CONFIG;
1028 }
1029
1030 int
1031 guestfs__is_launching (guestfs_h *g)
1032 {
1033   return g->state == LAUNCHING;
1034 }
1035
1036 int
1037 guestfs__is_ready (guestfs_h *g)
1038 {
1039   return g->state == READY;
1040 }
1041
1042 int
1043 guestfs__is_busy (guestfs_h *g)
1044 {
1045   return g->state == BUSY;
1046 }
1047
1048 int
1049 guestfs__get_state (guestfs_h *g)
1050 {
1051   return g->state;
1052 }