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