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