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