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