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