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