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