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