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