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