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