Debug: Improve the way the qemu command line is printed.
[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 static void print_cmdline (guestfs_h *g);
870
871 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
872 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
873 static const char *supermin_name =
874   "initramfs." REPO "." host_cpu ".supermin.img";
875 static const char *supermin_hostfiles_name =
876   "initramfs." REPO "." host_cpu ".supermin.hostfiles";
877
878 int
879 guestfs_launch (guestfs_h *g)
880 {
881   const char *tmpdir;
882   char dir_template[PATH_MAX];
883   int r, pmore;
884   size_t len;
885   int wfd[2], rfd[2];
886   int tries;
887   char *path, *pelem, *pend;
888   char *kernel = NULL, *initrd = NULL;
889   char unixsock[256];
890   struct sockaddr_un addr;
891
892 #ifdef P_tmpdir
893   tmpdir = P_tmpdir;
894 #else
895   tmpdir = "/tmp";
896 #endif
897
898   tmpdir = getenv ("TMPDIR") ? : tmpdir;
899   snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
900
901   /* Configured? */
902   if (!g->cmdline) {
903     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
904     return -1;
905   }
906
907   if (g->state != CONFIG) {
908     error (g, _("qemu has already been launched"));
909     return -1;
910   }
911
912   /* Make the temporary directory. */
913   if (!g->tmpdir) {
914     g->tmpdir = safe_strdup (g, dir_template);
915     if (mkdtemp (g->tmpdir) == NULL) {
916       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
917       goto cleanup0;
918     }
919   }
920
921   /* First search g->path for the supermin appliance, and try to
922    * synthesize a kernel and initrd from that.  If it fails, we
923    * try the path search again looking for a backup ordinary
924    * appliance.
925    */
926   pelem = path = safe_strdup (g, g->path);
927   do {
928     pend = strchrnul (pelem, ':');
929     pmore = *pend == ':';
930     *pend = '\0';
931     len = pend - pelem;
932
933     /* Empty element of "." means cwd. */
934     if (len == 0 || (len == 1 && *pelem == '.')) {
935       if (g->verbose)
936         fprintf (stderr,
937                  "looking for supermin appliance in current directory\n");
938       if (dir_contains_files (".",
939                               supermin_name, supermin_hostfiles_name,
940                               "kmod.whitelist", NULL)) {
941         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
942           return -1;
943         break;
944       }
945     }
946     /* Look at <path>/supermin* etc. */
947     else {
948       if (g->verbose)
949         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
950
951       if (dir_contains_files (pelem,
952                               supermin_name, supermin_hostfiles_name,
953                               "kmod.whitelist", NULL)) {
954         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
955           return -1;
956         break;
957       }
958     }
959
960     pelem = pend + 1;
961   } while (pmore);
962
963   free (path);
964
965   if (kernel == NULL || initrd == NULL) {
966     /* Search g->path for the kernel and initrd. */
967     pelem = path = safe_strdup (g, g->path);
968     do {
969       pend = strchrnul (pelem, ':');
970       pmore = *pend == ':';
971       *pend = '\0';
972       len = pend - pelem;
973
974       /* Empty element or "." means cwd. */
975       if (len == 0 || (len == 1 && *pelem == '.')) {
976         if (g->verbose)
977           fprintf (stderr,
978                    "looking for appliance in current directory\n");
979         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
980           kernel = safe_strdup (g, kernel_name);
981           initrd = safe_strdup (g, initrd_name);
982           break;
983         }
984       }
985       /* Look at <path>/kernel etc. */
986       else {
987         if (g->verbose)
988           fprintf (stderr, "looking for appliance in %s\n", pelem);
989
990         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
991           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
992           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
993           sprintf (kernel, "%s/%s", pelem, kernel_name);
994           sprintf (initrd, "%s/%s", pelem, initrd_name);
995           break;
996         }
997       }
998
999       pelem = pend + 1;
1000     } while (pmore);
1001
1002     free (path);
1003   }
1004
1005   if (kernel == NULL || initrd == NULL) {
1006     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1007            kernel_name, initrd_name, g->path);
1008     goto cleanup0;
1009   }
1010
1011   /* Get qemu help text and version. */
1012   if (test_qemu (g) == -1)
1013     goto cleanup0;
1014
1015   /* Make the vmchannel socket. */
1016   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1017   unlink (unixsock);
1018
1019   if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1020     perrorf (g, "pipe");
1021     goto cleanup0;
1022   }
1023
1024   r = fork ();
1025   if (r == -1) {
1026     perrorf (g, "fork");
1027     close (wfd[0]);
1028     close (wfd[1]);
1029     close (rfd[0]);
1030     close (rfd[1]);
1031     goto cleanup0;
1032   }
1033
1034   if (r == 0) {                 /* Child (qemu). */
1035     char vmchannel[256];
1036     char append[256];
1037     char memsize_str[256];
1038
1039     /* Set up the full command line.  Do this in the subprocess so we
1040      * don't need to worry about cleaning up.
1041      */
1042     g->cmdline[0] = g->qemu;
1043
1044 #define LINUX_CMDLINE                                                   \
1045     "panic=1 "         /* force kernel to panic if daemon exits */      \
1046     "console=ttyS0 "   /* serial console */                             \
1047     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
1048     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
1049     "acpi=off "        /* we don't need ACPI, turn it off */            \
1050     "cgroup_disable=memory " /* saves us about 5 MB of RAM */           \
1051     "selinux=0 "       /* SELinux is messed up if there's no policy */
1052
1053     /* Linux kernel command line. */
1054     snprintf (append, sizeof append,
1055               LINUX_CMDLINE "guestfs=%s:%d%s%s%s",
1056               VMCHANNEL_ADDR, VMCHANNEL_PORT,
1057               g->verbose ? " guestfs_verbose=1" : "",
1058               g->append ? " " : "", g->append ? g->append : "");
1059
1060     snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1061
1062     add_cmdline (g, "-m");
1063     add_cmdline (g, memsize_str);
1064     add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1065     add_cmdline (g, "-kernel");
1066     add_cmdline (g, (char *) kernel);
1067     add_cmdline (g, "-initrd");
1068     add_cmdline (g, (char *) initrd);
1069     add_cmdline (g, "-append");
1070     add_cmdline (g, append);
1071     add_cmdline (g, "-nographic");
1072     add_cmdline (g, "-serial");
1073     add_cmdline (g, "stdio");
1074
1075 #if 0
1076     /* Doesn't work.  See:
1077      * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1078      * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1079      */
1080     if (qemu_supports (g, "guestfwd")) {
1081       /* New-style -net user,guestfwd=... syntax for vmchannel.  See:
1082        * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1083        */
1084       snprintf (vmchannel, sizeof vmchannel,
1085                 "user,vlan=0,net=10.0.2.0/8,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1086                 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1087
1088       add_cmdline (g, "-net");
1089       add_cmdline (g, vmchannel);
1090     } else {
1091 #endif
1092       /* Not guestfwd.  HOPEFULLY this qemu uses the older -net channel
1093        * syntax, or if not then we'll get a quick failure.
1094        */
1095       snprintf (vmchannel, sizeof vmchannel,
1096                 "channel,%d:unix:%s,server,nowait",
1097                 VMCHANNEL_PORT, unixsock);
1098
1099       add_cmdline (g, "-net");
1100       add_cmdline (g, vmchannel);
1101       add_cmdline (g, "-net");
1102       add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1103 #if 0
1104     }
1105 #endif
1106     add_cmdline (g, "-net");
1107     add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1108
1109     /* These options recommended by KVM developers to improve reliability. */
1110     if (qemu_supports (g, "-no-hpet"))
1111       add_cmdline (g, "-no-hpet");
1112
1113     if (qemu_supports (g, "-rtc-td-hack"))
1114       add_cmdline (g, "-rtc-td-hack");
1115
1116     /* Finish off the command line. */
1117     incr_cmdline_size (g);
1118     g->cmdline[g->cmdline_size-1] = NULL;
1119
1120     if (g->verbose)
1121       print_cmdline (g);
1122
1123     /* Set up stdin, stdout. */
1124     close (0);
1125     close (1);
1126     close (wfd[1]);
1127     close (rfd[0]);
1128     dup (wfd[0]);
1129     dup (rfd[1]);
1130     close (wfd[0]);
1131     close (rfd[1]);
1132
1133 #if 0
1134     /* Set up a new process group, so we can signal this process
1135      * and all subprocesses (eg. if qemu is really a shell script).
1136      */
1137     setpgid (0, 0);
1138 #endif
1139
1140     execv (g->qemu, g->cmdline); /* Run qemu. */
1141     perror (g->qemu);
1142     _exit (1);
1143   }
1144
1145   /* Parent (library). */
1146   g->pid = r;
1147
1148   free (kernel);
1149   kernel = NULL;
1150   free (initrd);
1151   initrd = NULL;
1152
1153   /* Fork the recovery process off which will kill qemu if the parent
1154    * process fails to do so (eg. if the parent segfaults).
1155    */
1156   r = fork ();
1157   if (r == 0) {
1158     pid_t qemu_pid = g->pid;
1159     pid_t parent_pid = getppid ();
1160
1161     /* Writing to argv is hideously complicated and error prone.  See:
1162      * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1163      */
1164
1165     /* Loop around waiting for one or both of the other processes to
1166      * disappear.  It's fair to say this is very hairy.  The PIDs that
1167      * we are looking at might be reused by another process.  We are
1168      * effectively polling.  Is the cure worse than the disease?
1169      */
1170     for (;;) {
1171       if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1172         _exit (0);
1173       if (kill (parent_pid, 0) == -1) {
1174         /* Parent's gone away, qemu still around, so kill qemu. */
1175         kill (qemu_pid, 9);
1176         _exit (0);
1177       }
1178       sleep (2);
1179     }
1180   }
1181
1182   /* Don't worry, if the fork failed, this will be -1.  The recovery
1183    * process isn't essential.
1184    */
1185   g->recoverypid = r;
1186
1187   /* Start the clock ... */
1188   time (&g->start_t);
1189
1190   /* Close the other ends of the pipe. */
1191   close (wfd[0]);
1192   close (rfd[1]);
1193
1194   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1195       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1196     perrorf (g, "fcntl");
1197     goto cleanup1;
1198   }
1199
1200   g->fd[0] = wfd[1];            /* stdin of child */
1201   g->fd[1] = rfd[0];            /* stdout of child */
1202
1203   /* Open the Unix socket.  The vmchannel implementation that got
1204    * merged with qemu sucks in a number of ways.  Both ends do
1205    * connect(2), which means that no one knows what, if anything, is
1206    * connected to the other end, or if it becomes disconnected.  Even
1207    * worse, we have to wait some indeterminate time for qemu to create
1208    * the socket and connect to it (which happens very early in qemu's
1209    * start-up), so any code that uses vmchannel is inherently racy.
1210    * Hence this silly loop.
1211    */
1212   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1213   if (g->sock == -1) {
1214     perrorf (g, "socket");
1215     goto cleanup1;
1216   }
1217
1218   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1219     perrorf (g, "fcntl");
1220     goto cleanup2;
1221   }
1222
1223   addr.sun_family = AF_UNIX;
1224   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1225   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1226
1227   tries = 100;
1228   /* Always sleep at least once to give qemu a small chance to start up. */
1229   usleep (10000);
1230   while (tries > 0) {
1231     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1232     if ((r == -1 && errno == EINPROGRESS) || r == 0)
1233       goto connected;
1234
1235     if (errno != ENOENT)
1236       perrorf (g, "connect");
1237     tries--;
1238     usleep (100000);
1239   }
1240
1241   error (g, _("failed to connect to vmchannel socket"));
1242   goto cleanup2;
1243
1244  connected:
1245   /* Watch the file descriptors. */
1246   free (g->msg_in);
1247   g->msg_in = NULL;
1248   g->msg_in_size = g->msg_in_allocated = 0;
1249
1250   free (g->msg_out);
1251   g->msg_out = NULL;
1252   g->msg_out_size = 0;
1253   g->msg_out_pos = 0;
1254
1255   g->stdout_watch =
1256     g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1257                               GUESTFS_HANDLE_READABLE,
1258                               stdout_event, NULL);
1259   if (g->stdout_watch == -1) {
1260     error (g, _("could not watch qemu stdout"));
1261     goto cleanup3;
1262   }
1263
1264   if (guestfs__switch_to_receiving (g) == -1)
1265     goto cleanup3;
1266
1267   g->state = LAUNCHING;
1268   return 0;
1269
1270  cleanup3:
1271   if (g->stdout_watch >= 0)
1272     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1273   if (g->sock_watch >= 0)
1274     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1275
1276  cleanup2:
1277   close (g->sock);
1278
1279  cleanup1:
1280   close (wfd[1]);
1281   close (rfd[0]);
1282   kill (g->pid, 9);
1283   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1284   waitpid (g->pid, NULL, 0);
1285   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1286   g->fd[0] = -1;
1287   g->fd[1] = -1;
1288   g->sock = -1;
1289   g->pid = 0;
1290   g->recoverypid = 0;
1291   g->start_t = 0;
1292   g->stdout_watch = -1;
1293   g->sock_watch = -1;
1294
1295  cleanup0:
1296   free (kernel);
1297   free (initrd);
1298   return -1;
1299 }
1300
1301 /* This function is used to print the qemu command line before it gets
1302  * executed, when in verbose mode.
1303  */
1304 static void
1305 print_cmdline (guestfs_h *g)
1306 {
1307   int i = 0;
1308   int needs_quote;
1309
1310   while (g->cmdline[i]) {
1311     if (g->cmdline[i][0] == '-') /* -option starts a new line */
1312       fprintf (stderr, " \\\n   ");
1313
1314     if (i > 0) fputc (' ', stderr);
1315
1316     /* Does it need shell quoting?  This only deals with simple cases. */
1317     needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1318
1319     if (needs_quote) fputc ('\'', stderr);
1320     fprintf (stderr, "%s", g->cmdline[i]);
1321     if (needs_quote) fputc ('\'', stderr);
1322     i++;
1323   }
1324
1325   fputc ('\n', stderr);
1326 }
1327
1328 /* This function does the hard work of building the supermin appliance
1329  * on the fly.  'path' is the directory containing the control files.
1330  * 'kernel' and 'initrd' are where we will return the names of the
1331  * kernel and initrd (only initrd is built).  The work is done by
1332  * an external script.  We just tell it where to put the result.
1333  */
1334 static int
1335 build_supermin_appliance (guestfs_h *g, const char *path,
1336                           char **kernel, char **initrd)
1337 {
1338   char cmd[4096];
1339   int r, len;
1340
1341   len = strlen (g->tmpdir);
1342   *kernel = safe_malloc (g, len + 8);
1343   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1344   *initrd = safe_malloc (g, len + 8);
1345   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1346
1347   snprintf (cmd, sizeof cmd,
1348             "PATH='%s':$PATH "
1349             "libguestfs-supermin-helper '%s' %s %s",
1350             path,
1351             path, *kernel, *initrd);
1352
1353   r = system (cmd);
1354   if (r == -1 || WEXITSTATUS(r) != 0) {
1355     error (g, _("external command failed: %s"), cmd);
1356     free (*kernel);
1357     free (*initrd);
1358     *kernel = *initrd = NULL;
1359     return -1;
1360   }
1361
1362   return 0;
1363 }
1364
1365 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1366
1367 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1368  * 'qemu -version' so we know what options this qemu supports and
1369  * the version.
1370  */
1371 static int
1372 test_qemu (guestfs_h *g)
1373 {
1374   char cmd[1024];
1375   FILE *fp;
1376
1377   free (g->qemu_help);
1378   free (g->qemu_version);
1379   g->qemu_help = NULL;
1380   g->qemu_version = NULL;
1381
1382   snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1383
1384   fp = popen (cmd, "r");
1385   /* qemu -help should always work (qemu -version OTOH wasn't
1386    * supported by qemu 0.9).  If this command doesn't work then it
1387    * probably indicates that the qemu binary is missing.
1388    */
1389   if (!fp) {
1390     /* XXX This error is never printed, even if the qemu binary
1391      * doesn't exist.  Why?
1392      */
1393   error:
1394     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1395     return -1;
1396   }
1397
1398   if (read_all (g, fp, &g->qemu_help) == -1)
1399     goto error;
1400
1401   if (pclose (fp) == -1)
1402     goto error;
1403
1404   snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1405
1406   fp = popen (cmd, "r");
1407   if (fp) {
1408     /* Intentionally ignore errors. */
1409     read_all (g, fp, &g->qemu_version);
1410     pclose (fp);
1411   }
1412
1413   return 0;
1414 }
1415
1416 static int
1417 read_all (guestfs_h *g, FILE *fp, char **ret)
1418 {
1419   int r, n = 0;
1420   char *p;
1421
1422  again:
1423   if (feof (fp)) {
1424     *ret = safe_realloc (g, *ret, n + 1);
1425     (*ret)[n] = '\0';
1426     return n;
1427   }
1428
1429   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1430   p = &(*ret)[n];
1431   r = fread (p, 1, BUFSIZ, fp);
1432   if (ferror (fp)) {
1433     perrorf (g, "read");
1434     return -1;
1435   }
1436   n += r;
1437   goto again;
1438 }
1439
1440 /* Test if option is supported by qemu command line (just by grepping
1441  * the help text).
1442  */
1443 static int
1444 qemu_supports (guestfs_h *g, const char *option)
1445 {
1446   return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1447 }
1448
1449 static void
1450 finish_wait_ready (guestfs_h *g, void *vp)
1451 {
1452   if (g->verbose)
1453     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1454
1455   *((int *)vp) = 1;
1456   g->main_loop->main_loop_quit (g->main_loop, g);
1457 }
1458
1459 int
1460 guestfs_wait_ready (guestfs_h *g)
1461 {
1462   int finished = 0, r;
1463
1464   if (g->state == READY) return 0;
1465
1466   if (g->state == BUSY) {
1467     error (g, _("qemu has finished launching already"));
1468     return -1;
1469   }
1470
1471   if (g->state != LAUNCHING) {
1472     error (g, _("qemu has not been launched yet"));
1473     return -1;
1474   }
1475
1476   g->launch_done_cb = finish_wait_ready;
1477   g->launch_done_cb_data = &finished;
1478   r = g->main_loop->main_loop_run (g->main_loop, g);
1479   g->launch_done_cb = NULL;
1480   g->launch_done_cb_data = NULL;
1481
1482   if (r == -1) return -1;
1483
1484   if (finished != 1) {
1485     error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1486     return -1;
1487   }
1488
1489   /* This is possible in some really strange situations, such as
1490    * guestfsd starts up OK but then qemu immediately exits.  Check for
1491    * it because the caller is probably expecting to be able to send
1492    * commands after this function returns.
1493    */
1494   if (g->state != READY) {
1495     error (g, _("qemu launched and contacted daemon, but state != READY"));
1496     return -1;
1497   }
1498
1499   return 0;
1500 }
1501
1502 int
1503 guestfs_kill_subprocess (guestfs_h *g)
1504 {
1505   if (g->state == CONFIG) {
1506     error (g, _("no subprocess to kill"));
1507     return -1;
1508   }
1509
1510   if (g->verbose)
1511     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1512
1513   kill (g->pid, SIGTERM);
1514   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1515
1516   return 0;
1517 }
1518
1519 /* Access current state. */
1520 int
1521 guestfs_is_config (guestfs_h *g)
1522 {
1523   return g->state == CONFIG;
1524 }
1525
1526 int
1527 guestfs_is_launching (guestfs_h *g)
1528 {
1529   return g->state == LAUNCHING;
1530 }
1531
1532 int
1533 guestfs_is_ready (guestfs_h *g)
1534 {
1535   return g->state == READY;
1536 }
1537
1538 int
1539 guestfs_is_busy (guestfs_h *g)
1540 {
1541   return g->state == BUSY;
1542 }
1543
1544 int
1545 guestfs_get_state (guestfs_h *g)
1546 {
1547   return g->state;
1548 }
1549
1550 int
1551 guestfs_set_ready (guestfs_h *g)
1552 {
1553   if (g->state != BUSY) {
1554     error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1555            g->state);
1556     return -1;
1557   }
1558   g->state = READY;
1559   return 0;
1560 }
1561
1562 int
1563 guestfs_set_busy (guestfs_h *g)
1564 {
1565   if (g->state != READY) {
1566     error (g, _("guestfs_set_busy: called when in state %d != READY"),
1567            g->state);
1568     return -1;
1569   }
1570   g->state = BUSY;
1571   return 0;
1572 }
1573
1574 int
1575 guestfs_end_busy (guestfs_h *g)
1576 {
1577   switch (g->state)
1578     {
1579     case BUSY:
1580       g->state = READY;
1581       break;
1582     case CONFIG:
1583     case READY:
1584       break;
1585     case LAUNCHING:
1586     case NO_HANDLE:
1587       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1588       return -1;
1589     }
1590   return 0;
1591 }
1592
1593 /* We don't know if stdout_event or sock_read_event will be the
1594  * first to receive EOF if the qemu process dies.  This function
1595  * has the common cleanup code for both.
1596  */
1597 static void
1598 child_cleanup (guestfs_h *g)
1599 {
1600   if (g->verbose)
1601     fprintf (stderr, "stdout_event: %p: child process died\n", g);
1602   /*kill (g->pid, SIGTERM);*/
1603   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1604   waitpid (g->pid, NULL, 0);
1605   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1606   if (g->stdout_watch >= 0)
1607     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1608   if (g->sock_watch >= 0)
1609     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1610   close (g->fd[0]);
1611   close (g->fd[1]);
1612   close (g->sock);
1613   g->fd[0] = -1;
1614   g->fd[1] = -1;
1615   g->sock = -1;
1616   g->pid = 0;
1617   g->recoverypid = 0;
1618   g->start_t = 0;
1619   g->stdout_watch = -1;
1620   g->sock_watch = -1;
1621   g->state = CONFIG;
1622   if (g->subprocess_quit_cb)
1623     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1624 }
1625
1626 /* This function is called whenever qemu prints something on stdout.
1627  * Qemu's stdout is also connected to the guest's serial console, so
1628  * we see kernel messages here too.
1629  */
1630 static void
1631 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1632               int watch, int fd, int events)
1633 {
1634   char buf[4096];
1635   int n;
1636
1637 #if 0
1638   if (g->verbose)
1639     fprintf (stderr,
1640              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1641              g, g->state, fd, events);
1642 #endif
1643
1644   if (g->fd[1] != fd) {
1645     error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1646     return;
1647   }
1648
1649   n = read (fd, buf, sizeof buf);
1650   if (n == 0) {
1651     /* Hopefully this indicates the qemu child process has died. */
1652     child_cleanup (g);
1653     return;
1654   }
1655
1656   if (n == -1) {
1657     if (errno != EINTR && errno != EAGAIN)
1658       perrorf (g, "read");
1659     return;
1660   }
1661
1662   /* In verbose mode, copy all log messages to stderr. */
1663   if (g->verbose)
1664     write (2, buf, n);
1665
1666   /* It's an actual log message, send it upwards if anyone is listening. */
1667   if (g->log_message_cb)
1668     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1669 }
1670
1671 /* The function is called whenever we can read something on the
1672  * guestfsd (daemon inside the guest) communication socket.
1673  */
1674 static void
1675 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1676                  int watch, int fd, int events)
1677 {
1678   XDR xdr;
1679   u_int32_t len;
1680   int n;
1681
1682   if (g->verbose)
1683     fprintf (stderr,
1684              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1685              g, g->state, fd, events);
1686
1687   if (g->sock != fd) {
1688     error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1689     return;
1690   }
1691
1692   if (g->msg_in_size <= g->msg_in_allocated) {
1693     g->msg_in_allocated += 4096;
1694     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1695   }
1696   n = read (g->sock, g->msg_in + g->msg_in_size,
1697             g->msg_in_allocated - g->msg_in_size);
1698   if (n == 0) {
1699     /* Disconnected. */
1700     child_cleanup (g);
1701     return;
1702   }
1703
1704   if (n == -1) {
1705     if (errno != EINTR && errno != EAGAIN)
1706       perrorf (g, "read");
1707     return;
1708   }
1709
1710   g->msg_in_size += n;
1711
1712   /* Have we got enough of a message to be able to process it yet? */
1713  again:
1714   if (g->msg_in_size < 4) return;
1715
1716   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1717   if (!xdr_uint32_t (&xdr, &len)) {
1718     error (g, _("can't decode length word"));
1719     goto cleanup;
1720   }
1721
1722   /* Length is normally the length of the message, but when guestfsd
1723    * starts up it sends a "magic" value (longer than any possible
1724    * message).  Check for this.
1725    */
1726   if (len == GUESTFS_LAUNCH_FLAG) {
1727     if (g->state != LAUNCHING)
1728       error (g, _("received magic signature from guestfsd, but in state %d"),
1729              g->state);
1730     else if (g->msg_in_size != 4)
1731       error (g, _("received magic signature from guestfsd, but msg size is %d"),
1732              g->msg_in_size);
1733     else {
1734       g->state = READY;
1735       if (g->launch_done_cb)
1736         g->launch_done_cb (g, g->launch_done_cb_data);
1737     }
1738
1739     goto cleanup;
1740   }
1741
1742   /* This can happen if a cancellation happens right at the end
1743    * of us sending a FileIn parameter to the daemon.  Discard.  The
1744    * daemon should send us an error message next.
1745    */
1746   if (len == GUESTFS_CANCEL_FLAG) {
1747     g->msg_in_size -= 4;
1748     memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1749     goto again;
1750   }
1751
1752   /* If this happens, it's pretty bad and we've probably lost
1753    * synchronization.
1754    */
1755   if (len > GUESTFS_MESSAGE_MAX) {
1756     error (g, _("message length (%u) > maximum possible size (%d)"),
1757            len, GUESTFS_MESSAGE_MAX);
1758     goto cleanup;
1759   }
1760
1761   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1762
1763   /* Got the full message, begin processing it. */
1764 #if 0
1765   if (g->verbose) {
1766     int i, j;
1767
1768     for (i = 0; i < g->msg_in_size; i += 16) {
1769       printf ("%04x: ", i);
1770       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1771         printf ("%02x ", (unsigned char) g->msg_in[j]);
1772       for (; j < i+16; ++j)
1773         printf ("   ");
1774       printf ("|");
1775       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1776         if (isprint (g->msg_in[j]))
1777           printf ("%c", g->msg_in[j]);
1778         else
1779           printf (".");
1780       for (; j < i+16; ++j)
1781         printf (" ");
1782       printf ("|\n");
1783     }
1784   }
1785 #endif
1786
1787   /* Not in the expected state. */
1788   if (g->state != BUSY)
1789     error (g, _("state %d != BUSY"), g->state);
1790
1791   /* Push the message up to the higher layer. */
1792   if (g->reply_cb)
1793     g->reply_cb (g, g->reply_cb_data, &xdr);
1794   else
1795     /* This message (probably) should never be printed. */
1796     fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1797
1798   g->msg_in_size -= len + 4;
1799   memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1800   if (g->msg_in_size > 0) goto again;
1801
1802  cleanup:
1803   /* Free the message buffer if it's grown excessively large. */
1804   if (g->msg_in_allocated > 65536) {
1805     free (g->msg_in);
1806     g->msg_in = NULL;
1807     g->msg_in_size = g->msg_in_allocated = 0;
1808   } else
1809     g->msg_in_size = 0;
1810
1811   xdr_destroy (&xdr);
1812 }
1813
1814 /* The function is called whenever we can write something on the
1815  * guestfsd (daemon inside the guest) communication socket.
1816  */
1817 static void
1818 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1819                   int watch, int fd, int events)
1820 {
1821   int n, err;
1822
1823   if (g->verbose)
1824     fprintf (stderr,
1825              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1826              g, g->state, fd, events);
1827
1828   if (g->sock != fd) {
1829     error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1830     return;
1831   }
1832
1833   if (g->state != BUSY) {
1834     error (g, _("sock_write_event: state %d != BUSY"), g->state);
1835     return;
1836   }
1837
1838   if (g->verbose)
1839     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1840              g->msg_out_size - g->msg_out_pos);
1841
1842   n = write (g->sock, g->msg_out + g->msg_out_pos,
1843              g->msg_out_size - g->msg_out_pos);
1844   if (n == -1) {
1845     err = errno;
1846     if (err != EAGAIN)
1847       perrorf (g, "write");
1848     if (err == EPIPE)   /* Disconnected from guest (RHBZ#508713). */
1849       child_cleanup (g);
1850     return;
1851   }
1852
1853   if (g->verbose)
1854     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1855
1856   g->msg_out_pos += n;
1857
1858   /* More to write? */
1859   if (g->msg_out_pos < g->msg_out_size)
1860     return;
1861
1862   if (g->verbose)
1863     fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1864
1865   free (g->msg_out);
1866   g->msg_out = NULL;
1867   g->msg_out_pos = g->msg_out_size = 0;
1868
1869   /* Done writing, call the higher layer. */
1870   if (g->send_cb)
1871     g->send_cb (g, g->send_cb_data);
1872 }
1873
1874 void
1875 guestfs_set_send_callback (guestfs_h *g,
1876                            guestfs_send_cb cb, void *opaque)
1877 {
1878   g->send_cb = cb;
1879   g->send_cb_data = opaque;
1880 }
1881
1882 void
1883 guestfs_set_reply_callback (guestfs_h *g,
1884                             guestfs_reply_cb cb, void *opaque)
1885 {
1886   g->reply_cb = cb;
1887   g->reply_cb_data = opaque;
1888 }
1889
1890 void
1891 guestfs_set_log_message_callback (guestfs_h *g,
1892                                   guestfs_log_message_cb cb, void *opaque)
1893 {
1894   g->log_message_cb = cb;
1895   g->log_message_cb_data = opaque;
1896 }
1897
1898 void
1899 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1900                                       guestfs_subprocess_quit_cb cb, void *opaque)
1901 {
1902   g->subprocess_quit_cb = cb;
1903   g->subprocess_quit_cb_data = opaque;
1904 }
1905
1906 void
1907 guestfs_set_launch_done_callback (guestfs_h *g,
1908                                   guestfs_launch_done_cb cb, void *opaque)
1909 {
1910   g->launch_done_cb = cb;
1911   g->launch_done_cb_data = opaque;
1912 }
1913
1914 /* Access to the handle's main loop and the default main loop. */
1915 void
1916 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1917 {
1918   g->main_loop = main_loop;
1919 }
1920
1921 guestfs_main_loop *
1922 guestfs_get_main_loop (guestfs_h *g)
1923 {
1924   return g->main_loop;
1925 }
1926
1927 guestfs_main_loop *
1928 guestfs_get_default_main_loop (void)
1929 {
1930   return (guestfs_main_loop *) &default_main_loop;
1931 }
1932
1933 /* Change the daemon socket handler so that we are now writing.
1934  * This sets the handle to sock_write_event.
1935  */
1936 int
1937 guestfs__switch_to_sending (guestfs_h *g)
1938 {
1939   if (g->sock_watch >= 0) {
1940     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1941       error (g, _("remove_handle failed"));
1942       g->sock_watch = -1;
1943       return -1;
1944     }
1945   }
1946
1947   g->sock_watch =
1948     g->main_loop->add_handle (g->main_loop, g, g->sock,
1949                               GUESTFS_HANDLE_WRITABLE,
1950                               sock_write_event, NULL);
1951   if (g->sock_watch == -1) {
1952     error (g, _("add_handle failed"));
1953     return -1;
1954   }
1955
1956   return 0;
1957 }
1958
1959 int
1960 guestfs__switch_to_receiving (guestfs_h *g)
1961 {
1962   if (g->sock_watch >= 0) {
1963     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1964       error (g, _("remove_handle failed"));
1965       g->sock_watch = -1;
1966       return -1;
1967     }
1968   }
1969
1970   g->sock_watch =
1971     g->main_loop->add_handle (g->main_loop, g, g->sock,
1972                               GUESTFS_HANDLE_READABLE,
1973                               sock_read_event, NULL);
1974   if (g->sock_watch == -1) {
1975     error (g, _("add_handle failed"));
1976     return -1;
1977   }
1978
1979   return 0;
1980 }
1981
1982 /* Dispatch a call (len + header + args) to the remote daemon,
1983  * synchronously (ie. using the guest's main loop to wait until
1984  * it has been sent).  Returns -1 for error, or the serial
1985  * number of the message.
1986  */
1987 static void
1988 send_cb (guestfs_h *g, void *data)
1989 {
1990   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1991
1992   *((int *)data) = 1;
1993   ml->main_loop_quit (ml, g);
1994 }
1995
1996 int
1997 guestfs__send_sync (guestfs_h *g, int proc_nr,
1998                     xdrproc_t xdrp, char *args)
1999 {
2000   struct guestfs_message_header hdr;
2001   XDR xdr;
2002   u_int32_t len;
2003   int serial = g->msg_next_serial++;
2004   int sent;
2005   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2006
2007   if (g->state != BUSY) {
2008     error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
2009     return -1;
2010   }
2011
2012   /* This is probably an internal error.  Or perhaps we should just
2013    * free the buffer anyway?
2014    */
2015   if (g->msg_out != NULL) {
2016     error (g, _("guestfs__send_sync: msg_out should be NULL"));
2017     return -1;
2018   }
2019
2020   /* We have to allocate this message buffer on the heap because
2021    * it is quite large (although will be mostly unused).  We
2022    * can't allocate it on the stack because in some environments
2023    * we have quite limited stack space available, notably when
2024    * running in the JVM.
2025    */
2026   g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2027   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2028
2029   /* Serialize the header. */
2030   hdr.prog = GUESTFS_PROGRAM;
2031   hdr.vers = GUESTFS_PROTOCOL_VERSION;
2032   hdr.proc = proc_nr;
2033   hdr.direction = GUESTFS_DIRECTION_CALL;
2034   hdr.serial = serial;
2035   hdr.status = GUESTFS_STATUS_OK;
2036
2037   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2038     error (g, _("xdr_guestfs_message_header failed"));
2039     goto cleanup1;
2040   }
2041
2042   /* Serialize the args.  If any, because some message types
2043    * have no parameters.
2044    */
2045   if (xdrp) {
2046     if (!(*xdrp) (&xdr, args)) {
2047       error (g, _("dispatch failed to marshal args"));
2048       goto cleanup1;
2049     }
2050   }
2051
2052   /* Get the actual length of the message, resize the buffer to match
2053    * the actual length, and write the length word at the beginning.
2054    */
2055   len = xdr_getpos (&xdr);
2056   xdr_destroy (&xdr);
2057
2058   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2059   g->msg_out_size = len + 4;
2060   g->msg_out_pos = 0;
2061
2062   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2063   xdr_uint32_t (&xdr, &len);
2064
2065   if (guestfs__switch_to_sending (g) == -1)
2066     goto cleanup1;
2067
2068   sent = 0;
2069   guestfs_set_send_callback (g, send_cb, &sent);
2070   if (ml->main_loop_run (ml, g) == -1)
2071     goto cleanup1;
2072   if (sent != 1) {
2073     error (g, _("send failed, see earlier error messages"));
2074     goto cleanup1;
2075   }
2076
2077   return serial;
2078
2079  cleanup1:
2080   free (g->msg_out);
2081   g->msg_out = NULL;
2082   g->msg_out_size = 0;
2083   return -1;
2084 }
2085
2086 static int cancel = 0; /* XXX Implement file cancellation. */
2087 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2088 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2089 static int send_file_cancellation_sync (guestfs_h *g);
2090 static int send_file_complete_sync (guestfs_h *g);
2091
2092 /* Synchronously send a file.
2093  * Returns:
2094  *   0 OK
2095  *   -1 error
2096  *   -2 daemon cancelled (we must read the error message)
2097  */
2098 int
2099 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2100 {
2101   char buf[GUESTFS_MAX_CHUNK_SIZE];
2102   int fd, r, err;
2103
2104   fd = open (filename, O_RDONLY);
2105   if (fd == -1) {
2106     perrorf (g, "open: %s", filename);
2107     send_file_cancellation_sync (g);
2108     /* Daemon sees cancellation and won't reply, so caller can
2109      * just return here.
2110      */
2111     return -1;
2112   }
2113
2114   /* Send file in chunked encoding. */
2115   while (!cancel) {
2116     r = read (fd, buf, sizeof buf);
2117     if (r == -1 && (errno == EINTR || errno == EAGAIN))
2118       continue;
2119     if (r <= 0) break;
2120     err = send_file_data_sync (g, buf, r);
2121     if (err < 0) {
2122       if (err == -2)            /* daemon sent cancellation */
2123         send_file_cancellation_sync (g);
2124       return err;
2125     }
2126   }
2127
2128   if (cancel) {                 /* cancel from either end */
2129     send_file_cancellation_sync (g);
2130     return -1;
2131   }
2132
2133   if (r == -1) {
2134     perrorf (g, "read: %s", filename);
2135     send_file_cancellation_sync (g);
2136     return -1;
2137   }
2138
2139   /* End of file, but before we send that, we need to close
2140    * the file and check for errors.
2141    */
2142   if (close (fd) == -1) {
2143     perrorf (g, "close: %s", filename);
2144     send_file_cancellation_sync (g);
2145     return -1;
2146   }
2147
2148   return send_file_complete_sync (g);
2149 }
2150
2151 /* Send a chunk of file data. */
2152 static int
2153 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2154 {
2155   return send_file_chunk_sync (g, 0, buf, len);
2156 }
2157
2158 /* Send a cancellation message. */
2159 static int
2160 send_file_cancellation_sync (guestfs_h *g)
2161 {
2162   return send_file_chunk_sync (g, 1, NULL, 0);
2163 }
2164
2165 /* Send a file complete chunk. */
2166 static int
2167 send_file_complete_sync (guestfs_h *g)
2168 {
2169   char buf[1];
2170   return send_file_chunk_sync (g, 0, buf, 0);
2171 }
2172
2173 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2174  * for it to go).
2175  */
2176 static int check_for_daemon_cancellation (guestfs_h *g);
2177
2178 static int
2179 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2180 {
2181   u_int32_t len;
2182   int sent;
2183   guestfs_chunk chunk;
2184   XDR xdr;
2185   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2186
2187   if (g->state != BUSY) {
2188     error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2189     return -1;
2190   }
2191
2192   /* This is probably an internal error.  Or perhaps we should just
2193    * free the buffer anyway?
2194    */
2195   if (g->msg_out != NULL) {
2196     error (g, _("guestfs__send_sync: msg_out should be NULL"));
2197     return -1;
2198   }
2199
2200   /* Did the daemon send a cancellation message? */
2201   if (check_for_daemon_cancellation (g)) {
2202     if (g->verbose)
2203       fprintf (stderr, "got daemon cancellation\n");
2204     return -2;
2205   }
2206
2207   /* Allocate the chunk buffer.  Don't use the stack to avoid
2208    * excessive stack usage and unnecessary copies.
2209    */
2210   g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2211   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2212
2213   /* Serialize the chunk. */
2214   chunk.cancel = cancel;
2215   chunk.data.data_len = buflen;
2216   chunk.data.data_val = (char *) buf;
2217
2218   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2219     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2220            buf, buflen);
2221     xdr_destroy (&xdr);
2222     goto cleanup1;
2223   }
2224
2225   len = xdr_getpos (&xdr);
2226   xdr_destroy (&xdr);
2227
2228   /* Reduce the size of the outgoing message buffer to the real length. */
2229   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2230   g->msg_out_size = len + 4;
2231   g->msg_out_pos = 0;
2232
2233   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2234   xdr_uint32_t (&xdr, &len);
2235
2236   if (guestfs__switch_to_sending (g) == -1)
2237     goto cleanup1;
2238
2239   sent = 0;
2240   guestfs_set_send_callback (g, send_cb, &sent);
2241   if (ml->main_loop_run (ml, g) == -1)
2242     goto cleanup1;
2243   if (sent != 1) {
2244     error (g, _("send file chunk failed, see earlier error messages"));
2245     goto cleanup1;
2246   }
2247
2248   return 0;
2249
2250  cleanup1:
2251   free (g->msg_out);
2252   g->msg_out = NULL;
2253   g->msg_out_size = 0;
2254   return -1;
2255 }
2256
2257 /* At this point we are sending FileIn file(s) to the guest, and not
2258  * expecting to read anything, so if we do read anything, it must be
2259  * a cancellation message.  This checks for this case without blocking.
2260  */
2261 static int
2262 check_for_daemon_cancellation (guestfs_h *g)
2263 {
2264   fd_set rset;
2265   struct timeval tv;
2266   int r;
2267   char buf[4];
2268   uint32_t flag;
2269   XDR xdr;
2270
2271   FD_ZERO (&rset);
2272   FD_SET (g->sock, &rset);
2273   tv.tv_sec = 0;
2274   tv.tv_usec = 0;
2275   r = select (g->sock+1, &rset, NULL, NULL, &tv);
2276   if (r == -1) {
2277     perrorf (g, "select");
2278     return 0;
2279   }
2280   if (r == 0)
2281     return 0;
2282
2283   /* Read the message from the daemon. */
2284   r = xread (g->sock, buf, sizeof buf);
2285   if (r == -1) {
2286     perrorf (g, "read");
2287     return 0;
2288   }
2289
2290   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2291   xdr_uint32_t (&xdr, &flag);
2292   xdr_destroy (&xdr);
2293
2294   if (flag != GUESTFS_CANCEL_FLAG) {
2295     error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2296            flag, GUESTFS_CANCEL_FLAG);
2297     return 0;
2298   }
2299
2300   return 1;
2301 }
2302
2303 /* Synchronously receive a file. */
2304
2305 /* Returns -1 = error, 0 = EOF, 1 = more data */
2306 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2307
2308 int
2309 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2310 {
2311   void *buf;
2312   int fd, r;
2313   size_t len;
2314
2315   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2316   if (fd == -1) {
2317     perrorf (g, "open: %s", filename);
2318     goto cancel;
2319   }
2320
2321   /* Receive the file in chunked encoding. */
2322   while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2323     if (xwrite (fd, buf, len) == -1) {
2324       perrorf (g, "%s: write", filename);
2325       free (buf);
2326       goto cancel;
2327     }
2328     free (buf);
2329     if (r == 0) break; /* End of file. */
2330   }
2331
2332   if (r == -1) {
2333     error (g, _("%s: error in chunked encoding"), filename);
2334     return -1;
2335   }
2336
2337   if (close (fd) == -1) {
2338     perrorf (g, "close: %s", filename);
2339     return -1;
2340   }
2341
2342   return 0;
2343
2344  cancel: ;
2345   /* Send cancellation message to daemon, then wait until it
2346    * cancels (just throwing away data).
2347    */
2348   XDR xdr;
2349   char fbuf[4];
2350   uint32_t flag = GUESTFS_CANCEL_FLAG;
2351
2352   if (g->verbose)
2353     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2354              __func__);
2355
2356   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2357   xdr_uint32_t (&xdr, &flag);
2358   xdr_destroy (&xdr);
2359
2360   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2361     perrorf (g, _("write to daemon socket"));
2362     return -1;
2363   }
2364
2365   while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2366     ;                           /* just discard it */
2367
2368   return -1;
2369 }
2370
2371 /* Note that the reply callback can be called multiple times before
2372  * the main loop quits and we get back to the synchronous code.  So
2373  * we have to be prepared to save multiple chunks on a list here.
2374  */
2375 struct receive_file_ctx {
2376   int count;                    /* 0 if receive_file_cb not called, or
2377                                  * else count number of chunks.
2378                                  */
2379   guestfs_chunk *chunks;        /* Array of chunks. */
2380 };
2381
2382 static void
2383 free_chunks (struct receive_file_ctx *ctx)
2384 {
2385   int i;
2386
2387   for (i = 0; i < ctx->count; ++i)
2388     free (ctx->chunks[i].data.data_val);
2389
2390   free (ctx->chunks);
2391 }
2392
2393 static void
2394 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2395 {
2396   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2397   struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2398   guestfs_chunk chunk;
2399
2400   if (ctx->count == -1)         /* Parse error occurred previously. */
2401     return;
2402
2403   ml->main_loop_quit (ml, g);
2404
2405   memset (&chunk, 0, sizeof chunk);
2406
2407   if (!xdr_guestfs_chunk (xdr, &chunk)) {
2408     error (g, _("failed to parse file chunk"));
2409     free_chunks (ctx);
2410     ctx->chunks = NULL;
2411     ctx->count = -1;
2412     return;
2413   }
2414
2415   /* Copy the chunk to the list. */
2416   ctx->chunks = safe_realloc (g, ctx->chunks,
2417                               sizeof (guestfs_chunk) * (ctx->count+1));
2418   ctx->chunks[ctx->count] = chunk;
2419   ctx->count++;
2420 }
2421
2422 /* Receive a chunk of file data. */
2423 /* Returns -1 = error, 0 = EOF, 1 = more data */
2424 static int
2425 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2426 {
2427   struct receive_file_ctx ctx;
2428   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2429   int i;
2430   size_t len;
2431
2432   ctx.count = 0;
2433   ctx.chunks = NULL;
2434
2435   guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2436   (void) ml->main_loop_run (ml, g);
2437   guestfs_set_reply_callback (g, NULL, NULL);
2438
2439   if (ctx.count == 0) {
2440     error (g, _("receive_file_data_sync: reply callback not called\n"));
2441     return -1;
2442   }
2443
2444   if (ctx.count == -1) {
2445     error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2446     /* callback already freed the chunks */
2447     return -1;
2448   }
2449
2450   if (g->verbose)
2451     fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2452
2453   /* Process each chunk in the list. */
2454   if (buf) *buf = NULL;         /* Accumulate data in this buffer. */
2455   len = 0;
2456
2457   for (i = 0; i < ctx.count; ++i) {
2458     if (ctx.chunks[i].cancel) {
2459       error (g, _("file receive cancelled by daemon"));
2460       free_chunks (&ctx);
2461       if (buf) free (*buf);
2462       if (len_r) *len_r = 0;
2463       return -1;
2464     }
2465
2466     if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2467       free_chunks (&ctx);
2468       if (len_r) *len_r = len;
2469       return 0;
2470     }
2471
2472     if (buf) {
2473       *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2474       memcpy (*buf+len, ctx.chunks[i].data.data_val,
2475               ctx.chunks[i].data.data_len);
2476     }
2477     len += ctx.chunks[i].data.data_len;
2478   }
2479
2480   if (len_r) *len_r = len;
2481   free_chunks (&ctx);
2482   return 1;
2483 }
2484
2485 /* This is the default main loop implementation, using select(2). */
2486
2487 static int
2488 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2489                    guestfs_handle_event_cb cb, void *data)
2490 {
2491   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2492
2493   if (fd < 0 || fd >= FD_SETSIZE) {
2494     error (g, _("fd %d is out of range"), fd);
2495     return -1;
2496   }
2497
2498   if ((events & ~(GUESTFS_HANDLE_READABLE |
2499                   GUESTFS_HANDLE_WRITABLE |
2500                   GUESTFS_HANDLE_HANGUP |
2501                   GUESTFS_HANDLE_ERROR)) != 0) {
2502     error (g, _("set of events (0x%x) contains unknown events"), events);
2503     return -1;
2504   }
2505
2506   if (events == 0) {
2507     error (g, _("set of events is empty"));
2508     return -1;
2509   }
2510
2511   if (FD_ISSET (fd, &ml->rset) ||
2512       FD_ISSET (fd, &ml->wset) ||
2513       FD_ISSET (fd, &ml->xset)) {
2514     error (g, _("fd %d is already registered"), fd);
2515     return -1;
2516   }
2517
2518   if (cb == NULL) {
2519     error (g, _("callback is NULL"));
2520     return -1;
2521   }
2522
2523   if ((events & GUESTFS_HANDLE_READABLE))
2524     FD_SET (fd, &ml->rset);
2525   if ((events & GUESTFS_HANDLE_WRITABLE))
2526     FD_SET (fd, &ml->wset);
2527   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2528     FD_SET (fd, &ml->xset);
2529
2530   if (fd > ml->max_fd) {
2531     ml->max_fd = fd;
2532     ml->handle_cb_data =
2533       safe_realloc (g, ml->handle_cb_data,
2534                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2535   }
2536   ml->handle_cb_data[fd].cb = cb;
2537   ml->handle_cb_data[fd].g = g;
2538   ml->handle_cb_data[fd].data = data;
2539
2540   ml->nr_fds++;
2541
2542   /* Any integer >= 0 can be the handle, and this is as good as any ... */
2543   return fd;
2544 }
2545
2546 static int
2547 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2548 {
2549   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2550
2551   if (fd < 0 || fd >= FD_SETSIZE) {
2552     error (g, _("fd %d is out of range"), fd);
2553     return -1;
2554   }
2555
2556   if (!FD_ISSET (fd, &ml->rset) &&
2557       !FD_ISSET (fd, &ml->wset) &&
2558       !FD_ISSET (fd, &ml->xset)) {
2559     error (g, _("fd %d was not registered"), fd);
2560     return -1;
2561   }
2562
2563   FD_CLR (fd, &ml->rset);
2564   FD_CLR (fd, &ml->wset);
2565   FD_CLR (fd, &ml->xset);
2566
2567   if (fd == ml->max_fd) {
2568     ml->max_fd--;
2569     ml->handle_cb_data =
2570       safe_realloc (g, ml->handle_cb_data,
2571                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2572   }
2573
2574   ml->nr_fds--;
2575
2576   return 0;
2577 }
2578
2579 static int
2580 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2581                     guestfs_handle_timeout_cb cb, void *data)
2582 {
2583   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2584
2585   abort ();                     /* XXX not implemented yet */
2586 }
2587
2588 static int
2589 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2590 {
2591   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2592
2593   abort ();                     /* XXX not implemented yet */
2594 }
2595
2596 /* The 'g' parameter is just used for error reporting.  Events
2597  * for multiple handles can be dispatched by running the main
2598  * loop.
2599  */
2600 static int
2601 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2602 {
2603   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2604   int fd, r, events;
2605   fd_set rset2, wset2, xset2;
2606
2607   if (ml->is_running) {
2608     error (g, _("select_main_loop_run: this cannot be called recursively"));
2609     return -1;
2610   }
2611
2612   ml->is_running = 1;
2613
2614   while (ml->is_running) {
2615     if (ml->nr_fds == 0)
2616       break;
2617
2618     rset2 = ml->rset;
2619     wset2 = ml->wset;
2620     xset2 = ml->xset;
2621     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2622     if (r == -1) {
2623       if (errno == EINTR || errno == EAGAIN)
2624         continue;
2625       perrorf (g, "select");
2626       ml->is_running = 0;
2627       return -1;
2628     }
2629
2630     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2631       events = 0;
2632       if (FD_ISSET (fd, &rset2))
2633         events |= GUESTFS_HANDLE_READABLE;
2634       if (FD_ISSET (fd, &wset2))
2635         events |= GUESTFS_HANDLE_WRITABLE;
2636       if (FD_ISSET (fd, &xset2))
2637         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2638       if (events) {
2639         r--;
2640         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2641                                    ml->handle_cb_data[fd].g,
2642                                    ml->handle_cb_data[fd].data,
2643                                    fd, fd, events);
2644       }
2645     }
2646   }
2647
2648   ml->is_running = 0;
2649   return 0;
2650 }
2651
2652 static int
2653 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2654 {
2655   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2656
2657   /* Note that legitimately ml->is_running can be zero when
2658    * this function is called.
2659    */
2660
2661   ml->is_running = 0;
2662   return 0;
2663 }