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