hivex: Reimplement hivexget as a simple shell script.
[libguestfs.git] / src / guestfs.c
1 /* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #include <sys/select.h>
35 #include <dirent.h>
36
37 #include <rpc/types.h>
38 #include <rpc/xdr.h>
39
40 #ifdef HAVE_ERRNO_H
41 #include <errno.h>
42 #endif
43
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
46 #endif
47
48 #ifdef HAVE_SYS_WAIT_H
49 #include <sys/wait.h>
50 #endif
51
52 #ifdef HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
54 #endif
55
56 #ifdef HAVE_SYS_UN_H
57 #include <sys/un.h>
58 #endif
59
60 #include <arpa/inet.h>
61 #include <netinet/in.h>
62
63 #include "c-ctype.h"
64 #include "glthread/lock.h"
65 #include "ignore-value.h"
66
67 #include "guestfs.h"
68 #include "guestfs-internal.h"
69 #include "guestfs-internal-actions.h"
70 #include "guestfs_protocol.h"
71
72 #ifdef HAVE_GETTEXT
73 #include "gettext.h"
74 #define _(str) dgettext(PACKAGE, (str))
75 //#define N_(str) dgettext(PACKAGE, (str))
76 #else
77 #define _(str) str
78 //#define N_(str) str
79 #endif
80
81 #define error guestfs_error
82 #define perrorf guestfs_perrorf
83 #define safe_malloc guestfs_safe_malloc
84 #define safe_realloc guestfs_safe_realloc
85 #define safe_strdup guestfs_safe_strdup
86 //#define safe_memdup guestfs_safe_memdup
87
88 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
89 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
90 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
91 static int accept_from_daemon (guestfs_h *g);
92 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
93 static void close_handles (void);
94
95 #define UNIX_PATH_MAX 108
96
97 /* Also in guestfsd.c */
98 #define GUESTFWD_ADDR "10.0.2.4"
99 #define GUESTFWD_PORT "6666"
100
101 /* GuestFS handle and connection. */
102 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
103
104 struct guestfs_h
105 {
106   struct guestfs_h *next;       /* Linked list of open handles. */
107
108   /* State: see the state machine diagram in the man page guestfs(3). */
109   enum state state;
110
111   int fd[2];                    /* Stdin/stdout of qemu. */
112   int sock;                     /* Daemon communications socket. */
113   pid_t pid;                    /* Qemu PID. */
114   pid_t recoverypid;            /* Recovery process PID. */
115
116   struct timeval launch_t;      /* The time that we called guestfs_launch. */
117
118   char *tmpdir;                 /* Temporary directory containing socket. */
119
120   char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
121
122   char **cmdline;               /* Qemu command line. */
123   int cmdline_size;
124
125   int verbose;
126   int trace;
127   int autosync;
128   int direct;
129   int recovery_proc;
130
131   char *path;                   /* Path to kernel, initrd. */
132   char *qemu;                   /* Qemu binary. */
133   char *append;                 /* Append to kernel command line. */
134
135   int memsize;                  /* Size of RAM (megabytes). */
136
137   int selinux;                  /* selinux enabled? */
138
139   char *last_error;
140
141   /* Callbacks. */
142   guestfs_abort_cb           abort_cb;
143   guestfs_error_handler_cb   error_cb;
144   void *                     error_cb_data;
145   guestfs_log_message_cb     log_message_cb;
146   void *                     log_message_cb_data;
147   guestfs_subprocess_quit_cb subprocess_quit_cb;
148   void *                     subprocess_quit_cb_data;
149   guestfs_launch_done_cb     launch_done_cb;
150   void *                     launch_done_cb_data;
151
152   int msg_next_serial;
153 };
154
155 gl_lock_define_initialized (static, handles_lock);
156 static guestfs_h *handles = NULL;
157 static int atexit_handler_set = 0;
158
159 guestfs_h *
160 guestfs_create (void)
161 {
162   guestfs_h *g;
163   const char *str;
164
165   g = malloc (sizeof (*g));
166   if (!g) return NULL;
167
168   memset (g, 0, sizeof (*g));
169
170   g->state = CONFIG;
171
172   g->fd[0] = -1;
173   g->fd[1] = -1;
174   g->sock = -1;
175
176   g->abort_cb = abort;
177   g->error_cb = default_error_cb;
178   g->error_cb_data = NULL;
179
180   g->recovery_proc = 1;
181
182   str = getenv ("LIBGUESTFS_DEBUG");
183   g->verbose = str != NULL && STREQ (str, "1");
184
185   str = getenv ("LIBGUESTFS_TRACE");
186   g->trace = str != NULL && STREQ (str, "1");
187
188   str = getenv ("LIBGUESTFS_PATH");
189   g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
190   if (!g->path) goto error;
191
192   str = getenv ("LIBGUESTFS_QEMU");
193   g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
194   if (!g->qemu) goto error;
195
196   str = getenv ("LIBGUESTFS_APPEND");
197   if (str) {
198     g->append = strdup (str);
199     if (!g->append) goto error;
200   }
201
202   /* Choose a suitable memory size.  Previously we tried to choose
203    * a minimal memory size, but this isn't really necessary since
204    * recent QEMU and KVM don't do anything nasty like locking
205    * memory into core any more.  Thus we can safely choose a
206    * large, generous amount of memory, and it'll just get swapped
207    * on smaller systems.
208    */
209   str = getenv ("LIBGUESTFS_MEMSIZE");
210   if (str) {
211     if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
212       fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
213       goto error;
214     }
215   } else
216     g->memsize = 500;
217
218   /* Start with large serial numbers so they are easy to spot
219    * inside the protocol.
220    */
221   g->msg_next_serial = 0x00123400;
222
223   /* Link the handles onto a global list. */
224   gl_lock_lock (handles_lock);
225   g->next = handles;
226   handles = g;
227   if (!atexit_handler_set) {
228     atexit (close_handles);
229     atexit_handler_set = 1;
230   }
231   gl_lock_unlock (handles_lock);
232
233   if (g->verbose)
234     fprintf (stderr, "new guestfs handle %p\n", g);
235
236   return g;
237
238  error:
239   free (g->path);
240   free (g->qemu);
241   free (g->append);
242   free (g);
243   return NULL;
244 }
245
246 void
247 guestfs_close (guestfs_h *g)
248 {
249   int i;
250   char filename[256];
251   guestfs_h *gg;
252
253   if (g->state == NO_HANDLE) {
254     /* Not safe to call 'error' here, so ... */
255     fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
256     return;
257   }
258
259   if (g->verbose)
260     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
261
262   /* Try to sync if autosync flag is set. */
263   if (g->autosync && g->state == READY) {
264     guestfs_umount_all (g);
265     guestfs_sync (g);
266   }
267
268   /* Remove any handlers that might be called back before we kill the
269    * subprocess.
270    */
271   g->log_message_cb = NULL;
272
273   if (g->state != CONFIG)
274     guestfs_kill_subprocess (g);
275
276   /* Close sockets. */
277   if (g->fd[0] >= 0)
278     close (g->fd[0]);
279   if (g->fd[1] >= 0)
280     close (g->fd[1]);
281   if (g->sock >= 0)
282     close (g->sock);
283   g->fd[0] = -1;
284   g->fd[1] = -1;
285   g->sock = -1;
286
287   /* Wait for subprocess(es) to exit. */
288   waitpid (g->pid, NULL, 0);
289   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
290
291   /* Remove tmpfiles. */
292   if (g->tmpdir) {
293     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
294     unlink (filename);
295
296     snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
297     unlink (filename);
298
299     snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
300     unlink (filename);
301
302     rmdir (g->tmpdir);
303
304     free (g->tmpdir);
305   }
306
307   if (g->cmdline) {
308     for (i = 0; i < g->cmdline_size; ++i)
309       free (g->cmdline[i]);
310     free (g->cmdline);
311   }
312
313   /* Mark the handle as dead before freeing it. */
314   g->state = NO_HANDLE;
315
316   gl_lock_lock (handles_lock);
317   if (handles == g)
318     handles = g->next;
319   else {
320     for (gg = handles; gg->next != g; gg = gg->next)
321       ;
322     gg->next = g->next;
323   }
324   gl_lock_unlock (handles_lock);
325
326   free (g->last_error);
327   free (g->path);
328   free (g->qemu);
329   free (g->append);
330   free (g->qemu_help);
331   free (g->qemu_version);
332   free (g);
333 }
334
335 /* Close all open handles (called from atexit(3)). */
336 static void
337 close_handles (void)
338 {
339   while (handles) guestfs_close (handles);
340 }
341
342 const char *
343 guestfs_last_error (guestfs_h *g)
344 {
345   return g->last_error;
346 }
347
348 static void
349 set_last_error (guestfs_h *g, const char *msg)
350 {
351   free (g->last_error);
352   g->last_error = strdup (msg);
353 }
354
355 static void
356 default_error_cb (guestfs_h *g, void *data, const char *msg)
357 {
358   fprintf (stderr, _("libguestfs: error: %s\n"), msg);
359 }
360
361 void
362 guestfs_error (guestfs_h *g, const char *fs, ...)
363 {
364   va_list args;
365   char *msg;
366
367   va_start (args, fs);
368   int err = vasprintf (&msg, fs, args);
369   va_end (args);
370
371   if (err < 0) return;
372
373   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
374   set_last_error (g, msg);
375
376   free (msg);
377 }
378
379 void
380 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
381 {
382   va_list args;
383   char *msg;
384   int errnum = errno;
385
386   va_start (args, fs);
387   int err = vasprintf (&msg, fs, args);
388   va_end (args);
389
390   if (err < 0) return;
391
392 #ifndef _GNU_SOURCE
393   char buf[256];
394   strerror_r (errnum, buf, sizeof buf);
395 #else
396   char _buf[256];
397   char *buf;
398   buf = strerror_r (errnum, _buf, sizeof _buf);
399 #endif
400
401   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
402   strcat (msg, ": ");
403   strcat (msg, buf);
404
405   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
406   set_last_error (g, msg);
407
408   free (msg);
409 }
410
411 void *
412 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
413 {
414   void *ptr = malloc (nbytes);
415   if (nbytes > 0 && !ptr) g->abort_cb ();
416   return ptr;
417 }
418
419 /* Return 1 if an array of N objects, each of size S, cannot exist due
420    to size arithmetic overflow.  S must be positive and N must be
421    nonnegative.  This is a macro, not an inline function, so that it
422    works correctly even when SIZE_MAX < N.
423
424    By gnulib convention, SIZE_MAX represents overflow in size
425    calculations, so the conservative dividend to use here is
426    SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
427    However, malloc (SIZE_MAX) fails on all known hosts where
428    sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
429    exactly-SIZE_MAX allocations on such hosts; this avoids a test and
430    branch when S is known to be 1.  */
431 # define xalloc_oversized(n, s) \
432     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
433
434 /* Technically we should add an autoconf test for this, testing for the desired
435    functionality, like what's done in gnulib, but for now, this is fine.  */
436 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
437
438 /* Allocate zeroed memory for N elements of S bytes, with error
439    checking.  S must be nonzero.  */
440 void *
441 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
442 {
443   /* From gnulib's calloc function in xmalloc.c.  */
444   void *p;
445   /* Test for overflow, since some calloc implementations don't have
446      proper overflow checks.  But omit overflow and size-zero tests if
447      HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
448      returns NULL if successful.  */
449   if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
450       || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
451     g->abort_cb ();
452   return p;
453 }
454
455 void *
456 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
457 {
458   void *p = realloc (ptr, nbytes);
459   if (nbytes > 0 && !p) g->abort_cb ();
460   return p;
461 }
462
463 char *
464 guestfs_safe_strdup (guestfs_h *g, const char *str)
465 {
466   char *s = strdup (str);
467   if (!s) g->abort_cb ();
468   return s;
469 }
470
471 void *
472 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
473 {
474   void *p = malloc (size);
475   if (!p) g->abort_cb ();
476   memcpy (p, ptr, size);
477   return p;
478 }
479
480 static int
481 xwrite (int fd, const void *v_buf, size_t len)
482 {
483   const char *buf = v_buf;
484   int r;
485
486   while (len > 0) {
487     r = write (fd, buf, len);
488     if (r == -1)
489       return -1;
490
491     buf += r;
492     len -= r;
493   }
494
495   return 0;
496 }
497
498 void
499 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
500 {
501   g->abort_cb = cb;
502 }
503
504 guestfs_abort_cb
505 guestfs_get_out_of_memory_handler (guestfs_h *g)
506 {
507   return g->abort_cb;
508 }
509
510 void
511 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
512 {
513   g->error_cb = cb;
514   g->error_cb_data = data;
515 }
516
517 guestfs_error_handler_cb
518 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
519 {
520   if (data_rtn) *data_rtn = g->error_cb_data;
521   return g->error_cb;
522 }
523
524 int
525 guestfs__set_verbose (guestfs_h *g, int v)
526 {
527   g->verbose = !!v;
528   return 0;
529 }
530
531 int
532 guestfs__get_verbose (guestfs_h *g)
533 {
534   return g->verbose;
535 }
536
537 int
538 guestfs__set_autosync (guestfs_h *g, int a)
539 {
540   g->autosync = !!a;
541   return 0;
542 }
543
544 int
545 guestfs__get_autosync (guestfs_h *g)
546 {
547   return g->autosync;
548 }
549
550 int
551 guestfs__set_path (guestfs_h *g, const char *path)
552 {
553   free (g->path);
554   g->path = NULL;
555
556   g->path =
557     path == NULL ?
558     safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
559   return 0;
560 }
561
562 const char *
563 guestfs__get_path (guestfs_h *g)
564 {
565   return g->path;
566 }
567
568 int
569 guestfs__set_qemu (guestfs_h *g, const char *qemu)
570 {
571   free (g->qemu);
572   g->qemu = NULL;
573
574   g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
575   return 0;
576 }
577
578 const char *
579 guestfs__get_qemu (guestfs_h *g)
580 {
581   return g->qemu;
582 }
583
584 int
585 guestfs__set_append (guestfs_h *g, const char *append)
586 {
587   free (g->append);
588   g->append = NULL;
589
590   g->append = append ? safe_strdup (g, append) : NULL;
591   return 0;
592 }
593
594 const char *
595 guestfs__get_append (guestfs_h *g)
596 {
597   return g->append;
598 }
599
600 int
601 guestfs__set_memsize (guestfs_h *g, int memsize)
602 {
603   g->memsize = memsize;
604   return 0;
605 }
606
607 int
608 guestfs__get_memsize (guestfs_h *g)
609 {
610   return g->memsize;
611 }
612
613 int
614 guestfs__set_selinux (guestfs_h *g, int selinux)
615 {
616   g->selinux = selinux;
617   return 0;
618 }
619
620 int
621 guestfs__get_selinux (guestfs_h *g)
622 {
623   return g->selinux;
624 }
625
626 int
627 guestfs__get_pid (guestfs_h *g)
628 {
629   if (g->pid > 0)
630     return g->pid;
631   else {
632     error (g, "get_pid: no qemu subprocess");
633     return -1;
634   }
635 }
636
637 struct guestfs_version *
638 guestfs__version (guestfs_h *g)
639 {
640   struct guestfs_version *r;
641
642   r = safe_malloc (g, sizeof *r);
643   r->major = PACKAGE_VERSION_MAJOR;
644   r->minor = PACKAGE_VERSION_MINOR;
645   r->release = PACKAGE_VERSION_RELEASE;
646   r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
647   return r;
648 }
649
650 int
651 guestfs__set_trace (guestfs_h *g, int t)
652 {
653   g->trace = !!t;
654   return 0;
655 }
656
657 int
658 guestfs__get_trace (guestfs_h *g)
659 {
660   return g->trace;
661 }
662
663 int
664 guestfs__set_direct (guestfs_h *g, int d)
665 {
666   g->direct = !!d;
667   return 0;
668 }
669
670 int
671 guestfs__get_direct (guestfs_h *g)
672 {
673   return g->direct;
674 }
675
676 int
677 guestfs__set_recovery_proc (guestfs_h *g, int f)
678 {
679   g->recovery_proc = !!f;
680   return 0;
681 }
682
683 int
684 guestfs__get_recovery_proc (guestfs_h *g)
685 {
686   return g->recovery_proc;
687 }
688
689 /* Add a string to the current command line. */
690 static void
691 incr_cmdline_size (guestfs_h *g)
692 {
693   if (g->cmdline == NULL) {
694     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
695     g->cmdline_size = 1;
696     g->cmdline = safe_malloc (g, sizeof (char *));
697     g->cmdline[0] = NULL;
698   }
699
700   g->cmdline_size++;
701   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
702 }
703
704 static int
705 add_cmdline (guestfs_h *g, const char *str)
706 {
707   if (g->state != CONFIG) {
708     error (g,
709         _("command line cannot be altered after qemu subprocess launched"));
710     return -1;
711   }
712
713   incr_cmdline_size (g);
714   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
715   return 0;
716 }
717
718 int
719 guestfs__config (guestfs_h *g,
720                  const char *qemu_param, const char *qemu_value)
721 {
722   if (qemu_param[0] != '-') {
723     error (g, _("guestfs_config: parameter must begin with '-' character"));
724     return -1;
725   }
726
727   /* A bit fascist, but the user will probably break the extra
728    * parameters that we add if they try to set any of these.
729    */
730   if (STREQ (qemu_param, "-kernel") ||
731       STREQ (qemu_param, "-initrd") ||
732       STREQ (qemu_param, "-nographic") ||
733       STREQ (qemu_param, "-serial") ||
734       STREQ (qemu_param, "-full-screen") ||
735       STREQ (qemu_param, "-std-vga") ||
736       STREQ (qemu_param, "-vnc")) {
737     error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
738     return -1;
739   }
740
741   if (add_cmdline (g, qemu_param) != 0) return -1;
742
743   if (qemu_value != NULL) {
744     if (add_cmdline (g, qemu_value) != 0) return -1;
745   }
746
747   return 0;
748 }
749
750 int
751 guestfs__add_drive (guestfs_h *g, const char *filename)
752 {
753   size_t len = strlen (filename) + 64;
754   char buf[len];
755
756   if (strchr (filename, ',') != NULL) {
757     error (g, _("filename cannot contain ',' (comma) character"));
758     return -1;
759   }
760
761   /* cache=off improves reliability in the event of a host crash.
762    *
763    * However this option causes qemu to try to open the file with
764    * O_DIRECT.  This fails on some filesystem types (notably tmpfs).
765    * So we check if we can open the file with or without O_DIRECT,
766    * and use cache=off (or not) accordingly.
767    *
768    * This test also checks for the presence of the file, which
769    * is a documented semantic of this interface.
770    */
771   int fd = open (filename, O_RDONLY|O_DIRECT);
772   if (fd >= 0) {
773     close (fd);
774     snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
775   } else {
776     fd = open (filename, O_RDONLY);
777     if (fd >= 0) {
778       close (fd);
779       snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
780     } else {
781       perrorf (g, "%s", filename);
782       return -1;
783     }
784   }
785
786   return guestfs__config (g, "-drive", buf);
787 }
788
789 int
790 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
791 {
792   size_t len = strlen (filename) + 64;
793   char buf[len];
794
795   if (strchr (filename, ',') != NULL) {
796     error (g, _("filename cannot contain ',' (comma) character"));
797     return -1;
798   }
799
800   if (access (filename, F_OK) == -1) {
801     perrorf (g, "%s", filename);
802     return -1;
803   }
804
805   snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
806
807   return guestfs__config (g, "-drive", buf);
808 }
809
810 int
811 guestfs__add_cdrom (guestfs_h *g, const char *filename)
812 {
813   if (strchr (filename, ',') != NULL) {
814     error (g, _("filename cannot contain ',' (comma) character"));
815     return -1;
816   }
817
818   if (access (filename, F_OK) == -1) {
819     perrorf (g, "%s", filename);
820     return -1;
821   }
822
823   return guestfs__config (g, "-cdrom", filename);
824 }
825
826 /* Returns true iff file is contained in dir. */
827 static int
828 dir_contains_file (const char *dir, const char *file)
829 {
830   int dirlen = strlen (dir);
831   int filelen = strlen (file);
832   int len = dirlen+filelen+2;
833   char path[len];
834
835   snprintf (path, len, "%s/%s", dir, file);
836   return access (path, F_OK) == 0;
837 }
838
839 /* Returns true iff every listed file is contained in 'dir'. */
840 static int
841 dir_contains_files (const char *dir, ...)
842 {
843   va_list args;
844   const char *file;
845
846   va_start (args, dir);
847   while ((file = va_arg (args, const char *)) != NULL) {
848     if (!dir_contains_file (dir, file)) {
849       va_end (args);
850       return 0;
851     }
852   }
853   va_end (args);
854   return 1;
855 }
856
857 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
858 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
859 static int test_qemu (guestfs_h *g);
860 static int qemu_supports (guestfs_h *g, const char *option);
861 static void print_cmdline (guestfs_h *g);
862
863 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
864 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
865 static const char *supermin_name =
866   "initramfs." REPO "." host_cpu ".supermin.img";
867 static const char *supermin_hostfiles_name =
868   "initramfs." REPO "." host_cpu ".supermin.hostfiles";
869
870 int
871 guestfs__launch (guestfs_h *g)
872 {
873   const char *tmpdir;
874   char dir_template[PATH_MAX];
875   int r, pmore;
876   size_t len;
877   int wfd[2], rfd[2];
878   int tries;
879   char *path, *pelem, *pend;
880   char *kernel = NULL, *initrd = NULL;
881   int null_vmchannel_sock;
882   char unixsock[256];
883   struct sockaddr_un addr;
884
885   /* Start the clock ... */
886   gettimeofday (&g->launch_t, NULL);
887
888 #ifdef P_tmpdir
889   tmpdir = P_tmpdir;
890 #else
891   tmpdir = "/tmp";
892 #endif
893
894   tmpdir = getenv ("TMPDIR") ? : tmpdir;
895   snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
896
897   /* Configured? */
898   if (!g->cmdline) {
899     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
900     return -1;
901   }
902
903   if (g->state != CONFIG) {
904     error (g, _("qemu has already been launched"));
905     return -1;
906   }
907
908   /* Make the temporary directory. */
909   if (!g->tmpdir) {
910     g->tmpdir = safe_strdup (g, dir_template);
911     if (mkdtemp (g->tmpdir) == NULL) {
912       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
913       goto cleanup0;
914     }
915   }
916
917   /* First search g->path for the supermin appliance, and try to
918    * synthesize a kernel and initrd from that.  If it fails, we
919    * try the path search again looking for a backup ordinary
920    * appliance.
921    */
922   pelem = path = safe_strdup (g, g->path);
923   do {
924     pend = strchrnul (pelem, ':');
925     pmore = *pend == ':';
926     *pend = '\0';
927     len = pend - pelem;
928
929     /* Empty element of "." means cwd. */
930     if (len == 0 || (len == 1 && *pelem == '.')) {
931       if (g->verbose)
932         fprintf (stderr,
933                  "looking for supermin appliance in current directory\n");
934       if (dir_contains_files (".",
935                               supermin_name, supermin_hostfiles_name,
936                               "kmod.whitelist", NULL)) {
937         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
938           return -1;
939         break;
940       }
941     }
942     /* Look at <path>/supermin* etc. */
943     else {
944       if (g->verbose)
945         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
946
947       if (dir_contains_files (pelem,
948                               supermin_name, supermin_hostfiles_name,
949                               "kmod.whitelist", NULL)) {
950         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
951           return -1;
952         break;
953       }
954     }
955
956     pelem = pend + 1;
957   } while (pmore);
958
959   free (path);
960
961   if (kernel == NULL || initrd == NULL) {
962     /* Search g->path for the kernel and initrd. */
963     pelem = path = safe_strdup (g, g->path);
964     do {
965       pend = strchrnul (pelem, ':');
966       pmore = *pend == ':';
967       *pend = '\0';
968       len = pend - pelem;
969
970       /* Empty element or "." means cwd. */
971       if (len == 0 || (len == 1 && *pelem == '.')) {
972         if (g->verbose)
973           fprintf (stderr,
974                    "looking for appliance in current directory\n");
975         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
976           kernel = safe_strdup (g, kernel_name);
977           initrd = safe_strdup (g, initrd_name);
978           break;
979         }
980       }
981       /* Look at <path>/kernel etc. */
982       else {
983         if (g->verbose)
984           fprintf (stderr, "looking for appliance in %s\n", pelem);
985
986         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
987           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
988           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
989           sprintf (kernel, "%s/%s", pelem, kernel_name);
990           sprintf (initrd, "%s/%s", pelem, initrd_name);
991           break;
992         }
993       }
994
995       pelem = pend + 1;
996     } while (pmore);
997
998     free (path);
999   }
1000
1001   if (kernel == NULL || initrd == NULL) {
1002     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1003            kernel_name, initrd_name, g->path);
1004     goto cleanup0;
1005   }
1006
1007   if (g->verbose)
1008     print_timestamped_message (g, "begin testing qemu features");
1009
1010   /* Get qemu help text and version. */
1011   if (test_qemu (g) == -1)
1012     goto cleanup0;
1013
1014   /* Choose which vmchannel implementation to use. */
1015   if (qemu_supports (g, "-net user")) {
1016     /* The "null vmchannel" implementation.  Requires SLIRP (user mode
1017      * networking in qemu) but no other vmchannel support.  The daemon
1018      * will connect back to a random port number on localhost.
1019      */
1020     struct sockaddr_in addr;
1021     socklen_t addrlen = sizeof addr;
1022
1023     g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1024     if (g->sock == -1) {
1025       perrorf (g, "socket");
1026       goto cleanup0;
1027     }
1028     addr.sin_family = AF_INET;
1029     addr.sin_port = htons (0);
1030     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1031     if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1032       perrorf (g, "bind");
1033       goto cleanup0;
1034     }
1035
1036     if (listen (g->sock, 256) == -1) {
1037       perrorf (g, "listen");
1038       goto cleanup0;
1039     }
1040
1041     if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1042       perrorf (g, "getsockname");
1043       goto cleanup0;
1044     }
1045
1046     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1047       perrorf (g, "fcntl");
1048       goto cleanup0;
1049     }
1050
1051     null_vmchannel_sock = ntohs (addr.sin_port);
1052     if (g->verbose)
1053       fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1054   } else {
1055     /* Using some vmchannel impl.  We need to create a local Unix
1056      * domain socket for qemu to use.
1057      */
1058     snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1059     unlink (unixsock);
1060     null_vmchannel_sock = 0;
1061   }
1062
1063   if (!g->direct) {
1064     if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1065       perrorf (g, "pipe");
1066       goto cleanup0;
1067     }
1068   }
1069
1070   if (g->verbose)
1071     print_timestamped_message (g, "finished testing qemu features");
1072
1073   r = fork ();
1074   if (r == -1) {
1075     perrorf (g, "fork");
1076     if (!g->direct) {
1077       close (wfd[0]);
1078       close (wfd[1]);
1079       close (rfd[0]);
1080       close (rfd[1]);
1081     }
1082     goto cleanup0;
1083   }
1084
1085   if (r == 0) {                 /* Child (qemu). */
1086     char buf[256];
1087     const char *vmchannel = NULL;
1088
1089     /* Set up the full command line.  Do this in the subprocess so we
1090      * don't need to worry about cleaning up.
1091      */
1092     g->cmdline[0] = g->qemu;
1093
1094     /* Newer versions of qemu (from around 2009/12) changed the
1095      * behaviour of monitors so that an implicit '-monitor stdio' is
1096      * assumed if we are in -nographic mode and there is no other
1097      * -monitor option.  Only a single stdio device is allowed, so
1098      * this broke the '-serial stdio' option.  There is a new flag
1099      * called -nodefaults which gets rid of all this default crud, so
1100      * let's use that to avoid this and any future surprises.
1101      */
1102     if (qemu_supports (g, "-nodefaults"))
1103       add_cmdline (g, "-nodefaults");
1104
1105     add_cmdline (g, "-nographic");
1106     add_cmdline (g, "-serial");
1107     add_cmdline (g, "stdio");
1108
1109     snprintf (buf, sizeof buf, "%d", g->memsize);
1110     add_cmdline (g, "-m");
1111     add_cmdline (g, buf);
1112
1113     /* Force exit instead of reboot on panic */
1114     add_cmdline (g, "-no-reboot");
1115
1116     /* These options recommended by KVM developers to improve reliability. */
1117     if (qemu_supports (g, "-no-hpet"))
1118       add_cmdline (g, "-no-hpet");
1119
1120     if (qemu_supports (g, "-rtc-td-hack"))
1121       add_cmdline (g, "-rtc-td-hack");
1122
1123     /* If qemu has SLIRP (user mode network) enabled then we can get
1124      * away with "no vmchannel", where we just connect back to a random
1125      * host port.
1126      */
1127     if (null_vmchannel_sock) {
1128       add_cmdline (g, "-net");
1129       add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1130
1131       snprintf (buf, sizeof buf,
1132                 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1133       vmchannel = strdup (buf);
1134     }
1135
1136     /* New-style -net user,guestfwd=... syntax for guestfwd.  See:
1137      *
1138      * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1139      *
1140      * The original suggested format doesn't work, see:
1141      *
1142      * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1143      *
1144      * However Gerd Hoffman privately suggested to me using -chardev
1145      * instead, which does work.
1146      */
1147     else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1148       snprintf (buf, sizeof buf,
1149                 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1150
1151       add_cmdline (g, "-chardev");
1152       add_cmdline (g, buf);
1153
1154       snprintf (buf, sizeof buf,
1155                 "user,vlan=0,net=10.0.2.0/8,"
1156                 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1157                 "-chardev:guestfsvmc");
1158
1159       add_cmdline (g, "-net");
1160       add_cmdline (g, buf);
1161
1162       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1163     }
1164
1165     /* Not guestfwd.  HOPEFULLY this qemu uses the older -net channel
1166      * syntax, or if not then we'll get a quick failure.
1167      */
1168     else {
1169       snprintf (buf, sizeof buf,
1170                 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1171
1172       add_cmdline (g, "-net");
1173       add_cmdline (g, buf);
1174       add_cmdline (g, "-net");
1175       add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1176
1177       vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1178     }
1179     add_cmdline (g, "-net");
1180     add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1181
1182 #define LINUX_CMDLINE                                                   \
1183     "panic=1 "         /* force kernel to panic if daemon exits */      \
1184     "console=ttyS0 "   /* serial console */                             \
1185     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
1186     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
1187     "acpi=off "        /* we don't need ACPI, turn it off */            \
1188     "printk.time=1 "   /* display timestamp before kernel messages */   \
1189     "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1190
1191     /* Linux kernel command line. */
1192     snprintf (buf, sizeof buf,
1193               LINUX_CMDLINE
1194               "%s "             /* (selinux) */
1195               "%s "             /* (vmchannel) */
1196               "%s "             /* (verbose) */
1197               "%s",             /* (append) */
1198               g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1199               vmchannel ? vmchannel : "",
1200               g->verbose ? "guestfs_verbose=1" : "",
1201               g->append ? g->append : "");
1202
1203     add_cmdline (g, "-kernel");
1204     add_cmdline (g, (char *) kernel);
1205     add_cmdline (g, "-initrd");
1206     add_cmdline (g, (char *) initrd);
1207     add_cmdline (g, "-append");
1208     add_cmdline (g, buf);
1209
1210     /* Finish off the command line. */
1211     incr_cmdline_size (g);
1212     g->cmdline[g->cmdline_size-1] = NULL;
1213
1214     if (g->verbose)
1215       print_cmdline (g);
1216
1217     if (!g->direct) {
1218       /* Set up stdin, stdout. */
1219       close (0);
1220       close (1);
1221       close (wfd[1]);
1222       close (rfd[0]);
1223
1224       if (dup (wfd[0]) == -1) {
1225       dup_failed:
1226         perror ("dup failed");
1227         _exit (1);
1228       }
1229       if (dup (rfd[1]) == -1)
1230         goto dup_failed;
1231
1232       close (wfd[0]);
1233       close (rfd[1]);
1234     }
1235
1236 #if 0
1237     /* Set up a new process group, so we can signal this process
1238      * and all subprocesses (eg. if qemu is really a shell script).
1239      */
1240     setpgid (0, 0);
1241 #endif
1242
1243     setenv ("LC_ALL", "C", 1);
1244
1245     execv (g->qemu, g->cmdline); /* Run qemu. */
1246     perror (g->qemu);
1247     _exit (1);
1248   }
1249
1250   /* Parent (library). */
1251   g->pid = r;
1252
1253   free (kernel);
1254   kernel = NULL;
1255   free (initrd);
1256   initrd = NULL;
1257
1258   /* Fork the recovery process off which will kill qemu if the parent
1259    * process fails to do so (eg. if the parent segfaults).
1260    */
1261   g->recoverypid = -1;
1262   if (g->recovery_proc) {
1263     r = fork ();
1264     if (r == 0) {
1265       pid_t qemu_pid = g->pid;
1266       pid_t parent_pid = getppid ();
1267
1268       /* Writing to argv is hideously complicated and error prone.  See:
1269        * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1270        */
1271
1272       /* Loop around waiting for one or both of the other processes to
1273        * disappear.  It's fair to say this is very hairy.  The PIDs that
1274        * we are looking at might be reused by another process.  We are
1275        * effectively polling.  Is the cure worse than the disease?
1276        */
1277       for (;;) {
1278         if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1279           _exit (0);
1280         if (kill (parent_pid, 0) == -1) {
1281           /* Parent's gone away, qemu still around, so kill qemu. */
1282           kill (qemu_pid, 9);
1283           _exit (0);
1284         }
1285         sleep (2);
1286       }
1287     }
1288
1289     /* Don't worry, if the fork failed, this will be -1.  The recovery
1290      * process isn't essential.
1291      */
1292     g->recoverypid = r;
1293   }
1294
1295   if (!g->direct) {
1296     /* Close the other ends of the pipe. */
1297     close (wfd[0]);
1298     close (rfd[1]);
1299
1300     if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1301         fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1302       perrorf (g, "fcntl");
1303       goto cleanup1;
1304     }
1305
1306     g->fd[0] = wfd[1];          /* stdin of child */
1307     g->fd[1] = rfd[0];          /* stdout of child */
1308   } else {
1309     g->fd[0] = open ("/dev/null", O_RDWR);
1310     if (g->fd[0] == -1) {
1311       perrorf (g, "open /dev/null");
1312       goto cleanup1;
1313     }
1314     g->fd[1] = dup (g->fd[0]);
1315     if (g->fd[1] == -1) {
1316       perrorf (g, "dup");
1317       close (g->fd[0]);
1318       goto cleanup1;
1319     }
1320   }
1321
1322   if (null_vmchannel_sock) {
1323     int sock = -1;
1324     uid_t uid;
1325
1326     /* Null vmchannel implementation: We listen on g->sock for a
1327      * connection.  The connection could come from any local process
1328      * so we must check it comes from the appliance (or at least
1329      * from our UID) for security reasons.
1330      */
1331     while (sock == -1) {
1332       sock = accept_from_daemon (g);
1333       if (sock == -1)
1334         goto cleanup1;
1335
1336       if (check_peer_euid (g, sock, &uid) == -1)
1337         goto cleanup1;
1338       if (uid != geteuid ()) {
1339         fprintf (stderr,
1340                  "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1341                  uid, null_vmchannel_sock);
1342         close (sock);
1343         continue;
1344       }
1345     }
1346
1347     if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1348       perrorf (g, "fcntl");
1349       goto cleanup1;
1350     }
1351
1352     close (g->sock);
1353     g->sock = sock;
1354   } else {
1355     /* Other vmchannel.  Open the Unix socket.
1356      *
1357      * The vmchannel implementation that got merged with qemu sucks in
1358      * a number of ways.  Both ends do connect(2), which means that no
1359      * one knows what, if anything, is connected to the other end, or
1360      * if it becomes disconnected.  Even worse, we have to wait some
1361      * indeterminate time for qemu to create the socket and connect to
1362      * it (which happens very early in qemu's start-up), so any code
1363      * that uses vmchannel is inherently racy.  Hence this silly loop.
1364      */
1365     g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1366     if (g->sock == -1) {
1367       perrorf (g, "socket");
1368       goto cleanup1;
1369     }
1370
1371     if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1372       perrorf (g, "fcntl");
1373       goto cleanup1;
1374     }
1375
1376     addr.sun_family = AF_UNIX;
1377     strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1378     addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1379
1380     tries = 100;
1381     /* Always sleep at least once to give qemu a small chance to start up. */
1382     usleep (10000);
1383     while (tries > 0) {
1384       r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1385       if ((r == -1 && errno == EINPROGRESS) || r == 0)
1386         goto connected;
1387
1388       if (errno != ENOENT)
1389         perrorf (g, "connect");
1390       tries--;
1391       usleep (100000);
1392     }
1393
1394     error (g, _("failed to connect to vmchannel socket"));
1395     goto cleanup1;
1396
1397   connected: ;
1398   }
1399
1400   g->state = LAUNCHING;
1401
1402   /* Wait for qemu to start and to connect back to us via vmchannel and
1403    * send the GUESTFS_LAUNCH_FLAG message.
1404    */
1405   uint32_t size;
1406   void *buf = NULL;
1407   r = recv_from_daemon (g, &size, &buf);
1408   free (buf);
1409
1410   if (r == -1) return -1;
1411
1412   if (size != GUESTFS_LAUNCH_FLAG) {
1413     error (g, _("guestfs_launch failed, see earlier error messages"));
1414     goto cleanup1;
1415   }
1416
1417   if (g->verbose)
1418     print_timestamped_message (g, "appliance is up");
1419
1420   /* This is possible in some really strange situations, such as
1421    * guestfsd starts up OK but then qemu immediately exits.  Check for
1422    * it because the caller is probably expecting to be able to send
1423    * commands after this function returns.
1424    */
1425   if (g->state != READY) {
1426     error (g, _("qemu launched and contacted daemon, but state != READY"));
1427     goto cleanup1;
1428   }
1429
1430   return 0;
1431
1432  cleanup1:
1433   if (!g->direct) {
1434     close (wfd[1]);
1435     close (rfd[0]);
1436   }
1437   kill (g->pid, 9);
1438   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1439   waitpid (g->pid, NULL, 0);
1440   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1441   g->fd[0] = -1;
1442   g->fd[1] = -1;
1443   g->pid = 0;
1444   g->recoverypid = 0;
1445   memset (&g->launch_t, 0, sizeof g->launch_t);
1446
1447  cleanup0:
1448   if (g->sock >= 0) {
1449     close (g->sock);
1450     g->sock = -1;
1451   }
1452   g->state = CONFIG;
1453   free (kernel);
1454   free (initrd);
1455   return -1;
1456 }
1457
1458 /* This function is used to print the qemu command line before it gets
1459  * executed, when in verbose mode.
1460  */
1461 static void
1462 print_cmdline (guestfs_h *g)
1463 {
1464   int i = 0;
1465   int needs_quote;
1466
1467   while (g->cmdline[i]) {
1468     if (g->cmdline[i][0] == '-') /* -option starts a new line */
1469       fprintf (stderr, " \\\n   ");
1470
1471     if (i > 0) fputc (' ', stderr);
1472
1473     /* Does it need shell quoting?  This only deals with simple cases. */
1474     needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1475
1476     if (needs_quote) fputc ('\'', stderr);
1477     fprintf (stderr, "%s", g->cmdline[i]);
1478     if (needs_quote) fputc ('\'', stderr);
1479     i++;
1480   }
1481
1482   fputc ('\n', stderr);
1483 }
1484
1485 /* This function does the hard work of building the supermin appliance
1486  * on the fly.  'path' is the directory containing the control files.
1487  * 'kernel' and 'initrd' are where we will return the names of the
1488  * kernel and initrd (only initrd is built).  The work is done by
1489  * an external script.  We just tell it where to put the result.
1490  */
1491 static int
1492 build_supermin_appliance (guestfs_h *g, const char *path,
1493                           char **kernel, char **initrd)
1494 {
1495   char cmd[4096];
1496   int r, len;
1497
1498   if (g->verbose)
1499     print_timestamped_message (g, "begin building supermin appliance");
1500
1501   len = strlen (g->tmpdir);
1502   *kernel = safe_malloc (g, len + 8);
1503   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1504   *initrd = safe_malloc (g, len + 8);
1505   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1506
1507   snprintf (cmd, sizeof cmd,
1508             "PATH='%s':$PATH "
1509             "libguestfs-supermin-helper '%s' " host_cpu " " REPO " %s %s",
1510             path,
1511             path, *kernel, *initrd);
1512   if (g->verbose)
1513     print_timestamped_message (g, "%s", cmd);
1514
1515   r = system (cmd);
1516   if (r == -1 || WEXITSTATUS(r) != 0) {
1517     error (g, _("external command failed: %s"), cmd);
1518     free (*kernel);
1519     free (*initrd);
1520     *kernel = *initrd = NULL;
1521     return -1;
1522   }
1523
1524   if (g->verbose)
1525     print_timestamped_message (g, "finished building supermin appliance");
1526
1527   return 0;
1528 }
1529
1530 /* Compute Y - X and return the result in milliseconds.
1531  * Approximately the same as this code:
1532  * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1533  */
1534 static int64_t
1535 timeval_diff (const struct timeval *x, const struct timeval *y)
1536 {
1537   int64_t msec;
1538
1539   msec = (y->tv_sec - x->tv_sec) * 1000;
1540   msec += (y->tv_usec - x->tv_usec) / 1000;
1541   return msec;
1542 }
1543
1544 static void
1545 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1546 {
1547   va_list args;
1548   char *msg;
1549   int err;
1550   struct timeval tv, diff;
1551
1552   va_start (args, fs);
1553   err = vasprintf (&msg, fs, args);
1554   va_end (args);
1555
1556   if (err < 0) return;
1557
1558   gettimeofday (&tv, NULL);
1559
1560   fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1561            timeval_diff (&g->launch_t, &tv), msg);
1562
1563   free (msg);
1564 }
1565
1566 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1567
1568 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1569  * 'qemu -version' so we know what options this qemu supports and
1570  * the version.
1571  */
1572 static int
1573 test_qemu (guestfs_h *g)
1574 {
1575   char cmd[1024];
1576   FILE *fp;
1577
1578   free (g->qemu_help);
1579   free (g->qemu_version);
1580   g->qemu_help = NULL;
1581   g->qemu_version = NULL;
1582
1583   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -help", g->qemu);
1584
1585   fp = popen (cmd, "r");
1586   /* qemu -help should always work (qemu -version OTOH wasn't
1587    * supported by qemu 0.9).  If this command doesn't work then it
1588    * probably indicates that the qemu binary is missing.
1589    */
1590   if (!fp) {
1591     /* XXX This error is never printed, even if the qemu binary
1592      * doesn't exist.  Why?
1593      */
1594   error:
1595     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1596     return -1;
1597   }
1598
1599   if (read_all (g, fp, &g->qemu_help) == -1)
1600     goto error;
1601
1602   if (pclose (fp) == -1)
1603     goto error;
1604
1605   snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -version 2>/dev/null", g->qemu);
1606
1607   fp = popen (cmd, "r");
1608   if (fp) {
1609     /* Intentionally ignore errors. */
1610     read_all (g, fp, &g->qemu_version);
1611     pclose (fp);
1612   }
1613
1614   return 0;
1615 }
1616
1617 static int
1618 read_all (guestfs_h *g, FILE *fp, char **ret)
1619 {
1620   int r, n = 0;
1621   char *p;
1622
1623  again:
1624   if (feof (fp)) {
1625     *ret = safe_realloc (g, *ret, n + 1);
1626     (*ret)[n] = '\0';
1627     return n;
1628   }
1629
1630   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1631   p = &(*ret)[n];
1632   r = fread (p, 1, BUFSIZ, fp);
1633   if (ferror (fp)) {
1634     perrorf (g, "read");
1635     return -1;
1636   }
1637   n += r;
1638   goto again;
1639 }
1640
1641 /* Test if option is supported by qemu command line (just by grepping
1642  * the help text).
1643  */
1644 static int
1645 qemu_supports (guestfs_h *g, const char *option)
1646 {
1647   return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1648 }
1649
1650 /* Check the peer effective UID for a TCP socket.  Ideally we'd like
1651  * SO_PEERCRED for a loopback TCP socket.  This isn't possible on
1652  * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1653  */
1654 static int
1655 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1656 {
1657   struct sockaddr_in peer;
1658   socklen_t addrlen = sizeof peer;
1659
1660   if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1661     perrorf (g, "getpeername");
1662     return -1;
1663   }
1664
1665   if (peer.sin_family != AF_INET ||
1666       ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1667     error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1668            peer.sin_family, inet_ntoa (peer.sin_addr));
1669     return -1;
1670   }
1671
1672   struct sockaddr_in our;
1673   addrlen = sizeof our;
1674   if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1675     perrorf (g, "getsockname");
1676     return -1;
1677   }
1678
1679   FILE *fp = fopen ("/proc/net/tcp", "r");
1680   if (fp == NULL) {
1681     perrorf (g, "/proc/net/tcp");
1682     return -1;
1683   }
1684
1685   char line[256];
1686   if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1687     error (g, "unexpected end of file in /proc/net/tcp");
1688     fclose (fp);
1689     return -1;
1690   }
1691
1692   while (fgets (line, sizeof line, fp) != NULL) {
1693     unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1694     int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1695     int line_uid;
1696
1697     if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1698                 &dummy0,
1699                 &line_our_addr, &line_our_port,
1700                 &line_peer_addr, &line_peer_port,
1701                 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1702                 &line_uid) == 12) {
1703       /* Note about /proc/net/tcp: local_address and rem_address are
1704        * always in network byte order.  However the port part is
1705        * always in host byte order.
1706        *
1707        * The sockname and peername that we got above are in network
1708        * byte order.  So we have to byte swap the port but not the
1709        * address part.
1710        */
1711       if (line_our_addr == our.sin_addr.s_addr &&
1712           line_our_port == ntohs (our.sin_port) &&
1713           line_peer_addr == peer.sin_addr.s_addr &&
1714           line_peer_port == ntohs (peer.sin_port)) {
1715         *rtn = line_uid;
1716         fclose (fp);
1717         return 0;
1718       }
1719     }
1720   }
1721
1722   error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1723   fclose (fp);
1724   return -1;
1725 }
1726
1727 /* You had to call this function after launch in versions <= 1.0.70,
1728  * but it is now a no-op.
1729  */
1730 int
1731 guestfs__wait_ready (guestfs_h *g)
1732 {
1733   if (g->state != READY)  {
1734     error (g, _("qemu has not been launched yet"));
1735     return -1;
1736   }
1737
1738   return 0;
1739 }
1740
1741 int
1742 guestfs__kill_subprocess (guestfs_h *g)
1743 {
1744   if (g->state == CONFIG) {
1745     error (g, _("no subprocess to kill"));
1746     return -1;
1747   }
1748
1749   if (g->verbose)
1750     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1751
1752   kill (g->pid, SIGTERM);
1753   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1754
1755   return 0;
1756 }
1757
1758 /* Access current state. */
1759 int
1760 guestfs__is_config (guestfs_h *g)
1761 {
1762   return g->state == CONFIG;
1763 }
1764
1765 int
1766 guestfs__is_launching (guestfs_h *g)
1767 {
1768   return g->state == LAUNCHING;
1769 }
1770
1771 int
1772 guestfs__is_ready (guestfs_h *g)
1773 {
1774   return g->state == READY;
1775 }
1776
1777 int
1778 guestfs__is_busy (guestfs_h *g)
1779 {
1780   return g->state == BUSY;
1781 }
1782
1783 int
1784 guestfs__get_state (guestfs_h *g)
1785 {
1786   return g->state;
1787 }
1788
1789 void
1790 guestfs_set_log_message_callback (guestfs_h *g,
1791                                   guestfs_log_message_cb cb, void *opaque)
1792 {
1793   g->log_message_cb = cb;
1794   g->log_message_cb_data = opaque;
1795 }
1796
1797 void
1798 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1799                                       guestfs_subprocess_quit_cb cb, void *opaque)
1800 {
1801   g->subprocess_quit_cb = cb;
1802   g->subprocess_quit_cb_data = opaque;
1803 }
1804
1805 void
1806 guestfs_set_launch_done_callback (guestfs_h *g,
1807                                   guestfs_launch_done_cb cb, void *opaque)
1808 {
1809   g->launch_done_cb = cb;
1810   g->launch_done_cb_data = opaque;
1811 }
1812
1813 /*----------------------------------------------------------------------*/
1814
1815 /* This is the code used to send and receive RPC messages and (for
1816  * certain types of message) to perform file transfers.  This code is
1817  * driven from the generated actions (src/guestfs-actions.c).  There
1818  * are five different cases to consider:
1819  *
1820  * (1) A non-daemon function.  There is no RPC involved at all, it's
1821  * all handled inside the library.
1822  *
1823  * (2) A simple RPC (eg. "mount").  We write the request, then read
1824  * the reply.  The sequence of calls is:
1825  *
1826  *   guestfs___set_busy
1827  *   guestfs___send
1828  *   guestfs___recv
1829  *   guestfs___end_busy
1830  *
1831  * (3) An RPC with FileOut parameters (eg. "upload").  We write the
1832  * request, then write the file(s), then read the reply.  The sequence
1833  * of calls is:
1834  *
1835  *   guestfs___set_busy
1836  *   guestfs___send
1837  *   guestfs___send_file  (possibly multiple times)
1838  *   guestfs___recv
1839  *   guestfs___end_busy
1840  *
1841  * (4) An RPC with FileIn parameters (eg. "download").  We write the
1842  * request, then read the reply, then read the file(s).  The sequence
1843  * of calls is:
1844  *
1845  *   guestfs___set_busy
1846  *   guestfs___send
1847  *   guestfs___recv
1848  *   guestfs___recv_file  (possibly multiple times)
1849  *   guestfs___end_busy
1850  *
1851  * (5) Both FileOut and FileIn parameters.  There are no calls like
1852  * this in the current API, but they would be implemented as a
1853  * combination of cases (3) and (4).
1854  *
1855  * During all writes and reads, we also select(2) on qemu stdout
1856  * looking for messages (guestfsd stderr and guest kernel dmesg), and
1857  * anything received is passed up through the log_message_cb.  This is
1858  * also the reason why all the sockets are non-blocking.  We also have
1859  * to check for EOF (qemu died).  All of this is handled by the
1860  * functions send_to_daemon and recv_from_daemon.
1861  */
1862
1863 int
1864 guestfs___set_busy (guestfs_h *g)
1865 {
1866   if (g->state != READY) {
1867     error (g, _("guestfs_set_busy: called when in state %d != READY"),
1868            g->state);
1869     return -1;
1870   }
1871   g->state = BUSY;
1872   return 0;
1873 }
1874
1875 int
1876 guestfs___end_busy (guestfs_h *g)
1877 {
1878   switch (g->state)
1879     {
1880     case BUSY:
1881       g->state = READY;
1882       break;
1883     case CONFIG:
1884     case READY:
1885       break;
1886
1887     case LAUNCHING:
1888     case NO_HANDLE:
1889     default:
1890       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1891       return -1;
1892     }
1893   return 0;
1894 }
1895
1896 /* This is called if we detect EOF, ie. qemu died. */
1897 static void
1898 child_cleanup (guestfs_h *g)
1899 {
1900   if (g->verbose)
1901     fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1902
1903   /*kill (g->pid, SIGTERM);*/
1904   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1905   waitpid (g->pid, NULL, 0);
1906   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1907   close (g->fd[0]);
1908   close (g->fd[1]);
1909   close (g->sock);
1910   g->fd[0] = -1;
1911   g->fd[1] = -1;
1912   g->sock = -1;
1913   g->pid = 0;
1914   g->recoverypid = 0;
1915   memset (&g->launch_t, 0, sizeof g->launch_t);
1916   g->state = CONFIG;
1917   if (g->subprocess_quit_cb)
1918     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1919 }
1920
1921 static int
1922 read_log_message_or_eof (guestfs_h *g, int fd)
1923 {
1924   char buf[BUFSIZ];
1925   int n;
1926
1927 #if 0
1928   if (g->verbose)
1929     fprintf (stderr,
1930              "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1931              g, g->state, fd);
1932 #endif
1933
1934   /* QEMU's console emulates a 16550A serial port.  The real 16550A
1935    * device has a small FIFO buffer (16 bytes) which means here we see
1936    * lots of small reads of 1-16 bytes in length, usually single
1937    * bytes.
1938    */
1939   n = read (fd, buf, sizeof buf);
1940   if (n == 0) {
1941     /* Hopefully this indicates the qemu child process has died. */
1942     child_cleanup (g);
1943     return -1;
1944   }
1945
1946   if (n == -1) {
1947     if (errno == EINTR || errno == EAGAIN)
1948       return 0;
1949
1950     perrorf (g, "read");
1951     return -1;
1952   }
1953
1954   /* In verbose mode, copy all log messages to stderr. */
1955   if (g->verbose)
1956     ignore_value (write (STDERR_FILENO, buf, n));
1957
1958   /* It's an actual log message, send it upwards if anyone is listening. */
1959   if (g->log_message_cb)
1960     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1961
1962   return 0;
1963 }
1964
1965 static int
1966 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1967 {
1968   char buf[4];
1969   int n;
1970   uint32_t flag;
1971   XDR xdr;
1972
1973   if (g->verbose)
1974     fprintf (stderr,
1975              "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1976              g, g->state, fd);
1977
1978   n = read (fd, buf, 4);
1979   if (n == 0) {
1980     /* Hopefully this indicates the qemu child process has died. */
1981     child_cleanup (g);
1982     return -1;
1983   }
1984
1985   if (n == -1) {
1986     if (errno == EINTR || errno == EAGAIN)
1987       return 0;
1988
1989     perrorf (g, "read");
1990     return -1;
1991   }
1992
1993   xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1994   xdr_uint32_t (&xdr, &flag);
1995   xdr_destroy (&xdr);
1996
1997   if (flag != GUESTFS_CANCEL_FLAG) {
1998     error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1999            flag, GUESTFS_CANCEL_FLAG);
2000     return -1;
2001   }
2002
2003   return -2;
2004 }
2005
2006 /* This writes the whole N bytes of BUF to the daemon socket.
2007  *
2008  * If the whole write is successful, it returns 0.
2009  * If there was an error, it returns -1.
2010  * If the daemon sent a cancellation message, it returns -2.
2011  *
2012  * It also checks qemu stdout for log messages and passes those up
2013  * through log_message_cb.
2014  *
2015  * It also checks for EOF (qemu died) and passes that up through the
2016  * child_cleanup function above.
2017  */
2018 static int
2019 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2020 {
2021   const char *buf = v_buf;
2022   fd_set rset, rset2;
2023   fd_set wset, wset2;
2024
2025   if (g->verbose)
2026     fprintf (stderr,
2027              "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2028
2029   FD_ZERO (&rset);
2030   FD_ZERO (&wset);
2031
2032   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
2033   FD_SET (g->sock, &rset);      /* Read socket for cancellation & EOF. */
2034   FD_SET (g->sock, &wset);      /* Write to socket to send the data. */
2035
2036   int max_fd = MAX (g->sock, g->fd[1]);
2037
2038   while (n > 0) {
2039     rset2 = rset;
2040     wset2 = wset;
2041     int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2042     if (r == -1) {
2043       if (errno == EINTR || errno == EAGAIN)
2044         continue;
2045       perrorf (g, "select");
2046       return -1;
2047     }
2048
2049     if (FD_ISSET (g->fd[1], &rset2)) {
2050       if (read_log_message_or_eof (g, g->fd[1]) == -1)
2051         return -1;
2052     }
2053     if (FD_ISSET (g->sock, &rset2)) {
2054       r = check_for_daemon_cancellation_or_eof (g, g->sock);
2055       if (r < 0)
2056         return r;
2057     }
2058     if (FD_ISSET (g->sock, &wset2)) {
2059       r = write (g->sock, buf, n);
2060       if (r == -1) {
2061         if (errno == EINTR || errno == EAGAIN)
2062           continue;
2063         perrorf (g, "write");
2064         if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2065           child_cleanup (g);
2066         return -1;
2067       }
2068       buf += r;
2069       n -= r;
2070     }
2071   }
2072
2073   return 0;
2074 }
2075
2076 /* This reads a single message, file chunk, launch flag or
2077  * cancellation flag from the daemon.  If something was read, it
2078  * returns 0, otherwise -1.
2079  *
2080  * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2081  *
2082  * *size_rtn returns the size of the returned message or it may be
2083  * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2084  *
2085  * *buf_rtn is returned containing the message (if any) or will be set
2086  * to NULL.  *buf_rtn must be freed by the caller.
2087  *
2088  * It also checks qemu stdout for log messages and passes those up
2089  * through log_message_cb.
2090  *
2091  * It also checks for EOF (qemu died) and passes that up through the
2092  * child_cleanup function above.
2093  */
2094 static int
2095 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2096 {
2097   fd_set rset, rset2;
2098
2099   if (g->verbose)
2100     fprintf (stderr,
2101              "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2102              g, g->state, size_rtn, buf_rtn);
2103
2104   FD_ZERO (&rset);
2105
2106   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
2107   FD_SET (g->sock, &rset);      /* Read socket for data & EOF. */
2108
2109   int max_fd = MAX (g->sock, g->fd[1]);
2110
2111   *size_rtn = 0;
2112   *buf_rtn = NULL;
2113
2114   char lenbuf[4];
2115   /* nr is the size of the message, but we prime it as -4 because we
2116    * have to read the message length word first.
2117    */
2118   ssize_t nr = -4;
2119
2120   while (nr < (ssize_t) *size_rtn) {
2121     rset2 = rset;
2122     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2123     if (r == -1) {
2124       if (errno == EINTR || errno == EAGAIN)
2125         continue;
2126       perrorf (g, "select");
2127       free (*buf_rtn);
2128       *buf_rtn = NULL;
2129       return -1;
2130     }
2131
2132     if (FD_ISSET (g->fd[1], &rset2)) {
2133       if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2134         free (*buf_rtn);
2135         *buf_rtn = NULL;
2136         return -1;
2137       }
2138     }
2139     if (FD_ISSET (g->sock, &rset2)) {
2140       if (nr < 0) {    /* Have we read the message length word yet? */
2141         r = read (g->sock, lenbuf+nr+4, -nr);
2142         if (r == -1) {
2143           if (errno == EINTR || errno == EAGAIN)
2144             continue;
2145           int err = errno;
2146           perrorf (g, "read");
2147           /* Under some circumstances we see "Connection reset by peer"
2148            * here when the child dies suddenly.  Catch this and call
2149            * the cleanup function, same as for EOF.
2150            */
2151           if (err == ECONNRESET)
2152             child_cleanup (g);
2153           return -1;
2154         }
2155         if (r == 0) {
2156           error (g, _("unexpected end of file when reading from daemon"));
2157           child_cleanup (g);
2158           return -1;
2159         }
2160         nr += r;
2161
2162         if (nr < 0)         /* Still not got the whole length word. */
2163           continue;
2164
2165         XDR xdr;
2166         xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2167         xdr_uint32_t (&xdr, size_rtn);
2168         xdr_destroy (&xdr);
2169
2170         if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2171           if (g->state != LAUNCHING)
2172             error (g, _("received magic signature from guestfsd, but in state %d"),
2173                    g->state);
2174           else {
2175             g->state = READY;
2176             if (g->launch_done_cb)
2177               g->launch_done_cb (g, g->launch_done_cb_data);
2178           }
2179           return 0;
2180         }
2181         else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2182           return 0;
2183         /* If this happens, it's pretty bad and we've probably lost
2184          * synchronization.
2185          */
2186         else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2187           error (g, _("message length (%u) > maximum possible size (%d)"),
2188                  (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2189           return -1;
2190         }
2191
2192         /* Allocate the complete buffer, size now known. */
2193         *buf_rtn = safe_malloc (g, *size_rtn);
2194         /*FALLTHROUGH*/
2195       }
2196
2197       size_t sizetoread = *size_rtn - nr;
2198       if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2199
2200       r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2201       if (r == -1) {
2202         if (errno == EINTR || errno == EAGAIN)
2203           continue;
2204         perrorf (g, "read");
2205         free (*buf_rtn);
2206         *buf_rtn = NULL;
2207         return -1;
2208       }
2209       if (r == 0) {
2210         error (g, _("unexpected end of file when reading from daemon"));
2211         child_cleanup (g);
2212         free (*buf_rtn);
2213         *buf_rtn = NULL;
2214         return -1;
2215       }
2216       nr += r;
2217     }
2218   }
2219
2220   /* Got the full message, caller can start processing it. */
2221 #ifdef ENABLE_PACKET_DUMP
2222   if (g->verbose) {
2223     ssize_t i, j;
2224
2225     for (i = 0; i < nr; i += 16) {
2226       printf ("%04zx: ", i);
2227       for (j = i; j < MIN (i+16, nr); ++j)
2228         printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2229       for (; j < i+16; ++j)
2230         printf ("   ");
2231       printf ("|");
2232       for (j = i; j < MIN (i+16, nr); ++j)
2233         if (c_isprint ((*(char **)buf_rtn)[j]))
2234           printf ("%c", (*(char **)buf_rtn)[j]);
2235         else
2236           printf (".");
2237       for (; j < i+16; ++j)
2238         printf (" ");
2239       printf ("|\n");
2240     }
2241   }
2242 #endif
2243
2244   return 0;
2245 }
2246
2247 /* This is very much like recv_from_daemon above, but g->sock is
2248  * a listening socket and we are accepting a new connection on
2249  * that socket instead of reading anything.  Returns the newly
2250  * accepted socket.
2251  */
2252 static int
2253 accept_from_daemon (guestfs_h *g)
2254 {
2255   fd_set rset, rset2;
2256
2257   if (g->verbose)
2258     fprintf (stderr,
2259              "accept_from_daemon: %p g->state = %d\n", g, g->state);
2260
2261   FD_ZERO (&rset);
2262
2263   FD_SET (g->fd[1], &rset);     /* Read qemu stdout for log messages & EOF. */
2264   FD_SET (g->sock, &rset);      /* Read socket for accept. */
2265
2266   int max_fd = MAX (g->sock, g->fd[1]);
2267   int sock = -1;
2268
2269   while (sock == -1) {
2270     rset2 = rset;
2271     int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2272     if (r == -1) {
2273       if (errno == EINTR || errno == EAGAIN)
2274         continue;
2275       perrorf (g, "select");
2276       return -1;
2277     }
2278
2279     if (FD_ISSET (g->fd[1], &rset2)) {
2280       if (read_log_message_or_eof (g, g->fd[1]) == -1)
2281         return -1;
2282     }
2283     if (FD_ISSET (g->sock, &rset2)) {
2284       sock = accept (g->sock, NULL, NULL);
2285       if (sock == -1) {
2286         if (errno == EINTR || errno == EAGAIN)
2287           continue;
2288         perrorf (g, "accept");
2289         return -1;
2290       }
2291     }
2292   }
2293
2294   return sock;
2295 }
2296
2297 int
2298 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2299 {
2300   struct guestfs_message_header hdr;
2301   XDR xdr;
2302   u_int32_t len;
2303   int serial = g->msg_next_serial++;
2304   int r;
2305   char *msg_out;
2306   size_t msg_out_size;
2307
2308   if (g->state != BUSY) {
2309     error (g, _("guestfs___send: state %d != BUSY"), g->state);
2310     return -1;
2311   }
2312
2313   /* We have to allocate this message buffer on the heap because
2314    * it is quite large (although will be mostly unused).  We
2315    * can't allocate it on the stack because in some environments
2316    * we have quite limited stack space available, notably when
2317    * running in the JVM.
2318    */
2319   msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2320   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2321
2322   /* Serialize the header. */
2323   hdr.prog = GUESTFS_PROGRAM;
2324   hdr.vers = GUESTFS_PROTOCOL_VERSION;
2325   hdr.proc = proc_nr;
2326   hdr.direction = GUESTFS_DIRECTION_CALL;
2327   hdr.serial = serial;
2328   hdr.status = GUESTFS_STATUS_OK;
2329
2330   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2331     error (g, _("xdr_guestfs_message_header failed"));
2332     goto cleanup1;
2333   }
2334
2335   /* Serialize the args.  If any, because some message types
2336    * have no parameters.
2337    */
2338   if (xdrp) {
2339     if (!(*xdrp) (&xdr, args)) {
2340       error (g, _("dispatch failed to marshal args"));
2341       goto cleanup1;
2342     }
2343   }
2344
2345   /* Get the actual length of the message, resize the buffer to match
2346    * the actual length, and write the length word at the beginning.
2347    */
2348   len = xdr_getpos (&xdr);
2349   xdr_destroy (&xdr);
2350
2351   msg_out = safe_realloc (g, msg_out, len + 4);
2352   msg_out_size = len + 4;
2353
2354   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2355   xdr_uint32_t (&xdr, &len);
2356
2357  again:
2358   r = send_to_daemon (g, msg_out, msg_out_size);
2359   if (r == -2)                  /* Ignore stray daemon cancellations. */
2360     goto again;
2361   if (r == -1)
2362     goto cleanup1;
2363   free (msg_out);
2364
2365   return serial;
2366
2367  cleanup1:
2368   free (msg_out);
2369   return -1;
2370 }
2371
2372 static int cancel = 0; /* XXX Implement file cancellation. */
2373 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2374 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2375 static int send_file_cancellation (guestfs_h *g);
2376 static int send_file_complete (guestfs_h *g);
2377
2378 /* Send a file.
2379  * Returns:
2380  *   0 OK
2381  *   -1 error
2382  *   -2 daemon cancelled (we must read the error message)
2383  */
2384 int
2385 guestfs___send_file (guestfs_h *g, const char *filename)
2386 {
2387   char buf[GUESTFS_MAX_CHUNK_SIZE];
2388   int fd, r, err;
2389
2390   fd = open (filename, O_RDONLY);
2391   if (fd == -1) {
2392     perrorf (g, "open: %s", filename);
2393     send_file_cancellation (g);
2394     /* Daemon sees cancellation and won't reply, so caller can
2395      * just return here.
2396      */
2397     return -1;
2398   }
2399
2400   /* Send file in chunked encoding. */
2401   while (!cancel) {
2402     r = read (fd, buf, sizeof buf);
2403     if (r == -1 && (errno == EINTR || errno == EAGAIN))
2404       continue;
2405     if (r <= 0) break;
2406     err = send_file_data (g, buf, r);
2407     if (err < 0) {
2408       if (err == -2)            /* daemon sent cancellation */
2409         send_file_cancellation (g);
2410       return err;
2411     }
2412   }
2413
2414   if (cancel) {                 /* cancel from either end */
2415     send_file_cancellation (g);
2416     return -1;
2417   }
2418
2419   if (r == -1) {
2420     perrorf (g, "read: %s", filename);
2421     send_file_cancellation (g);
2422     return -1;
2423   }
2424
2425   /* End of file, but before we send that, we need to close
2426    * the file and check for errors.
2427    */
2428   if (close (fd) == -1) {
2429     perrorf (g, "close: %s", filename);
2430     send_file_cancellation (g);
2431     return -1;
2432   }
2433
2434   return send_file_complete (g);
2435 }
2436
2437 /* Send a chunk of file data. */
2438 static int
2439 send_file_data (guestfs_h *g, const char *buf, size_t len)
2440 {
2441   return send_file_chunk (g, 0, buf, len);
2442 }
2443
2444 /* Send a cancellation message. */
2445 static int
2446 send_file_cancellation (guestfs_h *g)
2447 {
2448   return send_file_chunk (g, 1, NULL, 0);
2449 }
2450
2451 /* Send a file complete chunk. */
2452 static int
2453 send_file_complete (guestfs_h *g)
2454 {
2455   char buf[1];
2456   return send_file_chunk (g, 0, buf, 0);
2457 }
2458
2459 static int
2460 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2461 {
2462   u_int32_t len;
2463   int r;
2464   guestfs_chunk chunk;
2465   XDR xdr;
2466   char *msg_out;
2467   size_t msg_out_size;
2468
2469   if (g->state != BUSY) {
2470     error (g, _("send_file_chunk: state %d != READY"), g->state);
2471     return -1;
2472   }
2473
2474   /* Allocate the chunk buffer.  Don't use the stack to avoid
2475    * excessive stack usage and unnecessary copies.
2476    */
2477   msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2478   xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2479
2480   /* Serialize the chunk. */
2481   chunk.cancel = cancel;
2482   chunk.data.data_len = buflen;
2483   chunk.data.data_val = (char *) buf;
2484
2485   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2486     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2487            buf, buflen);
2488     xdr_destroy (&xdr);
2489     goto cleanup1;
2490   }
2491
2492   len = xdr_getpos (&xdr);
2493   xdr_destroy (&xdr);
2494
2495   /* Reduce the size of the outgoing message buffer to the real length. */
2496   msg_out = safe_realloc (g, msg_out, len + 4);
2497   msg_out_size = len + 4;
2498
2499   xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2500   xdr_uint32_t (&xdr, &len);
2501
2502   r = send_to_daemon (g, msg_out, msg_out_size);
2503
2504   /* Did the daemon send a cancellation message? */
2505   if (r == -2) {
2506     if (g->verbose)
2507       fprintf (stderr, "got daemon cancellation\n");
2508     return -2;
2509   }
2510
2511   if (r == -1)
2512     goto cleanup1;
2513
2514   free (msg_out);
2515
2516   return 0;
2517
2518  cleanup1:
2519   free (msg_out);
2520   return -1;
2521 }
2522
2523 /* Receive a reply. */
2524 int
2525 guestfs___recv (guestfs_h *g, const char *fn,
2526                 guestfs_message_header *hdr,
2527                 guestfs_message_error *err,
2528                 xdrproc_t xdrp, char *ret)
2529 {
2530   XDR xdr;
2531   void *buf;
2532   uint32_t size;
2533   int r;
2534
2535  again:
2536   r = recv_from_daemon (g, &size, &buf);
2537   if (r == -1)
2538     return -1;
2539
2540   /* This can happen if a cancellation happens right at the end
2541    * of us sending a FileIn parameter to the daemon.  Discard.  The
2542    * daemon should send us an error message next.
2543    */
2544   if (size == GUESTFS_CANCEL_FLAG)
2545     goto again;
2546
2547   if (size == GUESTFS_LAUNCH_FLAG) {
2548     error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2549     return -1;
2550   }
2551
2552   xdrmem_create (&xdr, buf, size, XDR_DECODE);
2553
2554   if (!xdr_guestfs_message_header (&xdr, hdr)) {
2555     error (g, "%s: failed to parse reply header", fn);
2556     xdr_destroy (&xdr);
2557     free (buf);
2558     return -1;
2559   }
2560   if (hdr->status == GUESTFS_STATUS_ERROR) {
2561     if (!xdr_guestfs_message_error (&xdr, err)) {
2562       error (g, "%s: failed to parse reply error", fn);
2563       xdr_destroy (&xdr);
2564       free (buf);
2565       return -1;
2566     }
2567   } else {
2568     if (xdrp && ret && !xdrp (&xdr, ret)) {
2569       error (g, "%s: failed to parse reply", fn);
2570       xdr_destroy (&xdr);
2571       free (buf);
2572       return -1;
2573     }
2574   }
2575   xdr_destroy (&xdr);
2576   free (buf);
2577
2578   return 0;
2579 }
2580
2581 /* Receive a file. */
2582
2583 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2584 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2585
2586 int
2587 guestfs___recv_file (guestfs_h *g, const char *filename)
2588 {
2589   void *buf;
2590   int fd, r;
2591   size_t len;
2592
2593   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2594   if (fd == -1) {
2595     perrorf (g, "open: %s", filename);
2596     goto cancel;
2597   }
2598
2599   /* Receive the file in chunked encoding. */
2600   while ((r = receive_file_data (g, &buf)) > 0) {
2601     if (xwrite (fd, buf, r) == -1) {
2602       perrorf (g, "%s: write", filename);
2603       free (buf);
2604       goto cancel;
2605     }
2606     free (buf);
2607   }
2608
2609   if (r == -1) {
2610     error (g, _("%s: error in chunked encoding"), filename);
2611     return -1;
2612   }
2613
2614   if (close (fd) == -1) {
2615     perrorf (g, "close: %s", filename);
2616     return -1;
2617   }
2618
2619   return 0;
2620
2621  cancel: ;
2622   /* Send cancellation message to daemon, then wait until it
2623    * cancels (just throwing away data).
2624    */
2625   XDR xdr;
2626   char fbuf[4];
2627   uint32_t flag = GUESTFS_CANCEL_FLAG;
2628
2629   if (g->verbose)
2630     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2631              __func__);
2632
2633   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2634   xdr_uint32_t (&xdr, &flag);
2635   xdr_destroy (&xdr);
2636
2637   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2638     perrorf (g, _("write to daemon socket"));
2639     return -1;
2640   }
2641
2642   while (receive_file_data (g, NULL) > 0)
2643     ;                           /* just discard it */
2644
2645   return -1;
2646 }
2647
2648 /* Receive a chunk of file data. */
2649 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2650 static ssize_t
2651 receive_file_data (guestfs_h *g, void **buf_r)
2652 {
2653   int r;
2654   void *buf;
2655   uint32_t len;
2656   XDR xdr;
2657   guestfs_chunk chunk;
2658
2659   r = recv_from_daemon (g, &len, &buf);
2660   if (r == -1) {
2661     error (g, _("receive_file_data: parse error in reply callback"));
2662     return -1;
2663   }
2664
2665   if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2666     error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2667     return -1;
2668   }
2669
2670   memset (&chunk, 0, sizeof chunk);
2671
2672   xdrmem_create (&xdr, buf, len, XDR_DECODE);
2673   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2674     error (g, _("failed to parse file chunk"));
2675     free (buf);
2676     return -1;
2677   }
2678   xdr_destroy (&xdr);
2679   /* After decoding, the original buffer is no longer used. */
2680   free (buf);
2681
2682   if (chunk.cancel) {
2683     error (g, _("file receive cancelled by daemon"));
2684     free (chunk.data.data_val);
2685     return -1;
2686   }
2687
2688   if (chunk.data.data_len == 0) { /* end of transfer */
2689     free (chunk.data.data_val);
2690     return 0;
2691   }
2692
2693   if (buf_r) *buf_r = chunk.data.data_val;
2694   else free (chunk.data.data_val); /* else caller frees */
2695
2696   return chunk.data.data_len;
2697 }