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