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