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