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