6c49e9091887e6da643079be0fb556cb265040aa
[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/select.h>
33 #include <rpc/types.h>
34 #include <rpc/xdr.h>
35
36 #ifdef HAVE_ERRNO_H
37 #include <errno.h>
38 #endif
39
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
47
48 #ifdef HAVE_SYS_SOCKET_H
49 #include <sys/socket.h>
50 #endif
51
52 #ifdef HAVE_SYS_UN_H
53 #include <sys/un.h>
54 #endif
55
56 #include "guestfs.h"
57 #include "guestfs_protocol.h"
58
59 static void error (guestfs_h *g, const char *fs, ...);
60 static void perrorf (guestfs_h *g, const char *fs, ...);
61 static void *safe_malloc (guestfs_h *g, size_t nbytes);
62 static void *safe_realloc (guestfs_h *g, void *ptr, int nbytes);
63 static char *safe_strdup (guestfs_h *g, const char *str);
64 static void *safe_memdup (guestfs_h *g, void *ptr, size_t size);
65
66 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
67 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
68 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
69 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
70
71 static void close_handles (void);
72
73 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
74 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
75 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
76 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
77 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
78 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
79
80 /* Default select-based main loop. */
81 struct select_handle_cb_data {
82   guestfs_handle_event_cb cb;
83   guestfs_h *g;
84   void *data;
85 };
86
87 struct select_main_loop {
88   /* NB. These fields must be the same as in struct guestfs_main_loop: */
89   guestfs_add_handle_cb add_handle;
90   guestfs_remove_handle_cb remove_handle;
91   guestfs_add_timeout_cb add_timeout;
92   guestfs_remove_timeout_cb remove_timeout;
93   guestfs_main_loop_run_cb main_loop_run;
94   guestfs_main_loop_quit_cb main_loop_quit;
95
96   /* Additional private data: */
97   int is_running;
98
99   fd_set rset;
100   fd_set wset;
101   fd_set xset;
102
103   int max_fd;
104   int nr_fds;
105   struct select_handle_cb_data *handle_cb_data;
106 };
107
108 /* Default main loop. */
109 static struct select_main_loop default_main_loop = {
110   .add_handle = select_add_handle,
111   .remove_handle = select_remove_handle,
112   .add_timeout = select_add_timeout,
113   .remove_timeout = select_remove_timeout,
114   .main_loop_run = select_main_loop_run,
115   .main_loop_quit = select_main_loop_quit,
116
117   /* XXX hopefully .rset, .wset, .xset are initialized to the empty
118    * set by the normal action of everything being initialized to zero.
119    */
120   .is_running = 0,
121   .max_fd = -1,
122   .nr_fds = 0,
123   .handle_cb_data = NULL,
124 };
125
126 #define UNIX_PATH_MAX 108
127
128 /* Also in guestfsd.c */
129 #define VMCHANNEL_PORT 6666
130 #define VMCHANNEL_ADDR "10.0.2.4"
131
132 /* GuestFS handle and connection. */
133 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
134
135 struct guestfs_h
136 {
137   struct guestfs_h *next;       /* Linked list of open handles. */
138
139   /* State: see the state machine diagram in the man page guestfs(3). */
140   enum state state;
141
142   int fd[2];                    /* Stdin/stdout of qemu. */
143   int sock;                     /* Daemon communications socket. */
144   int pid;                      /* Qemu PID. */
145   time_t start_t;               /* The time when we started qemu. */
146
147   int stdout_watch;             /* Watches qemu stdout for log messages. */
148   int sock_watch;               /* Watches daemon comm socket. */
149
150   char *tmpdir;                 /* Temporary directory containing socket. */
151
152   char **cmdline;               /* Qemu command line. */
153   int cmdline_size;
154
155   int verbose;
156   int autosync;
157
158   const char *path;
159
160   char *last_error;
161
162   /* Callbacks. */
163   guestfs_abort_cb           abort_cb;
164   guestfs_error_handler_cb   error_cb;
165   void *                     error_cb_data;
166   guestfs_send_cb            send_cb;
167   void *                     send_cb_data;
168   guestfs_reply_cb           reply_cb;
169   void *                     reply_cb_data;
170   guestfs_log_message_cb     log_message_cb;
171   void *                     log_message_cb_data;
172   guestfs_subprocess_quit_cb subprocess_quit_cb;
173   void *                     subprocess_quit_cb_data;
174   guestfs_launch_done_cb     launch_done_cb;
175   void *                     launch_done_cb_data;
176
177   /* These callbacks are called before send_cb, reply_cb and
178    * launch_done_cb, and are used to implement the high-level
179    * API without needing to interfere with callbacks that the
180    * user might have set.
181    */
182   guestfs_send_cb            send_cb_internal;
183   void *                     send_cb_internal_data;
184   guestfs_reply_cb           reply_cb_internal;
185   void *                     reply_cb_internal_data;
186   guestfs_launch_done_cb     launch_done_cb_internal;
187   void *                     launch_done_cb_internal_data;
188
189   /* Main loop used by this handle. */
190   guestfs_main_loop *main_loop;
191
192   /* Messages sent and received from the daemon. */
193   char *msg_in;
194   int msg_in_size, msg_in_allocated;
195   char *msg_out;
196   int msg_out_size, msg_out_pos;
197
198   int msg_next_serial;
199 };
200
201 static guestfs_h *handles = NULL;
202 static int atexit_handler_set = 0;
203
204 guestfs_h *
205 guestfs_create (void)
206 {
207   guestfs_h *g;
208   const char *str;
209
210   g = malloc (sizeof (*g));
211   if (!g) return NULL;
212
213   memset (g, 0, sizeof (*g));
214
215   g->state = CONFIG;
216
217   g->fd[0] = -1;
218   g->fd[1] = -1;
219   g->sock = -1;
220   g->stdout_watch = -1;
221   g->sock_watch = -1;
222
223   g->abort_cb = abort;
224   g->error_cb = default_error_cb;
225   g->error_cb_data = NULL;
226
227   str = getenv ("LIBGUESTFS_DEBUG");
228   g->verbose = str != NULL && strcmp (str, "1") == 0;
229
230   str = getenv ("LIBGUESTFS_PATH");
231   g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
232   /* XXX We should probably make QEMU configurable as well. */
233
234   g->main_loop = (guestfs_main_loop *) &default_main_loop;
235
236   /* Start with large serial numbers so they are easy to spot
237    * inside the protocol.
238    */
239   g->msg_next_serial = 0x00123400;
240
241   /* Link the handles onto a global list.  This is the one area
242    * where the library needs to be made thread-safe. (XXX)
243    */
244   /* acquire mutex (XXX) */
245   g->next = handles;
246   handles = g;
247   if (!atexit_handler_set) {
248     atexit (close_handles);
249     atexit_handler_set = 1;
250   }
251   /* release mutex (XXX) */
252
253   if (g->verbose)
254     fprintf (stderr, "new guestfs handle %p\n", g);
255
256   return g;
257 }
258
259 void
260 guestfs_close (guestfs_h *g)
261 {
262   int i;
263   char filename[256];
264   guestfs_h *gg;
265
266   if (g->state == NO_HANDLE) {
267     /* Not safe to call 'error' here, so ... */
268     fprintf (stderr, "guestfs_close: called twice on the same handle\n");
269     return;
270   }
271
272   if (g->verbose)
273     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
274
275   /* Try to sync if autosync flag is set. */
276   if (g->autosync && g->state == READY)
277     guestfs_sync (g);
278
279   /* Remove any handlers that might be called back before we kill the
280    * subprocess.
281    */
282   g->log_message_cb = NULL;
283
284   if (g->state != CONFIG)
285     guestfs_kill_subprocess (g);
286
287   if (g->tmpdir) {
288     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
289     unlink (filename);
290
291     rmdir (g->tmpdir);
292
293     free (g->tmpdir);
294   }
295
296   if (g->cmdline) {
297     for (i = 0; i < g->cmdline_size; ++i)
298       free (g->cmdline[i]);
299     free (g->cmdline);
300   }
301
302   /* Mark the handle as dead before freeing it. */
303   g->state = NO_HANDLE;
304
305   /* acquire mutex (XXX) */
306   if (handles == g)
307     handles = g->next;
308   else {
309     for (gg = handles; gg->next != g; gg = gg->next)
310       ;
311     gg->next = g->next;
312   }
313   /* release mutex (XXX) */
314
315   free (g->last_error);
316   free (g);
317 }
318
319 /* Close all open handles (called from atexit(3)). */
320 static void
321 close_handles (void)
322 {
323   while (handles) guestfs_close (handles);
324 }
325
326 const char *
327 guestfs_last_error (guestfs_h *g)
328 {
329   return g->last_error;
330 }
331
332 static void
333 set_last_error (guestfs_h *g, const char *msg)
334 {
335   free (g->last_error);
336   g->last_error = strdup (msg);
337 }
338
339 static void
340 default_error_cb (guestfs_h *g, void *data, const char *msg)
341 {
342   fprintf (stderr, "libguestfs: error: %s\n", msg);
343 }
344
345 static void
346 error (guestfs_h *g, const char *fs, ...)
347 {
348   va_list args;
349   char *msg;
350
351   va_start (args, fs);
352   vasprintf (&msg, fs, args);
353   va_end (args);
354
355   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
356   set_last_error (g, msg);
357
358   free (msg);
359 }
360
361 static void
362 perrorf (guestfs_h *g, const char *fs, ...)
363 {
364   va_list args;
365   char *msg;
366   int err = errno;
367
368   va_start (args, fs);
369   vasprintf (&msg, fs, args);
370   va_end (args);
371
372 #ifndef _GNU_SOURCE
373   char buf[256];
374   strerror_r (err, buf, sizeof buf);
375 #else
376   char _buf[256];
377   char *buf;
378   buf = strerror_r (err, _buf, sizeof _buf);
379 #endif
380
381   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
382   strcat (msg, ": ");
383   strcat (msg, buf);
384
385   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
386   set_last_error (g, msg);
387
388   free (msg);
389 }
390
391 static void *
392 safe_malloc (guestfs_h *g, size_t nbytes)
393 {
394   void *ptr = malloc (nbytes);
395   if (!ptr) g->abort_cb ();
396   return ptr;
397 }
398
399 static void *
400 safe_realloc (guestfs_h *g, void *ptr, int nbytes)
401 {
402   void *p = realloc (ptr, nbytes);
403   if (!p) g->abort_cb ();
404   return p;
405 }
406
407 static char *
408 safe_strdup (guestfs_h *g, const char *str)
409 {
410   char *s = strdup (str);
411   if (!s) g->abort_cb ();
412   return s;
413 }
414
415 static void *
416 safe_memdup (guestfs_h *g, void *ptr, size_t size)
417 {
418   void *p = malloc (size);
419   if (!p) g->abort_cb ();
420   memcpy (p, ptr, size);
421   return p;
422 }
423
424 void
425 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
426 {
427   g->abort_cb = cb;
428 }
429
430 guestfs_abort_cb
431 guestfs_get_out_of_memory_handler (guestfs_h *g)
432 {
433   return g->abort_cb;
434 }
435
436 void
437 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
438 {
439   g->error_cb = cb;
440   g->error_cb_data = data;
441 }
442
443 guestfs_error_handler_cb
444 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
445 {
446   if (data_rtn) *data_rtn = g->error_cb_data;
447   return g->error_cb;
448 }
449
450 int
451 guestfs_set_verbose (guestfs_h *g, int v)
452 {
453   g->verbose = !!v;
454   return 0;
455 }
456
457 int
458 guestfs_get_verbose (guestfs_h *g)
459 {
460   return g->verbose;
461 }
462
463 int
464 guestfs_set_autosync (guestfs_h *g, int a)
465 {
466   g->autosync = !!a;
467   return 0;
468 }
469
470 int
471 guestfs_get_autosync (guestfs_h *g)
472 {
473   return g->autosync;
474 }
475
476 int
477 guestfs_set_path (guestfs_h *g, const char *path)
478 {
479   if (path == NULL)
480     g->path = GUESTFS_DEFAULT_PATH;
481   else
482     g->path = path;
483   return 0;
484 }
485
486 const char *
487 guestfs_get_path (guestfs_h *g)
488 {
489   return g->path;
490 }
491
492 /* Add a string to the current command line. */
493 static void
494 incr_cmdline_size (guestfs_h *g)
495 {
496   if (g->cmdline == NULL) {
497     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
498     g->cmdline_size = 1;
499     g->cmdline = safe_malloc (g, sizeof (char *));
500     g->cmdline[0] = NULL;
501   }
502
503   g->cmdline_size++;
504   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
505 }
506
507 static int
508 add_cmdline (guestfs_h *g, const char *str)
509 {
510   if (g->state != CONFIG) {
511     error (g, "command line cannot be altered after qemu subprocess launched");
512     return -1;
513   }
514
515   incr_cmdline_size (g);
516   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
517   return 0;
518 }
519
520 int
521 guestfs_config (guestfs_h *g,
522                 const char *qemu_param, const char *qemu_value)
523 {
524   if (qemu_param[0] != '-') {
525     error (g, "guestfs_config: parameter must begin with '-' character");
526     return -1;
527   }
528
529   /* A bit fascist, but the user will probably break the extra
530    * parameters that we add if they try to set any of these.
531    */
532   if (strcmp (qemu_param, "-kernel") == 0 ||
533       strcmp (qemu_param, "-initrd") == 0 ||
534       strcmp (qemu_param, "-nographic") == 0 ||
535       strcmp (qemu_param, "-serial") == 0 ||
536       strcmp (qemu_param, "-vnc") == 0 ||
537       strcmp (qemu_param, "-full-screen") == 0 ||
538       strcmp (qemu_param, "-std-vga") == 0 ||
539       strcmp (qemu_param, "-vnc") == 0) {
540     error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
541     return -1;
542   }
543
544   if (add_cmdline (g, qemu_param) != 0) return -1;
545
546   if (qemu_value != NULL) {
547     if (add_cmdline (g, qemu_value) != 0) return -1;
548   }
549
550   return 0;
551 }
552
553 int
554 guestfs_add_drive (guestfs_h *g, const char *filename)
555 {
556   int len = strlen (filename) + 64;
557   char buf[len];
558
559   if (strchr (filename, ',') != NULL) {
560     error (g, "filename cannot contain ',' (comma) character");
561     return -1;
562   }
563
564   if (access (filename, F_OK) == -1) {
565     perrorf (g, "%s", filename);
566     return -1;
567   }
568
569   snprintf (buf, len, "file=%s", filename);
570
571   return guestfs_config (g, "-drive", buf);
572 }
573
574 int
575 guestfs_add_cdrom (guestfs_h *g, const char *filename)
576 {
577   if (strchr (filename, ',') != NULL) {
578     error (g, "filename cannot contain ',' (comma) character");
579     return -1;
580   }
581
582   if (access (filename, F_OK) == -1) {
583     perrorf (g, "%s", filename);
584     return -1;
585   }
586
587   return guestfs_config (g, "-cdrom", filename);
588 }
589
590 int
591 guestfs_launch (guestfs_h *g)
592 {
593   static const char *dir_template = "/tmp/libguestfsXXXXXX";
594   int r, i, len, pmore;
595   int wfd[2], rfd[2];
596   int tries;
597   const char *kernel_name = "vmlinuz." REPO "." host_cpu;
598   const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
599   char *path, *pelem, *pend;
600   char *kernel = NULL, *initrd = NULL;
601   char unixsock[256];
602   struct sockaddr_un addr;
603
604   /* Configured? */
605   if (!g->cmdline) {
606     error (g, "you must call guestfs_add_drive before guestfs_launch");
607     return -1;
608   }
609
610   if (g->state != CONFIG) {
611     error (g, "qemu has already been launched");
612     return -1;
613   }
614
615   /* Search g->path for the kernel and initrd. */
616   pelem = path = safe_strdup (g, g->path);
617   do {
618     pend = strchrnul (pelem, ':');
619     pmore = *pend == ':';
620     *pend = '\0';
621     len = pend - pelem;
622
623     /* Empty element or "." means cwd. */
624     if (len == 0 || (len == 1 && *pelem == '.')) {
625       if (g->verbose)
626         fprintf (stderr,
627                  "looking for kernel and initrd in current directory\n");
628       if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
629         kernel = safe_strdup (g, kernel_name);
630         initrd = safe_strdup (g, initrd_name);
631         break;
632       }
633     }
634     /* Look at <path>/kernel etc. */
635     else {
636       kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
637       initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
638       sprintf (kernel, "%s/%s", pelem, kernel_name);
639       sprintf (initrd, "%s/%s", pelem, initrd_name);
640
641       if (g->verbose)
642         fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
643
644       if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
645         break;
646       free (kernel);
647       free (initrd);
648       kernel = initrd = NULL;
649     }
650
651     pelem = pend + 1;
652   } while (pmore);
653
654   free (path);
655
656   if (kernel == NULL || initrd == NULL) {
657     error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
658            kernel_name, initrd_name, g->path);
659     goto cleanup0;
660   }
661
662   /* Make the temporary directory containing the socket. */
663   if (!g->tmpdir) {
664     g->tmpdir = safe_strdup (g, dir_template);
665     if (mkdtemp (g->tmpdir) == NULL) {
666       perrorf (g, "%s: cannot create temporary directory", dir_template);
667       goto cleanup0;
668     }
669   }
670
671   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
672   unlink (unixsock);
673
674   if (pipe (wfd) == -1 || pipe (rfd) == -1) {
675     perrorf (g, "pipe");
676     goto cleanup0;
677   }
678
679   r = fork ();
680   if (r == -1) {
681     perrorf (g, "fork");
682     close (wfd[0]);
683     close (wfd[1]);
684     close (rfd[0]);
685     close (rfd[1]);
686     goto cleanup0;
687   }
688
689   if (r == 0) {                 /* Child (qemu). */
690     char vmchannel[256];
691     char append[256];
692
693     /* Set up the full command line.  Do this in the subprocess so we
694      * don't need to worry about cleaning up.
695      */
696     g->cmdline[0] = (char *) QEMU;
697
698     /* Construct the -net channel parameter for qemu. */
699     snprintf (vmchannel, sizeof vmchannel,
700               "channel,%d:unix:%s,server,nowait",
701               VMCHANNEL_PORT, unixsock);
702
703     /* Linux kernel command line. */
704     snprintf (append, sizeof append,
705               "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
706
707     add_cmdline (g, "-m");
708     add_cmdline (g, "384");       /* XXX Choose best size. */
709     add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
710     add_cmdline (g, "-kernel");
711     add_cmdline (g, (char *) kernel);
712     add_cmdline (g, "-initrd");
713     add_cmdline (g, (char *) initrd);
714     add_cmdline (g, "-append");
715     add_cmdline (g, append);
716     add_cmdline (g, "-nographic");
717     add_cmdline (g, "-serial");
718     add_cmdline (g, "stdio");
719     add_cmdline (g, "-net");
720     add_cmdline (g, vmchannel);
721     add_cmdline (g, "-net");
722     add_cmdline (g, "user,vlan=0");
723     add_cmdline (g, "-net");
724     add_cmdline (g, "nic,vlan=0");
725     incr_cmdline_size (g);
726     g->cmdline[g->cmdline_size-1] = NULL;
727
728     if (g->verbose) {
729       fprintf (stderr, "%s", QEMU);
730       for (i = 0; g->cmdline[i]; ++i)
731         fprintf (stderr, " %s", g->cmdline[i]);
732       fprintf (stderr, "\n");
733     }
734
735     /* Set up stdin, stdout. */
736     close (0);
737     close (1);
738     close (wfd[1]);
739     close (rfd[0]);
740     dup (wfd[0]);
741     dup (rfd[1]);
742     close (wfd[0]);
743     close (rfd[1]);
744
745 #if 0
746     /* Set up a new process group, so we can signal this process
747      * and all subprocesses (eg. if qemu is really a shell script).
748      */
749     setpgid (0, 0);
750 #endif
751
752     execv (QEMU, g->cmdline);   /* Run qemu. */
753     perror (QEMU);
754     _exit (1);
755   }
756
757   /* Parent (library). */
758   g->pid = r;
759
760   /* Start the clock ... */
761   time (&g->start_t);
762
763   /* Close the other ends of the pipe. */
764   close (wfd[0]);
765   close (rfd[1]);
766
767   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
768       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
769     perrorf (g, "fcntl");
770     goto cleanup1;
771   }
772
773   g->fd[0] = wfd[1];            /* stdin of child */
774   g->fd[1] = rfd[0];            /* stdout of child */
775
776   /* Open the Unix socket.  The vmchannel implementation that got
777    * merged with qemu sucks in a number of ways.  Both ends do
778    * connect(2), which means that no one knows what, if anything, is
779    * connected to the other end, or if it becomes disconnected.  Even
780    * worse, we have to wait some indeterminate time for qemu to create
781    * the socket and connect to it (which happens very early in qemu's
782    * start-up), so any code that uses vmchannel is inherently racy.
783    * Hence this silly loop.
784    */
785   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
786   if (g->sock == -1) {
787     perrorf (g, "socket");
788     goto cleanup1;
789   }
790
791   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
792     perrorf (g, "fcntl");
793     goto cleanup2;
794   }
795
796   addr.sun_family = AF_UNIX;
797   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
798   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
799
800   tries = 100;
801   while (tries > 0) {
802     /* Always sleep at least once to give qemu a small chance to start up. */
803     usleep (10000);
804
805     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
806     if ((r == -1 && errno == EINPROGRESS) || r == 0)
807       goto connected;
808
809     if (errno != ENOENT)
810       perrorf (g, "connect");
811     tries--;
812   }
813
814   error (g, "failed to connect to vmchannel socket");
815   goto cleanup2;
816
817  connected:
818   /* Watch the file descriptors. */
819   free (g->msg_in);
820   g->msg_in = NULL;
821   g->msg_in_size = g->msg_in_allocated = 0;
822
823   free (g->msg_out);
824   g->msg_out = NULL;
825   g->msg_out_size = 0;
826   g->msg_out_pos = 0;
827
828   g->stdout_watch =
829     g->main_loop->add_handle (g->main_loop, g, g->fd[1],
830                               GUESTFS_HANDLE_READABLE,
831                               stdout_event, NULL);
832   if (g->stdout_watch == -1) {
833     error (g, "could not watch qemu stdout");
834     goto cleanup3;
835   }
836
837   g->sock_watch =
838     g->main_loop->add_handle (g->main_loop, g, g->sock,
839                               GUESTFS_HANDLE_READABLE,
840                               sock_read_event, NULL);
841   if (g->sock_watch == -1) {
842     error (g, "could not watch daemon communications socket");
843     goto cleanup3;
844   }
845
846   g->state = LAUNCHING;
847   return 0;
848
849  cleanup3:
850   if (g->stdout_watch >= 0)
851     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
852   if (g->sock_watch >= 0)
853     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
854
855  cleanup2:
856   close (g->sock);
857
858  cleanup1:
859   close (wfd[1]);
860   close (rfd[0]);
861   kill (g->pid, 9);
862   waitpid (g->pid, NULL, 0);
863   g->fd[0] = -1;
864   g->fd[1] = -1;
865   g->sock = -1;
866   g->pid = 0;
867   g->start_t = 0;
868   g->stdout_watch = -1;
869   g->sock_watch = -1;
870
871  cleanup0:
872   free (kernel);
873   free (initrd);
874   return -1;
875 }
876
877 static void
878 finish_wait_ready (guestfs_h *g, void *vp)
879 {
880   if (g->verbose)
881     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
882
883   *((int *)vp) = 1;
884   g->main_loop->main_loop_quit (g->main_loop, g);
885 }
886
887 int
888 guestfs_wait_ready (guestfs_h *g)
889 {
890   int finished = 0, r;
891
892   if (g->state == READY) return 0;
893
894   if (g->state == BUSY) {
895     error (g, "qemu has finished launching already");
896     return -1;
897   }
898
899   if (g->state != LAUNCHING) {
900     error (g, "qemu has not been launched yet");
901     return -1;
902   }
903
904   g->launch_done_cb_internal = finish_wait_ready;
905   g->launch_done_cb_internal_data = &finished;
906   r = g->main_loop->main_loop_run (g->main_loop, g);
907   g->launch_done_cb_internal = NULL;
908   g->launch_done_cb_internal_data = NULL;
909
910   if (r == -1) return -1;
911
912   if (finished != 1) {
913     error (g, "guestfs_wait_ready failed, see earlier error messages");
914     return -1;
915   }
916
917   /* This is possible in some really strange situations, such as
918    * guestfsd starts up OK but then qemu immediately exits.  Check for
919    * it because the caller is probably expecting to be able to send
920    * commands after this function returns.
921    */
922   if (g->state != READY) {
923     error (g, "qemu launched and contacted daemon, but state != READY");
924     return -1;
925   }
926
927   return 0;
928 }
929
930 int
931 guestfs_kill_subprocess (guestfs_h *g)
932 {
933   if (g->state == CONFIG) {
934     error (g, "no subprocess to kill");
935     return -1;
936   }
937
938   if (g->verbose)
939     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
940
941   kill (g->pid, SIGTERM);
942
943   return 0;
944 }
945
946 /* This function is called whenever qemu prints something on stdout.
947  * Qemu's stdout is also connected to the guest's serial console, so
948  * we see kernel messages here too.
949  */
950 static void
951 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
952               int watch, int fd, int events)
953 {
954   char buf[4096];
955   int n;
956
957 #if 0
958   if (g->verbose)
959     fprintf (stderr,
960              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
961              g, g->state, fd, events);
962 #endif
963
964   if (g->fd[1] != fd) {
965     error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
966     return;
967   }
968
969   n = read (fd, buf, sizeof buf);
970   if (n == 0) {
971     /* Hopefully this indicates the qemu child process has died. */
972     if (g->verbose)
973       fprintf (stderr, "stdout_event: %p: child process died\n", g);
974     /*kill (g->pid, SIGTERM);*/
975     waitpid (g->pid, NULL, 0);
976     if (g->stdout_watch >= 0)
977       g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
978     if (g->sock_watch >= 0)
979       g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
980     close (g->fd[0]);
981     close (g->fd[1]);
982     close (g->sock);
983     g->fd[0] = -1;
984     g->fd[1] = -1;
985     g->sock = -1;
986     g->pid = 0;
987     g->start_t = 0;
988     g->stdout_watch = -1;
989     g->sock_watch = -1;
990     g->state = CONFIG;
991     if (g->subprocess_quit_cb)
992       g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
993     return;
994   }
995
996   if (n == -1) {
997     if (errno != EAGAIN)
998       perrorf (g, "read");
999     return;
1000   }
1001
1002   /* In verbose mode, copy all log messages to stderr. */
1003   if (g->verbose)
1004     write (2, buf, n);
1005
1006   /* It's an actual log message, send it upwards if anyone is listening. */
1007   if (g->log_message_cb)
1008     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1009 }
1010
1011 /* The function is called whenever we can read something on the
1012  * guestfsd (daemon inside the guest) communication socket.
1013  */
1014 static void
1015 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1016                  int watch, int fd, int events)
1017 {
1018   XDR xdr;
1019   unsigned len;
1020   int n;
1021
1022   if (g->verbose)
1023     fprintf (stderr,
1024              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1025              g, g->state, fd, events);
1026
1027   if (g->sock != fd) {
1028     error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1029     return;
1030   }
1031
1032   if (g->msg_in_size <= g->msg_in_allocated) {
1033     g->msg_in_allocated += 4096;
1034     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1035   }
1036   n = read (g->sock, g->msg_in + g->msg_in_size,
1037             g->msg_in_allocated - g->msg_in_size);
1038   if (n == 0)
1039     /* Disconnected?  Ignore it because stdout_watch will get called
1040      * and will do the cleanup.
1041      */
1042     return;
1043
1044   if (n == -1) {
1045     if (errno != EAGAIN)
1046       perrorf (g, "read");
1047     return;
1048   }
1049
1050   g->msg_in_size += n;
1051
1052   /* Have we got enough of a message to be able to process it yet? */
1053   if (g->msg_in_size < 4) return;
1054
1055   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1056   if (!xdr_uint32_t (&xdr, &len)) {
1057     error (g, "can't decode length word");
1058     goto cleanup;
1059   }
1060
1061   /* Length is normally the length of the message, but when guestfsd
1062    * starts up it sends a "magic" value (longer than any possible
1063    * message).  Check for this.
1064    */
1065   if (len == 0xf5f55ff5) {
1066     if (g->state != LAUNCHING)
1067       error (g, "received magic signature from guestfsd, but in state %d",
1068              g->state);
1069     else if (g->msg_in_size != 4)
1070       error (g, "received magic signature from guestfsd, but msg size is %d",
1071              g->msg_in_size);
1072     else {
1073       g->state = READY;
1074       if (g->launch_done_cb_internal)
1075         g->launch_done_cb_internal (g, g->launch_done_cb_internal_data);
1076       if (g->launch_done_cb)
1077         g->launch_done_cb (g, g->launch_done_cb_data);
1078     }
1079
1080     goto cleanup;
1081   }
1082
1083   /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1084   if (len > GUESTFS_MESSAGE_MAX) {
1085     error (g, "message length (%u) > maximum possible size (%d)",
1086            len, GUESTFS_MESSAGE_MAX);
1087     goto cleanup;
1088   }
1089
1090   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1091
1092   /* This should not happen, and if it does it probably means we've
1093    * lost all hope of synchronization.
1094    */
1095   if (g->msg_in_size-4 > len) {
1096     error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1097     goto cleanup;
1098   }
1099
1100   /* Got the full message, begin processing it. */
1101   if (g->verbose) {
1102     int i, j;
1103
1104     for (i = 0; i < g->msg_in_size; i += 16) {
1105       printf ("%04x: ", i);
1106       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1107         printf ("%02x ", (unsigned char) g->msg_in[j]);
1108       for (; j < i+16; ++j)
1109         printf ("   ");
1110       printf ("|");
1111       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1112         if (isprint (g->msg_in[j]))
1113           printf ("%c", g->msg_in[j]);
1114         else
1115           printf (".");
1116       for (; j < i+16; ++j)
1117         printf (" ");
1118       printf ("|\n");
1119     }
1120   }
1121
1122   /* Not in the expected state. */
1123   if (g->state != BUSY)
1124     error (g, "state %d != BUSY", g->state);
1125
1126   /* Push the message up to the higher layer.  Note that unlike
1127    * launch_done_cb / launch_done_cb_internal, we only call at
1128    * most one of the callback functions here.
1129    */
1130   g->state = READY;
1131   if (g->reply_cb_internal)
1132     g->reply_cb_internal (g, g->reply_cb_internal_data, &xdr);
1133   else if (g->reply_cb)
1134     g->reply_cb (g, g->reply_cb, &xdr);
1135
1136  cleanup:
1137   /* Free the message buffer if it's grown excessively large. */
1138   if (g->msg_in_allocated > 65536) {
1139     free (g->msg_in);
1140     g->msg_in = NULL;
1141     g->msg_in_size = g->msg_in_allocated = 0;
1142   } else
1143     g->msg_in_size = 0;
1144
1145   xdr_destroy (&xdr);
1146 }
1147
1148 /* The function is called whenever we can write something on the
1149  * guestfsd (daemon inside the guest) communication socket.
1150  */
1151 static void
1152 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1153                   int watch, int fd, int events)
1154 {
1155   int n;
1156
1157   if (g->verbose)
1158     fprintf (stderr,
1159              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1160              g, g->state, fd, events);
1161
1162   if (g->sock != fd) {
1163     error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1164     return;
1165   }
1166
1167   if (g->state != BUSY) {
1168     error (g, "sock_write_event: state %d != BUSY", g->state);
1169     return;
1170   }
1171
1172   if (g->verbose)
1173     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1174              g->msg_out_size - g->msg_out_pos);
1175
1176   n = write (g->sock, g->msg_out + g->msg_out_pos,
1177              g->msg_out_size - g->msg_out_pos);
1178   if (n == -1) {
1179     if (errno != EAGAIN)
1180       perrorf (g, "write");
1181     return;
1182   }
1183
1184   if (g->verbose)
1185     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1186
1187   g->msg_out_pos += n;
1188
1189   /* More to write? */
1190   if (g->msg_out_pos < g->msg_out_size)
1191     return;
1192
1193   if (g->verbose)
1194     fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1195
1196   free (g->msg_out);
1197   g->msg_out_pos = g->msg_out_size = 0;
1198
1199   if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1200     error (g, "remove_handle failed in sock_write_event");
1201     return;
1202   }
1203   g->sock_watch =
1204     g->main_loop->add_handle (g->main_loop, g, g->sock,
1205                               GUESTFS_HANDLE_READABLE,
1206                               sock_read_event, NULL);
1207   if (g->sock_watch == -1) {
1208     error (g, "add_handle failed in sock_write_event");
1209     return;
1210   }
1211 }
1212
1213 /* Dispatch a call to the remote daemon.  This function just queues
1214  * the call in msg_out, to be sent when we next enter the main loop.
1215  * Returns -1 for error, or the message serial number.
1216  */
1217 static int
1218 dispatch (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1219 {
1220   char buffer[GUESTFS_MESSAGE_MAX];
1221   struct guestfs_message_header hdr;
1222   XDR xdr;
1223   unsigned len;
1224   int serial = g->msg_next_serial++;
1225
1226   if (g->state != READY) {
1227     error (g, "dispatch: state %d != READY", g->state);
1228     return -1;
1229   }
1230
1231   /* Serialize the header. */
1232   hdr.prog = GUESTFS_PROGRAM;
1233   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1234   hdr.proc = proc_nr;
1235   hdr.direction = GUESTFS_DIRECTION_CALL;
1236   hdr.serial = serial;
1237   hdr.status = GUESTFS_STATUS_OK;
1238
1239   xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1240   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1241     error (g, "xdr_guestfs_message_header failed");
1242     return -1;
1243   }
1244
1245   /* Serialize the args.  If any, because some message types
1246    * have no parameters.
1247    */
1248   if (xdrp) {
1249     if (!(*xdrp) (&xdr, args)) {
1250       error (g, "dispatch failed to marshal args");
1251       return -1;
1252     }
1253   }
1254
1255   len = xdr_getpos (&xdr);
1256   xdr_destroy (&xdr);
1257
1258   /* Allocate the outgoing message buffer. */
1259   g->msg_out = safe_malloc (g, len + 4);
1260
1261   g->msg_out_size = len + 4;
1262   g->msg_out_pos = 0;
1263   g->state = BUSY;
1264
1265   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1266   if (!xdr_uint32_t (&xdr, &len)) {
1267     error (g, "xdr_uint32_t failed in dispatch");
1268     goto cleanup1;
1269   }
1270
1271   memcpy (g->msg_out + 4, buffer, len);
1272
1273   /* Change the handle to sock_write_event. */
1274   if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1275     error (g, "remove_handle failed in dispatch");
1276     goto cleanup1;
1277   }
1278   g->sock_watch =
1279     g->main_loop->add_handle (g->main_loop, g, g->sock,
1280                               GUESTFS_HANDLE_WRITABLE,
1281                               sock_write_event, NULL);
1282   if (g->sock_watch == -1) {
1283     error (g, "add_handle failed in dispatch");
1284     goto cleanup1;
1285   }
1286
1287   return serial;
1288
1289  cleanup1:
1290   free (g->msg_out);
1291   g->msg_out = NULL;
1292   g->msg_out_size = 0;
1293   g->state = READY;
1294   return -1;
1295 }
1296
1297 #if 0
1298 static int cancel = 0; /* XXX Implement file cancellation. */
1299
1300 static int
1301 send_file (guestfs_h *g, const char *filename)
1302 {
1303   char buf[GUESTFS_MAX_CHUNK_SIZE];
1304   int fd, r;
1305
1306   fd = open (filename, O_RDONLY);
1307   if (fd == -1) {
1308     perrorf (g, "open: %s", filename);
1309     send_file_cancellation (g);
1310     /* Daemon sees cancellation and won't reply, so caller can
1311      * just return here.
1312      */
1313     return -1;
1314   }
1315
1316   /* Send file in chunked encoding. */
1317   while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1318     if (send_file_data (g, buf, r) == -1)
1319       return -1;
1320   }
1321
1322   if (cancel) {
1323     send_file_cancellation (g);
1324     return -1;
1325   }
1326
1327   if (r == -1) {
1328     perrorf (g, "read: %s", filename);
1329     send_file_cancellation (g);
1330     return -1;
1331   }
1332
1333   /* End of file, but before we send that, we need to close
1334    * the file and check for errors.
1335    */
1336   if (close (fd) == -1) {
1337     perrorf (g, "close: %s", filename);
1338     send_file_cancellation (g);
1339     return -1;
1340   }
1341
1342   return send_file_complete (g);
1343 }
1344
1345 /* Send a chunk, cancellation or end of file, wait for it to go. */
1346 static int
1347 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len)
1348 {
1349   void *data;
1350   guestfs_chunk chunk;
1351   XDR xdr;
1352
1353   if (g->state != BUSY) {
1354     error (g, "send_file_chunk: state %d != READY", g->state);
1355     return -1;
1356   }
1357
1358   /* Serialize the chunk. */
1359   chunk.cancel = cancel;
1360   chunk.data.data_len = len;
1361   chunk.data.data_val = (char *) buf;
1362
1363   data = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 48);
1364   xdrmem_create (&xdr, data, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1365   if (xdr_guestfs_chunk (&xdr, &chunk)) {
1366     error (g, "xdr_guestfs_chunk failed");
1367     free (data);
1368     return -1;
1369   }
1370
1371   chunkdatalen = xdr_getpos (&xdr);
1372   xdr_destroy (&xdr);
1373
1374   len = xdr_getpos (&xdr);
1375   xdr_destroy (&xdr);
1376
1377   data = safe_realloc (g, data, len);
1378   g->msg_out = data;
1379   g->msg_out_size = len;
1380   g->msg_out_pos = 0;
1381
1382   /* Change the handle to sock_write_event. */
1383   if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1384     error (g, "remove_handle failed in dispatch");
1385     goto cleanup1;
1386   }
1387   g->sock_watch =
1388     g->main_loop->add_handle (g->main_loop, g, g->sock,
1389                               GUESTFS_HANDLE_WRITABLE,
1390                               sock_write_event, NULL);
1391   if (g->sock_watch == -1) {
1392     error (g, "add_handle failed in dispatch");
1393     goto cleanup1;
1394   }
1395
1396   return 0;
1397
1398  cleanup1:
1399   free (g->msg_out);
1400   g->msg_out = NULL;
1401   g->msg_out_size = 0;
1402   g->state = READY;
1403   return -1;
1404 }
1405
1406 /* Send a chunk of file data. */
1407 static int
1408 send_file_data (guestfs_h *g, const char *buf, size_t len)
1409 {
1410   return send_file_chunk (g, 0, buf, len);
1411 }
1412
1413 /* Send a cancellation message. */
1414 static int
1415 send_file_cancellation (guestfs_h *g)
1416 {
1417   char buf[1];
1418   return send_file_chunk (g, 1, buf, 0);
1419 }
1420
1421 /* Send a file complete chunk. */
1422 static int
1423 send_file_complete (guestfs_h *g)
1424 {
1425   char buf[0];
1426   return send_file_chunk (g, 0, buf, 0);
1427 }
1428 #endif
1429
1430 /* Check the return message from a call for validity. */
1431 static int
1432 check_reply_header (guestfs_h *g,
1433                     const struct guestfs_message_header *hdr,
1434                     int proc_nr, int serial)
1435 {
1436   if (hdr->prog != GUESTFS_PROGRAM) {
1437     error (g, "wrong program (%d/%d)", hdr->prog, GUESTFS_PROGRAM);
1438     return -1;
1439   }
1440   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
1441     error (g, "wrong protocol version (%d/%d)",
1442            hdr->vers, GUESTFS_PROTOCOL_VERSION);
1443     return -1;
1444   }
1445   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
1446     error (g, "unexpected message direction (%d/%d)",
1447            hdr->direction, GUESTFS_DIRECTION_REPLY);
1448     return -1;
1449   }
1450   if (hdr->proc != proc_nr) {
1451     error (g, "unexpected procedure number (%d/%d)", hdr->proc, proc_nr);
1452     return -1;
1453   }
1454   if (hdr->serial != serial) {
1455     error (g, "unexpected serial (%d/%d)", hdr->serial, serial);
1456     return -1;
1457   }
1458
1459   return 0;
1460 }
1461
1462 /* The high-level actions are autogenerated by generator.ml.  Include
1463  * them here.
1464  */
1465 #include "guestfs-actions.c"
1466
1467 /* Structure-freeing functions.  These rely on the fact that the
1468  * structure format is identical to the XDR format.  See note in
1469  * generator.ml.
1470  */
1471 void
1472 guestfs_free_int_bool (struct guestfs_int_bool *x)
1473 {
1474   free (x);
1475 }
1476
1477 void
1478 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1479 {
1480   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1481   free (x);
1482 }
1483
1484 void
1485 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1486 {
1487   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1488   free (x);
1489 }
1490
1491 void
1492 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1493 {
1494   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1495   free (x);
1496 }
1497
1498 /* This is the default main loop implementation, using select(2). */
1499
1500 static int
1501 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1502                    guestfs_handle_event_cb cb, void *data)
1503 {
1504   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1505
1506   if (fd < 0 || fd >= FD_SETSIZE) {
1507     error (g, "fd %d is out of range", fd);
1508     return -1;
1509   }
1510
1511   if ((events & ~(GUESTFS_HANDLE_READABLE |
1512                   GUESTFS_HANDLE_WRITABLE |
1513                   GUESTFS_HANDLE_HANGUP |
1514                   GUESTFS_HANDLE_ERROR)) != 0) {
1515     error (g, "set of events (0x%x) contains unknown events", events);
1516     return -1;
1517   }
1518
1519   if (events == 0) {
1520     error (g, "set of events is empty");
1521     return -1;
1522   }
1523
1524   if (FD_ISSET (fd, &ml->rset) ||
1525       FD_ISSET (fd, &ml->wset) ||
1526       FD_ISSET (fd, &ml->xset)) {
1527     error (g, "fd %d is already registered", fd);
1528     return -1;
1529   }
1530
1531   if (cb == NULL) {
1532     error (g, "callback is NULL");
1533     return -1;
1534   }
1535
1536   if ((events & GUESTFS_HANDLE_READABLE))
1537     FD_SET (fd, &ml->rset);
1538   if ((events & GUESTFS_HANDLE_WRITABLE))
1539     FD_SET (fd, &ml->wset);
1540   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1541     FD_SET (fd, &ml->xset);
1542
1543   if (fd > ml->max_fd) {
1544     ml->max_fd = fd;
1545     ml->handle_cb_data =
1546       safe_realloc (g, ml->handle_cb_data,
1547                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1548   }
1549   ml->handle_cb_data[fd].cb = cb;
1550   ml->handle_cb_data[fd].g = g;
1551   ml->handle_cb_data[fd].data = data;
1552
1553   ml->nr_fds++;
1554
1555   /* Any integer >= 0 can be the handle, and this is as good as any ... */
1556   return fd;
1557 }
1558
1559 static int
1560 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1561 {
1562   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1563
1564   if (fd < 0 || fd >= FD_SETSIZE) {
1565     error (g, "fd %d is out of range", fd);
1566     return -1;
1567   }
1568
1569   if (!FD_ISSET (fd, &ml->rset) &&
1570       !FD_ISSET (fd, &ml->wset) &&
1571       !FD_ISSET (fd, &ml->xset)) {
1572     error (g, "fd %d was not registered", fd);
1573     return -1;
1574   }
1575
1576   FD_CLR (fd, &ml->rset);
1577   FD_CLR (fd, &ml->wset);
1578   FD_CLR (fd, &ml->xset);
1579
1580   if (fd == ml->max_fd) {
1581     ml->max_fd--;
1582     ml->handle_cb_data =
1583       safe_realloc (g, ml->handle_cb_data,
1584                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1585   }
1586
1587   ml->nr_fds--;
1588
1589   return 0;
1590 }
1591
1592 static int
1593 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1594                     guestfs_handle_timeout_cb cb, void *data)
1595 {
1596   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1597
1598   abort ();                     /* XXX not implemented yet */
1599 }
1600
1601 static int
1602 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1603 {
1604   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1605
1606   abort ();                     /* XXX not implemented yet */
1607 }
1608
1609 /* The 'g' parameter is just used for error reporting.  Events
1610  * for multiple handles can be dispatched by running the main
1611  * loop.
1612  */
1613 static int
1614 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1615 {
1616   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1617   int fd, r, events;
1618   fd_set rset2, wset2, xset2;
1619
1620   if (ml->is_running) {
1621     error (g, "select_main_loop_run: this cannot be called recursively");
1622     return -1;
1623   }
1624
1625   ml->is_running = 1;
1626
1627   while (ml->is_running) {
1628     if (ml->nr_fds == 0)
1629       break;
1630
1631     rset2 = ml->rset;
1632     wset2 = ml->wset;
1633     xset2 = ml->xset;
1634     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1635     if (r == -1) {
1636       perrorf (g, "select");
1637       ml->is_running = 0;
1638       return -1;
1639     }
1640
1641     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1642       events = 0;
1643       if (FD_ISSET (fd, &rset2))
1644         events |= GUESTFS_HANDLE_READABLE;
1645       if (FD_ISSET (fd, &wset2))
1646         events |= GUESTFS_HANDLE_WRITABLE;
1647       if (FD_ISSET (fd, &xset2))
1648         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1649       if (events) {
1650         r--;
1651         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1652                                    ml->handle_cb_data[fd].g,
1653                                    ml->handle_cb_data[fd].data,
1654                                    fd, fd, events);
1655       }
1656     }
1657   }
1658
1659   ml->is_running = 0;
1660   return 0;
1661 }
1662
1663 static int
1664 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1665 {
1666   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1667
1668   if (!ml->is_running) {
1669     error (g, "cannot quit, we are not running in a main loop");
1670     return -1;
1671   }
1672
1673   ml->is_running = 0;
1674   return 0;
1675 }