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