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