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