Fix build_supermin_appliance to return kernel / initrd names.
[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 #if 0
934     add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
935 #endif
936     add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
937     add_cmdline (g, "-kernel");
938     add_cmdline (g, (char *) kernel);
939     add_cmdline (g, "-initrd");
940     add_cmdline (g, (char *) initrd);
941     add_cmdline (g, "-append");
942     add_cmdline (g, append);
943     add_cmdline (g, "-nographic");
944     add_cmdline (g, "-serial");
945     add_cmdline (g, "stdio");
946     add_cmdline (g, "-net");
947     add_cmdline (g, vmchannel);
948     add_cmdline (g, "-net");
949     add_cmdline (g, "user,vlan=0");
950     add_cmdline (g, "-net");
951     add_cmdline (g, "nic,model=virtio,vlan=0");
952     incr_cmdline_size (g);
953     g->cmdline[g->cmdline_size-1] = NULL;
954
955     if (g->verbose) {
956       fprintf (stderr, "%s", g->qemu);
957       for (i = 0; g->cmdline[i]; ++i)
958         fprintf (stderr, " %s", g->cmdline[i]);
959       fprintf (stderr, "\n");
960     }
961
962     /* Set up stdin, stdout. */
963     close (0);
964     close (1);
965     close (wfd[1]);
966     close (rfd[0]);
967     dup (wfd[0]);
968     dup (rfd[1]);
969     close (wfd[0]);
970     close (rfd[1]);
971
972 #if 0
973     /* Set up a new process group, so we can signal this process
974      * and all subprocesses (eg. if qemu is really a shell script).
975      */
976     setpgid (0, 0);
977 #endif
978
979     execv (g->qemu, g->cmdline); /* Run qemu. */
980     perror (g->qemu);
981     _exit (1);
982   }
983
984   /* Parent (library). */
985   g->pid = r;
986
987   free (kernel);
988   kernel = NULL;
989   free (initrd);
990   initrd = NULL;
991
992   /* Fork the recovery process off which will kill qemu if the parent
993    * process fails to do so (eg. if the parent segfaults).
994    */
995   r = fork ();
996   if (r == 0) {
997     pid_t qemu_pid = g->pid;
998     pid_t parent_pid = getppid ();
999
1000     /* Writing to argv is hideously complicated and error prone.  See:
1001      * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1002      */
1003
1004     /* Loop around waiting for one or both of the other processes to
1005      * disappear.  It's fair to say this is very hairy.  The PIDs that
1006      * we are looking at might be reused by another process.  We are
1007      * effectively polling.  Is the cure worse than the disease?
1008      */
1009     for (;;) {
1010       if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1011         _exit (0);
1012       if (kill (parent_pid, 0) == -1) {
1013         /* Parent's gone away, qemu still around, so kill qemu. */
1014         kill (qemu_pid, 9);
1015         _exit (0);
1016       }
1017       sleep (2);
1018     }
1019   }
1020
1021   /* Don't worry, if the fork failed, this will be -1.  The recovery
1022    * process isn't essential.
1023    */
1024   g->recoverypid = r;
1025
1026   /* Start the clock ... */
1027   time (&g->start_t);
1028
1029   /* Close the other ends of the pipe. */
1030   close (wfd[0]);
1031   close (rfd[1]);
1032
1033   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1034       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1035     perrorf (g, "fcntl");
1036     goto cleanup1;
1037   }
1038
1039   g->fd[0] = wfd[1];            /* stdin of child */
1040   g->fd[1] = rfd[0];            /* stdout of child */
1041
1042   /* Open the Unix socket.  The vmchannel implementation that got
1043    * merged with qemu sucks in a number of ways.  Both ends do
1044    * connect(2), which means that no one knows what, if anything, is
1045    * connected to the other end, or if it becomes disconnected.  Even
1046    * worse, we have to wait some indeterminate time for qemu to create
1047    * the socket and connect to it (which happens very early in qemu's
1048    * start-up), so any code that uses vmchannel is inherently racy.
1049    * Hence this silly loop.
1050    */
1051   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1052   if (g->sock == -1) {
1053     perrorf (g, "socket");
1054     goto cleanup1;
1055   }
1056
1057   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1058     perrorf (g, "fcntl");
1059     goto cleanup2;
1060   }
1061
1062   addr.sun_family = AF_UNIX;
1063   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1064   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1065
1066   tries = 100;
1067   /* Always sleep at least once to give qemu a small chance to start up. */
1068   usleep (10000);
1069   while (tries > 0) {
1070     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1071     if ((r == -1 && errno == EINPROGRESS) || r == 0)
1072       goto connected;
1073
1074     if (errno != ENOENT)
1075       perrorf (g, "connect");
1076     tries--;
1077     usleep (100000);
1078   }
1079
1080   error (g, _("failed to connect to vmchannel socket"));
1081   goto cleanup2;
1082
1083  connected:
1084   /* Watch the file descriptors. */
1085   free (g->msg_in);
1086   g->msg_in = NULL;
1087   g->msg_in_size = g->msg_in_allocated = 0;
1088
1089   free (g->msg_out);
1090   g->msg_out = NULL;
1091   g->msg_out_size = 0;
1092   g->msg_out_pos = 0;
1093
1094   g->stdout_watch =
1095     g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1096                               GUESTFS_HANDLE_READABLE,
1097                               stdout_event, NULL);
1098   if (g->stdout_watch == -1) {
1099     error (g, _("could not watch qemu stdout"));
1100     goto cleanup3;
1101   }
1102
1103   if (guestfs__switch_to_receiving (g) == -1)
1104     goto cleanup3;
1105
1106   g->state = LAUNCHING;
1107   return 0;
1108
1109  cleanup3:
1110   if (g->stdout_watch >= 0)
1111     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1112   if (g->sock_watch >= 0)
1113     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1114
1115  cleanup2:
1116   close (g->sock);
1117
1118  cleanup1:
1119   close (wfd[1]);
1120   close (rfd[0]);
1121   kill (g->pid, 9);
1122   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1123   waitpid (g->pid, NULL, 0);
1124   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1125   g->fd[0] = -1;
1126   g->fd[1] = -1;
1127   g->sock = -1;
1128   g->pid = 0;
1129   g->recoverypid = 0;
1130   g->start_t = 0;
1131   g->stdout_watch = -1;
1132   g->sock_watch = -1;
1133
1134  cleanup0:
1135   free (kernel);
1136   free (initrd);
1137   return -1;
1138 }
1139
1140 /* This function does the hard work of building the supermin appliance
1141  * on the fly.  'path' is the directory containing the control files.
1142  * 'kernel' and 'initrd' are where we will return the names of the
1143  * kernel and initrd (only initrd is built).  The work is done by
1144  * an external script.  We just tell it where to put the result.
1145  */
1146 static int
1147 build_supermin_appliance (guestfs_h *g, const char *path,
1148                           char **kernel, char **initrd)
1149 {
1150   char cmd[4096];
1151   int r, len;
1152
1153   len = strlen (g->tmpdir);
1154   *kernel = safe_malloc (g, len + 8);
1155   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1156   *initrd = safe_malloc (g, len + 8);
1157   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1158
1159   snprintf (cmd, sizeof cmd,
1160             "PATH='%s':$PATH "
1161             "guestfs-supermin-helper '%s' %s %s",
1162             path,
1163             path, *kernel, *initrd);
1164
1165   r = system (cmd);
1166   if (r == -1 || WEXITSTATUS(r) != 0) {
1167     error (g, _("external command failed: %s"), cmd);
1168     free (*kernel);
1169     free (*initrd);
1170     *kernel = *initrd = NULL;
1171     return -1;
1172   }
1173
1174   return 0;
1175 }
1176
1177 static void
1178 finish_wait_ready (guestfs_h *g, void *vp)
1179 {
1180   if (g->verbose)
1181     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1182
1183   *((int *)vp) = 1;
1184   g->main_loop->main_loop_quit (g->main_loop, g);
1185 }
1186
1187 int
1188 guestfs_wait_ready (guestfs_h *g)
1189 {
1190   int finished = 0, r;
1191
1192   if (g->state == READY) return 0;
1193
1194   if (g->state == BUSY) {
1195     error (g, _("qemu has finished launching already"));
1196     return -1;
1197   }
1198
1199   if (g->state != LAUNCHING) {
1200     error (g, _("qemu has not been launched yet"));
1201     return -1;
1202   }
1203
1204   g->launch_done_cb = finish_wait_ready;
1205   g->launch_done_cb_data = &finished;
1206   r = g->main_loop->main_loop_run (g->main_loop, g);
1207   g->launch_done_cb = NULL;
1208   g->launch_done_cb_data = NULL;
1209
1210   if (r == -1) return -1;
1211
1212   if (finished != 1) {
1213     error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1214     return -1;
1215   }
1216
1217   /* This is possible in some really strange situations, such as
1218    * guestfsd starts up OK but then qemu immediately exits.  Check for
1219    * it because the caller is probably expecting to be able to send
1220    * commands after this function returns.
1221    */
1222   if (g->state != READY) {
1223     error (g, _("qemu launched and contacted daemon, but state != READY"));
1224     return -1;
1225   }
1226
1227   return 0;
1228 }
1229
1230 int
1231 guestfs_kill_subprocess (guestfs_h *g)
1232 {
1233   if (g->state == CONFIG) {
1234     error (g, _("no subprocess to kill"));
1235     return -1;
1236   }
1237
1238   if (g->verbose)
1239     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1240
1241   kill (g->pid, SIGTERM);
1242   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1243
1244   return 0;
1245 }
1246
1247 /* Access current state. */
1248 int
1249 guestfs_is_config (guestfs_h *g)
1250 {
1251   return g->state == CONFIG;
1252 }
1253
1254 int
1255 guestfs_is_launching (guestfs_h *g)
1256 {
1257   return g->state == LAUNCHING;
1258 }
1259
1260 int
1261 guestfs_is_ready (guestfs_h *g)
1262 {
1263   return g->state == READY;
1264 }
1265
1266 int
1267 guestfs_is_busy (guestfs_h *g)
1268 {
1269   return g->state == BUSY;
1270 }
1271
1272 int
1273 guestfs_get_state (guestfs_h *g)
1274 {
1275   return g->state;
1276 }
1277
1278 int
1279 guestfs_set_ready (guestfs_h *g)
1280 {
1281   if (g->state != BUSY) {
1282     error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1283            g->state);
1284     return -1;
1285   }
1286   g->state = READY;
1287   return 0;
1288 }
1289
1290 int
1291 guestfs_set_busy (guestfs_h *g)
1292 {
1293   if (g->state != READY) {
1294     error (g, _("guestfs_set_busy: called when in state %d != READY"),
1295            g->state);
1296     return -1;
1297   }
1298   g->state = BUSY;
1299   return 0;
1300 }
1301
1302 int
1303 guestfs_end_busy (guestfs_h *g)
1304 {
1305   switch (g->state)
1306     {
1307     case BUSY:
1308       g->state = READY;
1309       break;
1310     case CONFIG:
1311     case READY:
1312       break;
1313     case LAUNCHING:
1314     case NO_HANDLE:
1315       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1316       return -1;
1317     }
1318   return 0;
1319 }
1320
1321 /* Structure-freeing functions.  These rely on the fact that the
1322  * structure format is identical to the XDR format.  See note in
1323  * generator.ml.
1324  */
1325 void
1326 guestfs_free_int_bool (struct guestfs_int_bool *x)
1327 {
1328   free (x);
1329 }
1330
1331 void
1332 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1333 {
1334   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1335   free (x);
1336 }
1337
1338 void
1339 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1340 {
1341   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1342   free (x);
1343 }
1344
1345 void
1346 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1347 {
1348   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1349   free (x);
1350 }
1351
1352 /* We don't know if stdout_event or sock_read_event will be the
1353  * first to receive EOF if the qemu process dies.  This function
1354  * has the common cleanup code for both.
1355  */
1356 static void
1357 child_cleanup (guestfs_h *g)
1358 {
1359   if (g->verbose)
1360     fprintf (stderr, "stdout_event: %p: child process died\n", g);
1361   /*kill (g->pid, SIGTERM);*/
1362   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1363   waitpid (g->pid, NULL, 0);
1364   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1365   if (g->stdout_watch >= 0)
1366     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1367   if (g->sock_watch >= 0)
1368     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1369   close (g->fd[0]);
1370   close (g->fd[1]);
1371   close (g->sock);
1372   g->fd[0] = -1;
1373   g->fd[1] = -1;
1374   g->sock = -1;
1375   g->pid = 0;
1376   g->recoverypid = 0;
1377   g->start_t = 0;
1378   g->stdout_watch = -1;
1379   g->sock_watch = -1;
1380   g->state = CONFIG;
1381   if (g->subprocess_quit_cb)
1382     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1383 }
1384
1385 /* This function is called whenever qemu prints something on stdout.
1386  * Qemu's stdout is also connected to the guest's serial console, so
1387  * we see kernel messages here too.
1388  */
1389 static void
1390 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1391               int watch, int fd, int events)
1392 {
1393   char buf[4096];
1394   int n;
1395
1396 #if 0
1397   if (g->verbose)
1398     fprintf (stderr,
1399              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1400              g, g->state, fd, events);
1401 #endif
1402
1403   if (g->fd[1] != fd) {
1404     error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1405     return;
1406   }
1407
1408   n = read (fd, buf, sizeof buf);
1409   if (n == 0) {
1410     /* Hopefully this indicates the qemu child process has died. */
1411     child_cleanup (g);
1412     return;
1413   }
1414
1415   if (n == -1) {
1416     if (errno != EINTR && errno != EAGAIN)
1417       perrorf (g, "read");
1418     return;
1419   }
1420
1421   /* In verbose mode, copy all log messages to stderr. */
1422   if (g->verbose)
1423     write (2, buf, n);
1424
1425   /* It's an actual log message, send it upwards if anyone is listening. */
1426   if (g->log_message_cb)
1427     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1428 }
1429
1430 /* The function is called whenever we can read something on the
1431  * guestfsd (daemon inside the guest) communication socket.
1432  */
1433 static void
1434 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1435                  int watch, int fd, int events)
1436 {
1437   XDR xdr;
1438   u_int32_t len;
1439   int n;
1440
1441   if (g->verbose)
1442     fprintf (stderr,
1443              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1444              g, g->state, fd, events);
1445
1446   if (g->sock != fd) {
1447     error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1448     return;
1449   }
1450
1451   if (g->msg_in_size <= g->msg_in_allocated) {
1452     g->msg_in_allocated += 4096;
1453     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1454   }
1455   n = read (g->sock, g->msg_in + g->msg_in_size,
1456             g->msg_in_allocated - g->msg_in_size);
1457   if (n == 0) {
1458     /* Disconnected. */
1459     child_cleanup (g);
1460     return;
1461   }
1462
1463   if (n == -1) {
1464     if (errno != EINTR && errno != EAGAIN)
1465       perrorf (g, "read");
1466     return;
1467   }
1468
1469   g->msg_in_size += n;
1470
1471   /* Have we got enough of a message to be able to process it yet? */
1472  again:
1473   if (g->msg_in_size < 4) return;
1474
1475   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1476   if (!xdr_uint32_t (&xdr, &len)) {
1477     error (g, _("can't decode length word"));
1478     goto cleanup;
1479   }
1480
1481   /* Length is normally the length of the message, but when guestfsd
1482    * starts up it sends a "magic" value (longer than any possible
1483    * message).  Check for this.
1484    */
1485   if (len == GUESTFS_LAUNCH_FLAG) {
1486     if (g->state != LAUNCHING)
1487       error (g, _("received magic signature from guestfsd, but in state %d"),
1488              g->state);
1489     else if (g->msg_in_size != 4)
1490       error (g, _("received magic signature from guestfsd, but msg size is %d"),
1491              g->msg_in_size);
1492     else {
1493       g->state = READY;
1494       if (g->launch_done_cb)
1495         g->launch_done_cb (g, g->launch_done_cb_data);
1496     }
1497
1498     goto cleanup;
1499   }
1500
1501   /* This can happen if a cancellation happens right at the end
1502    * of us sending a FileIn parameter to the daemon.  Discard.  The
1503    * daemon should send us an error message next.
1504    */
1505   if (len == GUESTFS_CANCEL_FLAG) {
1506     g->msg_in_size -= 4;
1507     memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1508     goto again;
1509   }
1510
1511   /* If this happens, it's pretty bad and we've probably lost
1512    * synchronization.
1513    */
1514   if (len > GUESTFS_MESSAGE_MAX) {
1515     error (g, _("message length (%u) > maximum possible size (%d)"),
1516            len, GUESTFS_MESSAGE_MAX);
1517     goto cleanup;
1518   }
1519
1520   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1521
1522   /* Got the full message, begin processing it. */
1523 #if 0
1524   if (g->verbose) {
1525     int i, j;
1526
1527     for (i = 0; i < g->msg_in_size; i += 16) {
1528       printf ("%04x: ", i);
1529       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1530         printf ("%02x ", (unsigned char) g->msg_in[j]);
1531       for (; j < i+16; ++j)
1532         printf ("   ");
1533       printf ("|");
1534       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1535         if (isprint (g->msg_in[j]))
1536           printf ("%c", g->msg_in[j]);
1537         else
1538           printf (".");
1539       for (; j < i+16; ++j)
1540         printf (" ");
1541       printf ("|\n");
1542     }
1543   }
1544 #endif
1545
1546   /* Not in the expected state. */
1547   if (g->state != BUSY)
1548     error (g, _("state %d != BUSY"), g->state);
1549
1550   /* Push the message up to the higher layer. */
1551   if (g->reply_cb)
1552     g->reply_cb (g, g->reply_cb_data, &xdr);
1553   else
1554     /* This message (probably) should never be printed. */
1555     fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1556
1557   g->msg_in_size -= len + 4;
1558   memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1559   if (g->msg_in_size > 0) goto again;
1560
1561  cleanup:
1562   /* Free the message buffer if it's grown excessively large. */
1563   if (g->msg_in_allocated > 65536) {
1564     free (g->msg_in);
1565     g->msg_in = NULL;
1566     g->msg_in_size = g->msg_in_allocated = 0;
1567   } else
1568     g->msg_in_size = 0;
1569
1570   xdr_destroy (&xdr);
1571 }
1572
1573 /* The function is called whenever we can write something on the
1574  * guestfsd (daemon inside the guest) communication socket.
1575  */
1576 static void
1577 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1578                   int watch, int fd, int events)
1579 {
1580   int n;
1581
1582   if (g->verbose)
1583     fprintf (stderr,
1584              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1585              g, g->state, fd, events);
1586
1587   if (g->sock != fd) {
1588     error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1589     return;
1590   }
1591
1592   if (g->state != BUSY) {
1593     error (g, _("sock_write_event: state %d != BUSY"), g->state);
1594     return;
1595   }
1596
1597   if (g->verbose)
1598     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1599              g->msg_out_size - g->msg_out_pos);
1600
1601   n = write (g->sock, g->msg_out + g->msg_out_pos,
1602              g->msg_out_size - g->msg_out_pos);
1603   if (n == -1) {
1604     if (errno != EAGAIN)
1605       perrorf (g, "write");
1606     return;
1607   }
1608
1609   if (g->verbose)
1610     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1611
1612   g->msg_out_pos += n;
1613
1614   /* More to write? */
1615   if (g->msg_out_pos < g->msg_out_size)
1616     return;
1617
1618   if (g->verbose)
1619     fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1620
1621   free (g->msg_out);
1622   g->msg_out = NULL;
1623   g->msg_out_pos = g->msg_out_size = 0;
1624
1625   /* Done writing, call the higher layer. */
1626   if (g->send_cb)
1627     g->send_cb (g, g->send_cb_data);
1628 }
1629
1630 void
1631 guestfs_set_send_callback (guestfs_h *g,
1632                            guestfs_send_cb cb, void *opaque)
1633 {
1634   g->send_cb = cb;
1635   g->send_cb_data = opaque;
1636 }
1637
1638 void
1639 guestfs_set_reply_callback (guestfs_h *g,
1640                             guestfs_reply_cb cb, void *opaque)
1641 {
1642   g->reply_cb = cb;
1643   g->reply_cb_data = opaque;
1644 }
1645
1646 void
1647 guestfs_set_log_message_callback (guestfs_h *g,
1648                                   guestfs_log_message_cb cb, void *opaque)
1649 {
1650   g->log_message_cb = cb;
1651   g->log_message_cb_data = opaque;
1652 }
1653
1654 void
1655 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1656                                       guestfs_subprocess_quit_cb cb, void *opaque)
1657 {
1658   g->subprocess_quit_cb = cb;
1659   g->subprocess_quit_cb_data = opaque;
1660 }
1661
1662 void
1663 guestfs_set_launch_done_callback (guestfs_h *g,
1664                                   guestfs_launch_done_cb cb, void *opaque)
1665 {
1666   g->launch_done_cb = cb;
1667   g->launch_done_cb_data = opaque;
1668 }
1669
1670 /* Access to the handle's main loop and the default main loop. */
1671 void
1672 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1673 {
1674   g->main_loop = main_loop;
1675 }
1676
1677 guestfs_main_loop *
1678 guestfs_get_main_loop (guestfs_h *g)
1679 {
1680   return g->main_loop;
1681 }
1682
1683 guestfs_main_loop *
1684 guestfs_get_default_main_loop (void)
1685 {
1686   return (guestfs_main_loop *) &default_main_loop;
1687 }
1688
1689 /* Change the daemon socket handler so that we are now writing.
1690  * This sets the handle to sock_write_event.
1691  */
1692 int
1693 guestfs__switch_to_sending (guestfs_h *g)
1694 {
1695   if (g->sock_watch >= 0) {
1696     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1697       error (g, _("remove_handle failed"));
1698       g->sock_watch = -1;
1699       return -1;
1700     }
1701   }
1702
1703   g->sock_watch =
1704     g->main_loop->add_handle (g->main_loop, g, g->sock,
1705                               GUESTFS_HANDLE_WRITABLE,
1706                               sock_write_event, NULL);
1707   if (g->sock_watch == -1) {
1708     error (g, _("add_handle failed"));
1709     return -1;
1710   }
1711
1712   return 0;
1713 }
1714
1715 int
1716 guestfs__switch_to_receiving (guestfs_h *g)
1717 {
1718   if (g->sock_watch >= 0) {
1719     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1720       error (g, _("remove_handle failed"));
1721       g->sock_watch = -1;
1722       return -1;
1723     }
1724   }
1725
1726   g->sock_watch =
1727     g->main_loop->add_handle (g->main_loop, g, g->sock,
1728                               GUESTFS_HANDLE_READABLE,
1729                               sock_read_event, NULL);
1730   if (g->sock_watch == -1) {
1731     error (g, _("add_handle failed"));
1732     return -1;
1733   }
1734
1735   return 0;
1736 }
1737
1738 /* Dispatch a call (len + header + args) to the remote daemon,
1739  * synchronously (ie. using the guest's main loop to wait until
1740  * it has been sent).  Returns -1 for error, or the serial
1741  * number of the message.
1742  */
1743 static void
1744 send_cb (guestfs_h *g, void *data)
1745 {
1746   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1747
1748   *((int *)data) = 1;
1749   ml->main_loop_quit (ml, g);
1750 }
1751
1752 int
1753 guestfs__send_sync (guestfs_h *g, int proc_nr,
1754                     xdrproc_t xdrp, char *args)
1755 {
1756   struct guestfs_message_header hdr;
1757   XDR xdr;
1758   u_int32_t len;
1759   int serial = g->msg_next_serial++;
1760   int sent;
1761   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1762
1763   if (g->state != BUSY) {
1764     error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1765     return -1;
1766   }
1767
1768   /* This is probably an internal error.  Or perhaps we should just
1769    * free the buffer anyway?
1770    */
1771   if (g->msg_out != NULL) {
1772     error (g, _("guestfs__send_sync: msg_out should be NULL"));
1773     return -1;
1774   }
1775
1776   /* We have to allocate this message buffer on the heap because
1777    * it is quite large (although will be mostly unused).  We
1778    * can't allocate it on the stack because in some environments
1779    * we have quite limited stack space available, notably when
1780    * running in the JVM.
1781    */
1782   g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1783   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1784
1785   /* Serialize the header. */
1786   hdr.prog = GUESTFS_PROGRAM;
1787   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1788   hdr.proc = proc_nr;
1789   hdr.direction = GUESTFS_DIRECTION_CALL;
1790   hdr.serial = serial;
1791   hdr.status = GUESTFS_STATUS_OK;
1792
1793   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1794     error (g, _("xdr_guestfs_message_header failed"));
1795     goto cleanup1;
1796   }
1797
1798   /* Serialize the args.  If any, because some message types
1799    * have no parameters.
1800    */
1801   if (xdrp) {
1802     if (!(*xdrp) (&xdr, args)) {
1803       error (g, _("dispatch failed to marshal args"));
1804       goto cleanup1;
1805     }
1806   }
1807
1808   /* Get the actual length of the message, resize the buffer to match
1809    * the actual length, and write the length word at the beginning.
1810    */
1811   len = xdr_getpos (&xdr);
1812   xdr_destroy (&xdr);
1813
1814   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1815   g->msg_out_size = len + 4;
1816   g->msg_out_pos = 0;
1817
1818   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1819   xdr_uint32_t (&xdr, &len);
1820
1821   if (guestfs__switch_to_sending (g) == -1)
1822     goto cleanup1;
1823
1824   sent = 0;
1825   guestfs_set_send_callback (g, send_cb, &sent);
1826   if (ml->main_loop_run (ml, g) == -1)
1827     goto cleanup1;
1828   if (sent != 1) {
1829     error (g, _("send failed, see earlier error messages"));
1830     goto cleanup1;
1831   }
1832
1833   return serial;
1834
1835  cleanup1:
1836   free (g->msg_out);
1837   g->msg_out = NULL;
1838   g->msg_out_size = 0;
1839   return -1;
1840 }
1841
1842 static int cancel = 0; /* XXX Implement file cancellation. */
1843 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1844 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1845 static int send_file_cancellation_sync (guestfs_h *g);
1846 static int send_file_complete_sync (guestfs_h *g);
1847
1848 /* Synchronously send a file.
1849  * Returns:
1850  *   0 OK
1851  *   -1 error
1852  *   -2 daemon cancelled (we must read the error message)
1853  */
1854 int
1855 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1856 {
1857   char buf[GUESTFS_MAX_CHUNK_SIZE];
1858   int fd, r, err;
1859
1860   fd = open (filename, O_RDONLY);
1861   if (fd == -1) {
1862     perrorf (g, "open: %s", filename);
1863     send_file_cancellation_sync (g);
1864     /* Daemon sees cancellation and won't reply, so caller can
1865      * just return here.
1866      */
1867     return -1;
1868   }
1869
1870   /* Send file in chunked encoding. */
1871   while (!cancel) {
1872     r = read (fd, buf, sizeof buf);
1873     if (r == -1 && (errno == EINTR || errno == EAGAIN))
1874       continue;
1875     if (r <= 0) break;
1876     err = send_file_data_sync (g, buf, r);
1877     if (err < 0) {
1878       if (err == -2)            /* daemon sent cancellation */
1879         send_file_cancellation_sync (g);
1880       return err;
1881     }
1882   }
1883
1884   if (cancel) {                 /* cancel from either end */
1885     send_file_cancellation_sync (g);
1886     return -1;
1887   }
1888
1889   if (r == -1) {
1890     perrorf (g, "read: %s", filename);
1891     send_file_cancellation_sync (g);
1892     return -1;
1893   }
1894
1895   /* End of file, but before we send that, we need to close
1896    * the file and check for errors.
1897    */
1898   if (close (fd) == -1) {
1899     perrorf (g, "close: %s", filename);
1900     send_file_cancellation_sync (g);
1901     return -1;
1902   }
1903
1904   return send_file_complete_sync (g);
1905 }
1906
1907 /* Send a chunk of file data. */
1908 static int
1909 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1910 {
1911   return send_file_chunk_sync (g, 0, buf, len);
1912 }
1913
1914 /* Send a cancellation message. */
1915 static int
1916 send_file_cancellation_sync (guestfs_h *g)
1917 {
1918   return send_file_chunk_sync (g, 1, NULL, 0);
1919 }
1920
1921 /* Send a file complete chunk. */
1922 static int
1923 send_file_complete_sync (guestfs_h *g)
1924 {
1925   char buf[1];
1926   return send_file_chunk_sync (g, 0, buf, 0);
1927 }
1928
1929 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1930  * for it to go).
1931  */
1932 static int check_for_daemon_cancellation (guestfs_h *g);
1933
1934 static int
1935 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
1936 {
1937   u_int32_t len;
1938   int sent;
1939   guestfs_chunk chunk;
1940   XDR xdr;
1941   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1942
1943   if (g->state != BUSY) {
1944     error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
1945     return -1;
1946   }
1947
1948   /* This is probably an internal error.  Or perhaps we should just
1949    * free the buffer anyway?
1950    */
1951   if (g->msg_out != NULL) {
1952     error (g, _("guestfs__send_sync: msg_out should be NULL"));
1953     return -1;
1954   }
1955
1956   /* Did the daemon send a cancellation message? */
1957   if (check_for_daemon_cancellation (g)) {
1958     if (g->verbose)
1959       fprintf (stderr, "got daemon cancellation\n");
1960     return -2;
1961   }
1962
1963   /* Allocate the chunk buffer.  Don't use the stack to avoid
1964    * excessive stack usage and unnecessary copies.
1965    */
1966   g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
1967   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1968
1969   /* Serialize the chunk. */
1970   chunk.cancel = cancel;
1971   chunk.data.data_len = buflen;
1972   chunk.data.data_val = (char *) buf;
1973
1974   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1975     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
1976            buf, buflen);
1977     xdr_destroy (&xdr);
1978     goto cleanup1;
1979   }
1980
1981   len = xdr_getpos (&xdr);
1982   xdr_destroy (&xdr);
1983
1984   /* Reduce the size of the outgoing message buffer to the real length. */
1985   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1986   g->msg_out_size = len + 4;
1987   g->msg_out_pos = 0;
1988
1989   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1990   xdr_uint32_t (&xdr, &len);
1991
1992   if (guestfs__switch_to_sending (g) == -1)
1993     goto cleanup1;
1994
1995   sent = 0;
1996   guestfs_set_send_callback (g, send_cb, &sent);
1997   if (ml->main_loop_run (ml, g) == -1)
1998     goto cleanup1;
1999   if (sent != 1) {
2000     error (g, _("send file chunk failed, see earlier error messages"));
2001     goto cleanup1;
2002   }
2003
2004   return 0;
2005
2006  cleanup1:
2007   free (g->msg_out);
2008   g->msg_out = NULL;
2009   g->msg_out_size = 0;
2010   return -1;
2011 }
2012
2013 /* At this point we are sending FileIn file(s) to the guest, and not
2014  * expecting to read anything, so if we do read anything, it must be
2015  * a cancellation message.  This checks for this case without blocking.
2016  */
2017 static int
2018 check_for_daemon_cancellation (guestfs_h *g)
2019 {
2020   fd_set rset;
2021   struct timeval tv;
2022   int r;
2023   char buf[4];
2024   uint32_t flag;
2025   XDR xdr;
2026
2027   FD_ZERO (&rset);
2028   FD_SET (g->sock, &rset);
2029   tv.tv_sec = 0;
2030   tv.tv_usec = 0;
2031   r = select (g->sock+1, &rset, NULL, NULL, &tv);
2032   if (r == -1) {
2033     perrorf (g, "select");
2034     return 0;
2035   }
2036   if (r == 0)
2037     return 0;
2038
2039   /* Read the message from the daemon. */
2040   r = xread (g->sock, buf, sizeof buf);
2041   if (r == -1) {
2042     perrorf (g, "read");
2043     return 0;
2044   }
2045
2046   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2047   xdr_uint32_t (&xdr, &flag);
2048   xdr_destroy (&xdr);
2049
2050   if (flag != GUESTFS_CANCEL_FLAG) {
2051     error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2052            flag, GUESTFS_CANCEL_FLAG);
2053     return 0;
2054   }
2055
2056   return 1;
2057 }
2058
2059 /* Synchronously receive a file. */
2060
2061 /* Returns -1 = error, 0 = EOF, 1 = more data */
2062 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2063
2064 int
2065 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2066 {
2067   void *buf;
2068   int fd, r;
2069   size_t len;
2070
2071   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2072   if (fd == -1) {
2073     perrorf (g, "open: %s", filename);
2074     goto cancel;
2075   }
2076
2077   /* Receive the file in chunked encoding. */
2078   while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2079     if (xwrite (fd, buf, len) == -1) {
2080       perrorf (g, "%s: write", filename);
2081       free (buf);
2082       goto cancel;
2083     }
2084     free (buf);
2085     if (r == 0) break; /* End of file. */
2086   }
2087
2088   if (r == -1) {
2089     error (g, _("%s: error in chunked encoding"), filename);
2090     return -1;
2091   }
2092
2093   if (close (fd) == -1) {
2094     perrorf (g, "close: %s", filename);
2095     return -1;
2096   }
2097
2098   return 0;
2099
2100  cancel: ;
2101   /* Send cancellation message to daemon, then wait until it
2102    * cancels (just throwing away data).
2103    */
2104   XDR xdr;
2105   char fbuf[4];
2106   uint32_t flag = GUESTFS_CANCEL_FLAG;
2107
2108   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2109   xdr_uint32_t (&xdr, &flag);
2110   xdr_destroy (&xdr);
2111
2112   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2113     perrorf (g, _("write to daemon socket"));
2114     return -1;
2115   }
2116
2117   while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2118     ;                           /* just discard it */
2119
2120   return -1;
2121 }
2122
2123 /* Note that the reply callback can be called multiple times before
2124  * the main loop quits and we get back to the synchronous code.  So
2125  * we have to be prepared to save multiple chunks on a list here.
2126  */
2127 struct receive_file_ctx {
2128   int count;                    /* 0 if receive_file_cb not called, or
2129                                  * else count number of chunks.
2130                                  */
2131   guestfs_chunk *chunks;        /* Array of chunks. */
2132 };
2133
2134 static void
2135 free_chunks (struct receive_file_ctx *ctx)
2136 {
2137   int i;
2138
2139   for (i = 0; i < ctx->count; ++i)
2140     free (ctx->chunks[i].data.data_val);
2141
2142   free (ctx->chunks);
2143 }
2144
2145 static void
2146 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2147 {
2148   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2149   struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2150   guestfs_chunk chunk;
2151
2152   if (ctx->count == -1)         /* Parse error occurred previously. */
2153     return;
2154
2155   ml->main_loop_quit (ml, g);
2156
2157   memset (&chunk, 0, sizeof chunk);
2158
2159   if (!xdr_guestfs_chunk (xdr, &chunk)) {
2160     error (g, _("failed to parse file chunk"));
2161     free_chunks (ctx);
2162     ctx->chunks = NULL;
2163     ctx->count = -1;
2164     return;
2165   }
2166
2167   /* Copy the chunk to the list. */
2168   ctx->chunks = safe_realloc (g, ctx->chunks,
2169                               sizeof (guestfs_chunk) * (ctx->count+1));
2170   ctx->chunks[ctx->count] = chunk;
2171   ctx->count++;
2172 }
2173
2174 /* Receive a chunk of file data. */
2175 /* Returns -1 = error, 0 = EOF, 1 = more data */
2176 static int
2177 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2178 {
2179   struct receive_file_ctx ctx;
2180   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2181   int i;
2182   size_t len;
2183
2184   ctx.count = 0;
2185   ctx.chunks = NULL;
2186
2187   guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2188   (void) ml->main_loop_run (ml, g);
2189   guestfs_set_reply_callback (g, NULL, NULL);
2190
2191   if (ctx.count == 0) {
2192     error (g, _("receive_file_data_sync: reply callback not called\n"));
2193     return -1;
2194   }
2195
2196   if (ctx.count == -1) {
2197     error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2198     /* callback already freed the chunks */
2199     return -1;
2200   }
2201
2202   if (g->verbose)
2203     fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2204
2205   /* Process each chunk in the list. */
2206   if (buf) *buf = NULL;         /* Accumulate data in this buffer. */
2207   len = 0;
2208
2209   for (i = 0; i < ctx.count; ++i) {
2210     if (ctx.chunks[i].cancel) {
2211       error (g, _("file receive cancelled by daemon"));
2212       free_chunks (&ctx);
2213       if (buf) free (*buf);
2214       if (len_r) *len_r = 0;
2215       return -1;
2216     }
2217
2218     if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2219       free_chunks (&ctx);
2220       if (len_r) *len_r = len;
2221       return 0;
2222     }
2223
2224     if (buf) {
2225       *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2226       memcpy (*buf+len, ctx.chunks[i].data.data_val,
2227               ctx.chunks[i].data.data_len);
2228     }
2229     len += ctx.chunks[i].data.data_len;
2230   }
2231
2232   if (len_r) *len_r = len;
2233   free_chunks (&ctx);
2234   return 1;
2235 }
2236
2237 /* This is the default main loop implementation, using select(2). */
2238
2239 static int
2240 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2241                    guestfs_handle_event_cb cb, void *data)
2242 {
2243   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2244
2245   if (fd < 0 || fd >= FD_SETSIZE) {
2246     error (g, _("fd %d is out of range"), fd);
2247     return -1;
2248   }
2249
2250   if ((events & ~(GUESTFS_HANDLE_READABLE |
2251                   GUESTFS_HANDLE_WRITABLE |
2252                   GUESTFS_HANDLE_HANGUP |
2253                   GUESTFS_HANDLE_ERROR)) != 0) {
2254     error (g, _("set of events (0x%x) contains unknown events"), events);
2255     return -1;
2256   }
2257
2258   if (events == 0) {
2259     error (g, _("set of events is empty"));
2260     return -1;
2261   }
2262
2263   if (FD_ISSET (fd, &ml->rset) ||
2264       FD_ISSET (fd, &ml->wset) ||
2265       FD_ISSET (fd, &ml->xset)) {
2266     error (g, _("fd %d is already registered"), fd);
2267     return -1;
2268   }
2269
2270   if (cb == NULL) {
2271     error (g, _("callback is NULL"));
2272     return -1;
2273   }
2274
2275   if ((events & GUESTFS_HANDLE_READABLE))
2276     FD_SET (fd, &ml->rset);
2277   if ((events & GUESTFS_HANDLE_WRITABLE))
2278     FD_SET (fd, &ml->wset);
2279   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2280     FD_SET (fd, &ml->xset);
2281
2282   if (fd > ml->max_fd) {
2283     ml->max_fd = fd;
2284     ml->handle_cb_data =
2285       safe_realloc (g, ml->handle_cb_data,
2286                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2287   }
2288   ml->handle_cb_data[fd].cb = cb;
2289   ml->handle_cb_data[fd].g = g;
2290   ml->handle_cb_data[fd].data = data;
2291
2292   ml->nr_fds++;
2293
2294   /* Any integer >= 0 can be the handle, and this is as good as any ... */
2295   return fd;
2296 }
2297
2298 static int
2299 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2300 {
2301   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2302
2303   if (fd < 0 || fd >= FD_SETSIZE) {
2304     error (g, _("fd %d is out of range"), fd);
2305     return -1;
2306   }
2307
2308   if (!FD_ISSET (fd, &ml->rset) &&
2309       !FD_ISSET (fd, &ml->wset) &&
2310       !FD_ISSET (fd, &ml->xset)) {
2311     error (g, _("fd %d was not registered"), fd);
2312     return -1;
2313   }
2314
2315   FD_CLR (fd, &ml->rset);
2316   FD_CLR (fd, &ml->wset);
2317   FD_CLR (fd, &ml->xset);
2318
2319   if (fd == ml->max_fd) {
2320     ml->max_fd--;
2321     ml->handle_cb_data =
2322       safe_realloc (g, ml->handle_cb_data,
2323                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2324   }
2325
2326   ml->nr_fds--;
2327
2328   return 0;
2329 }
2330
2331 static int
2332 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2333                     guestfs_handle_timeout_cb cb, void *data)
2334 {
2335   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2336
2337   abort ();                     /* XXX not implemented yet */
2338 }
2339
2340 static int
2341 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2342 {
2343   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2344
2345   abort ();                     /* XXX not implemented yet */
2346 }
2347
2348 /* The 'g' parameter is just used for error reporting.  Events
2349  * for multiple handles can be dispatched by running the main
2350  * loop.
2351  */
2352 static int
2353 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2354 {
2355   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2356   int fd, r, events;
2357   fd_set rset2, wset2, xset2;
2358
2359   if (ml->is_running) {
2360     error (g, _("select_main_loop_run: this cannot be called recursively"));
2361     return -1;
2362   }
2363
2364   ml->is_running = 1;
2365
2366   while (ml->is_running) {
2367     if (ml->nr_fds == 0)
2368       break;
2369
2370     rset2 = ml->rset;
2371     wset2 = ml->wset;
2372     xset2 = ml->xset;
2373     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2374     if (r == -1) {
2375       if (errno == EINTR || errno == EAGAIN)
2376         continue;
2377       perrorf (g, "select");
2378       ml->is_running = 0;
2379       return -1;
2380     }
2381
2382     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2383       events = 0;
2384       if (FD_ISSET (fd, &rset2))
2385         events |= GUESTFS_HANDLE_READABLE;
2386       if (FD_ISSET (fd, &wset2))
2387         events |= GUESTFS_HANDLE_WRITABLE;
2388       if (FD_ISSET (fd, &xset2))
2389         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2390       if (events) {
2391         r--;
2392         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2393                                    ml->handle_cb_data[fd].g,
2394                                    ml->handle_cb_data[fd].data,
2395                                    fd, fd, events);
2396       }
2397     }
2398   }
2399
2400   ml->is_running = 0;
2401   return 0;
2402 }
2403
2404 static int
2405 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2406 {
2407   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2408
2409   /* Note that legitimately ml->is_running can be zero when
2410    * this function is called.
2411    */
2412
2413   ml->is_running = 0;
2414   return 0;
2415 }