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