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