fa8a5fc3583635c1ee294fc58e43dfe5222c3bd8
[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   const char *tmpdir;
879   char dir_template[PATH_MAX];
880   int r, i, pmore;
881   size_t len;
882   int wfd[2], rfd[2];
883   int tries;
884   char *path, *pelem, *pend;
885   char *kernel = NULL, *initrd = NULL;
886   char unixsock[256];
887   struct sockaddr_un addr;
888
889 #ifdef P_tmpdir
890   tmpdir = P_tmpdir;
891 #else
892   tmpdir = "/tmp";
893 #endif
894
895   tmpdir = getenv ("TMPDIR") ? : tmpdir;
896   snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
897
898   /* Configured? */
899   if (!g->cmdline) {
900     error (g, _("you must call guestfs_add_drive before guestfs_launch"));
901     return -1;
902   }
903
904   if (g->state != CONFIG) {
905     error (g, _("qemu has already been launched"));
906     return -1;
907   }
908
909   /* Make the temporary directory. */
910   if (!g->tmpdir) {
911     g->tmpdir = safe_strdup (g, dir_template);
912     if (mkdtemp (g->tmpdir) == NULL) {
913       perrorf (g, _("%s: cannot create temporary directory"), dir_template);
914       goto cleanup0;
915     }
916   }
917
918   /* First search g->path for the supermin appliance, and try to
919    * synthesize a kernel and initrd from that.  If it fails, we
920    * try the path search again looking for a backup ordinary
921    * appliance.
922    */
923   pelem = path = safe_strdup (g, g->path);
924   do {
925     pend = strchrnul (pelem, ':');
926     pmore = *pend == ':';
927     *pend = '\0';
928     len = pend - pelem;
929
930     /* Empty element of "." means cwd. */
931     if (len == 0 || (len == 1 && *pelem == '.')) {
932       if (g->verbose)
933         fprintf (stderr,
934                  "looking for supermin appliance in current directory\n");
935       if (dir_contains_files (".",
936                               supermin_name, supermin_hostfiles_name,
937                               "kmod.whitelist", NULL)) {
938         if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
939           return -1;
940         break;
941       }
942     }
943     /* Look at <path>/supermin* etc. */
944     else {
945       if (g->verbose)
946         fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
947
948       if (dir_contains_files (pelem,
949                               supermin_name, supermin_hostfiles_name,
950                               "kmod.whitelist", NULL)) {
951         if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
952           return -1;
953         break;
954       }
955     }
956
957     pelem = pend + 1;
958   } while (pmore);
959
960   free (path);
961
962   if (kernel == NULL || initrd == NULL) {
963     /* Search g->path for the kernel and initrd. */
964     pelem = path = safe_strdup (g, g->path);
965     do {
966       pend = strchrnul (pelem, ':');
967       pmore = *pend == ':';
968       *pend = '\0';
969       len = pend - pelem;
970
971       /* Empty element or "." means cwd. */
972       if (len == 0 || (len == 1 && *pelem == '.')) {
973         if (g->verbose)
974           fprintf (stderr,
975                    "looking for appliance in current directory\n");
976         if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
977           kernel = safe_strdup (g, kernel_name);
978           initrd = safe_strdup (g, initrd_name);
979           break;
980         }
981       }
982       /* Look at <path>/kernel etc. */
983       else {
984         if (g->verbose)
985           fprintf (stderr, "looking for appliance in %s\n", pelem);
986
987         if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
988           kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
989           initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
990           sprintf (kernel, "%s/%s", pelem, kernel_name);
991           sprintf (initrd, "%s/%s", pelem, initrd_name);
992           break;
993         }
994       }
995
996       pelem = pend + 1;
997     } while (pmore);
998
999     free (path);
1000   }
1001
1002   if (kernel == NULL || initrd == NULL) {
1003     error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1004            kernel_name, initrd_name, g->path);
1005     goto cleanup0;
1006   }
1007
1008   /* Get qemu help text and version. */
1009   if (test_qemu (g) == -1)
1010     goto cleanup0;
1011
1012   /* Make the vmchannel socket. */
1013   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1014   unlink (unixsock);
1015
1016   if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1017     perrorf (g, "pipe");
1018     goto cleanup0;
1019   }
1020
1021   r = fork ();
1022   if (r == -1) {
1023     perrorf (g, "fork");
1024     close (wfd[0]);
1025     close (wfd[1]);
1026     close (rfd[0]);
1027     close (rfd[1]);
1028     goto cleanup0;
1029   }
1030
1031   if (r == 0) {                 /* Child (qemu). */
1032     char vmchannel[256];
1033     char append[256];
1034     char memsize_str[256];
1035
1036     /* Set up the full command line.  Do this in the subprocess so we
1037      * don't need to worry about cleaning up.
1038      */
1039     g->cmdline[0] = g->qemu;
1040
1041     /* Construct the -net channel parameter for qemu. */
1042     snprintf (vmchannel, sizeof vmchannel,
1043               "channel,%d:unix:%s,server,nowait",
1044               VMCHANNEL_PORT, unixsock);
1045
1046 #define LINUX_CMDLINE                                                   \
1047     "panic=1 "         /* force kernel to panic if daemon exits */      \
1048     "console=ttyS0 "   /* serial console */                             \
1049     "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */   \
1050     "noapic "          /* workaround for RHBZ#502058 - ok if not SMP */ \
1051     "acpi=off "        /* we don't need ACPI, turn it off */
1052
1053     /* Linux kernel command line. */
1054     snprintf (append, sizeof append,
1055               LINUX_CMDLINE "guestfs=%s:%d%s%s%s",
1056               VMCHANNEL_ADDR, VMCHANNEL_PORT,
1057               g->verbose ? " guestfs_verbose=1" : "",
1058               g->append ? " " : "", g->append ? g->append : "");
1059
1060     snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1061
1062     add_cmdline (g, "-m");
1063     add_cmdline (g, memsize_str);
1064     add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1065     add_cmdline (g, "-kernel");
1066     add_cmdline (g, (char *) kernel);
1067     add_cmdline (g, "-initrd");
1068     add_cmdline (g, (char *) initrd);
1069     add_cmdline (g, "-append");
1070     add_cmdline (g, append);
1071     add_cmdline (g, "-nographic");
1072     add_cmdline (g, "-serial");
1073     add_cmdline (g, "stdio");
1074     add_cmdline (g, "-net");
1075     add_cmdline (g, vmchannel);
1076     add_cmdline (g, "-net");
1077     add_cmdline (g, "user,vlan=0");
1078     add_cmdline (g, "-net");
1079     add_cmdline (g, "nic,model=virtio,vlan=0");
1080
1081     /* These options recommended by KVM developers to improve reliability. */
1082     if (qemu_supports (g, "-no-hpet"))
1083       add_cmdline (g, "-no-hpet");
1084
1085     if (qemu_supports (g, "-rtc-td-hack"))
1086       add_cmdline (g, "-rtc-td-hack");
1087
1088     /* Finish off the command line. */
1089     incr_cmdline_size (g);
1090     g->cmdline[g->cmdline_size-1] = NULL;
1091
1092     if (g->verbose) {
1093       fprintf (stderr, "%s", g->qemu);
1094       for (i = 0; g->cmdline[i]; ++i)
1095         fprintf (stderr, " %s", g->cmdline[i]);
1096       fprintf (stderr, "\n");
1097     }
1098
1099     /* Set up stdin, stdout. */
1100     close (0);
1101     close (1);
1102     close (wfd[1]);
1103     close (rfd[0]);
1104     dup (wfd[0]);
1105     dup (rfd[1]);
1106     close (wfd[0]);
1107     close (rfd[1]);
1108
1109 #if 0
1110     /* Set up a new process group, so we can signal this process
1111      * and all subprocesses (eg. if qemu is really a shell script).
1112      */
1113     setpgid (0, 0);
1114 #endif
1115
1116     execv (g->qemu, g->cmdline); /* Run qemu. */
1117     perror (g->qemu);
1118     _exit (1);
1119   }
1120
1121   /* Parent (library). */
1122   g->pid = r;
1123
1124   free (kernel);
1125   kernel = NULL;
1126   free (initrd);
1127   initrd = NULL;
1128
1129   /* Fork the recovery process off which will kill qemu if the parent
1130    * process fails to do so (eg. if the parent segfaults).
1131    */
1132   r = fork ();
1133   if (r == 0) {
1134     pid_t qemu_pid = g->pid;
1135     pid_t parent_pid = getppid ();
1136
1137     /* Writing to argv is hideously complicated and error prone.  See:
1138      * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1139      */
1140
1141     /* Loop around waiting for one or both of the other processes to
1142      * disappear.  It's fair to say this is very hairy.  The PIDs that
1143      * we are looking at might be reused by another process.  We are
1144      * effectively polling.  Is the cure worse than the disease?
1145      */
1146     for (;;) {
1147       if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1148         _exit (0);
1149       if (kill (parent_pid, 0) == -1) {
1150         /* Parent's gone away, qemu still around, so kill qemu. */
1151         kill (qemu_pid, 9);
1152         _exit (0);
1153       }
1154       sleep (2);
1155     }
1156   }
1157
1158   /* Don't worry, if the fork failed, this will be -1.  The recovery
1159    * process isn't essential.
1160    */
1161   g->recoverypid = r;
1162
1163   /* Start the clock ... */
1164   time (&g->start_t);
1165
1166   /* Close the other ends of the pipe. */
1167   close (wfd[0]);
1168   close (rfd[1]);
1169
1170   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1171       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1172     perrorf (g, "fcntl");
1173     goto cleanup1;
1174   }
1175
1176   g->fd[0] = wfd[1];            /* stdin of child */
1177   g->fd[1] = rfd[0];            /* stdout of child */
1178
1179   /* Open the Unix socket.  The vmchannel implementation that got
1180    * merged with qemu sucks in a number of ways.  Both ends do
1181    * connect(2), which means that no one knows what, if anything, is
1182    * connected to the other end, or if it becomes disconnected.  Even
1183    * worse, we have to wait some indeterminate time for qemu to create
1184    * the socket and connect to it (which happens very early in qemu's
1185    * start-up), so any code that uses vmchannel is inherently racy.
1186    * Hence this silly loop.
1187    */
1188   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1189   if (g->sock == -1) {
1190     perrorf (g, "socket");
1191     goto cleanup1;
1192   }
1193
1194   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1195     perrorf (g, "fcntl");
1196     goto cleanup2;
1197   }
1198
1199   addr.sun_family = AF_UNIX;
1200   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1201   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1202
1203   tries = 100;
1204   /* Always sleep at least once to give qemu a small chance to start up. */
1205   usleep (10000);
1206   while (tries > 0) {
1207     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1208     if ((r == -1 && errno == EINPROGRESS) || r == 0)
1209       goto connected;
1210
1211     if (errno != ENOENT)
1212       perrorf (g, "connect");
1213     tries--;
1214     usleep (100000);
1215   }
1216
1217   error (g, _("failed to connect to vmchannel socket"));
1218   goto cleanup2;
1219
1220  connected:
1221   /* Watch the file descriptors. */
1222   free (g->msg_in);
1223   g->msg_in = NULL;
1224   g->msg_in_size = g->msg_in_allocated = 0;
1225
1226   free (g->msg_out);
1227   g->msg_out = NULL;
1228   g->msg_out_size = 0;
1229   g->msg_out_pos = 0;
1230
1231   g->stdout_watch =
1232     g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1233                               GUESTFS_HANDLE_READABLE,
1234                               stdout_event, NULL);
1235   if (g->stdout_watch == -1) {
1236     error (g, _("could not watch qemu stdout"));
1237     goto cleanup3;
1238   }
1239
1240   if (guestfs__switch_to_receiving (g) == -1)
1241     goto cleanup3;
1242
1243   g->state = LAUNCHING;
1244   return 0;
1245
1246  cleanup3:
1247   if (g->stdout_watch >= 0)
1248     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1249   if (g->sock_watch >= 0)
1250     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1251
1252  cleanup2:
1253   close (g->sock);
1254
1255  cleanup1:
1256   close (wfd[1]);
1257   close (rfd[0]);
1258   kill (g->pid, 9);
1259   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1260   waitpid (g->pid, NULL, 0);
1261   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1262   g->fd[0] = -1;
1263   g->fd[1] = -1;
1264   g->sock = -1;
1265   g->pid = 0;
1266   g->recoverypid = 0;
1267   g->start_t = 0;
1268   g->stdout_watch = -1;
1269   g->sock_watch = -1;
1270
1271  cleanup0:
1272   free (kernel);
1273   free (initrd);
1274   return -1;
1275 }
1276
1277 /* This function does the hard work of building the supermin appliance
1278  * on the fly.  'path' is the directory containing the control files.
1279  * 'kernel' and 'initrd' are where we will return the names of the
1280  * kernel and initrd (only initrd is built).  The work is done by
1281  * an external script.  We just tell it where to put the result.
1282  */
1283 static int
1284 build_supermin_appliance (guestfs_h *g, const char *path,
1285                           char **kernel, char **initrd)
1286 {
1287   char cmd[4096];
1288   int r, len;
1289
1290   len = strlen (g->tmpdir);
1291   *kernel = safe_malloc (g, len + 8);
1292   snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1293   *initrd = safe_malloc (g, len + 8);
1294   snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1295
1296   snprintf (cmd, sizeof cmd,
1297             "PATH='%s':$PATH "
1298             "libguestfs-supermin-helper '%s' %s %s",
1299             path,
1300             path, *kernel, *initrd);
1301
1302   r = system (cmd);
1303   if (r == -1 || WEXITSTATUS(r) != 0) {
1304     error (g, _("external command failed: %s"), cmd);
1305     free (*kernel);
1306     free (*initrd);
1307     *kernel = *initrd = NULL;
1308     return -1;
1309   }
1310
1311   return 0;
1312 }
1313
1314 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1315
1316 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1317  * 'qemu -version' so we know what options this qemu supports and
1318  * the version.
1319  */
1320 static int
1321 test_qemu (guestfs_h *g)
1322 {
1323   char cmd[1024];
1324   FILE *fp;
1325
1326   free (g->qemu_help);
1327   free (g->qemu_version);
1328   g->qemu_help = NULL;
1329   g->qemu_version = NULL;
1330
1331   snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1332
1333   fp = popen (cmd, "r");
1334   /* qemu -help should always work (qemu -version OTOH wasn't
1335    * supported by qemu 0.9).  If this command doesn't work then it
1336    * probably indicates that the qemu binary is missing.
1337    */
1338   if (!fp) {
1339     /* XXX This error is never printed, even if the qemu binary
1340      * doesn't exist.  Why?
1341      */
1342   error:
1343     perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1344     return -1;
1345   }
1346
1347   if (read_all (g, fp, &g->qemu_help) == -1)
1348     goto error;
1349
1350   if (pclose (fp) == -1)
1351     goto error;
1352
1353   snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1354
1355   fp = popen (cmd, "r");
1356   if (fp) {
1357     /* Intentionally ignore errors. */
1358     read_all (g, fp, &g->qemu_version);
1359     pclose (fp);
1360   }
1361
1362   return 0;
1363 }
1364
1365 static int
1366 read_all (guestfs_h *g, FILE *fp, char **ret)
1367 {
1368   int r, n = 0;
1369   char *p;
1370
1371  again:
1372   if (feof (fp)) {
1373     *ret = safe_realloc (g, *ret, n + 1);
1374     (*ret)[n] = '\0';
1375     return n;
1376   }
1377
1378   *ret = safe_realloc (g, *ret, n + BUFSIZ);
1379   p = &(*ret)[n];
1380   r = fread (p, 1, BUFSIZ, fp);
1381   if (ferror (fp)) {
1382     perrorf (g, "read");
1383     return -1;
1384   }
1385   n += r;
1386   goto again;
1387 }
1388
1389 /* Test if option is supported by qemu command line (just by grepping
1390  * the help text).
1391  */
1392 static int
1393 qemu_supports (guestfs_h *g, const char *option)
1394 {
1395   return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1396 }
1397
1398 static void
1399 finish_wait_ready (guestfs_h *g, void *vp)
1400 {
1401   if (g->verbose)
1402     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1403
1404   *((int *)vp) = 1;
1405   g->main_loop->main_loop_quit (g->main_loop, g);
1406 }
1407
1408 int
1409 guestfs_wait_ready (guestfs_h *g)
1410 {
1411   int finished = 0, r;
1412
1413   if (g->state == READY) return 0;
1414
1415   if (g->state == BUSY) {
1416     error (g, _("qemu has finished launching already"));
1417     return -1;
1418   }
1419
1420   if (g->state != LAUNCHING) {
1421     error (g, _("qemu has not been launched yet"));
1422     return -1;
1423   }
1424
1425   g->launch_done_cb = finish_wait_ready;
1426   g->launch_done_cb_data = &finished;
1427   r = g->main_loop->main_loop_run (g->main_loop, g);
1428   g->launch_done_cb = NULL;
1429   g->launch_done_cb_data = NULL;
1430
1431   if (r == -1) return -1;
1432
1433   if (finished != 1) {
1434     error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1435     return -1;
1436   }
1437
1438   /* This is possible in some really strange situations, such as
1439    * guestfsd starts up OK but then qemu immediately exits.  Check for
1440    * it because the caller is probably expecting to be able to send
1441    * commands after this function returns.
1442    */
1443   if (g->state != READY) {
1444     error (g, _("qemu launched and contacted daemon, but state != READY"));
1445     return -1;
1446   }
1447
1448   return 0;
1449 }
1450
1451 int
1452 guestfs_kill_subprocess (guestfs_h *g)
1453 {
1454   if (g->state == CONFIG) {
1455     error (g, _("no subprocess to kill"));
1456     return -1;
1457   }
1458
1459   if (g->verbose)
1460     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1461
1462   kill (g->pid, SIGTERM);
1463   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1464
1465   return 0;
1466 }
1467
1468 /* Access current state. */
1469 int
1470 guestfs_is_config (guestfs_h *g)
1471 {
1472   return g->state == CONFIG;
1473 }
1474
1475 int
1476 guestfs_is_launching (guestfs_h *g)
1477 {
1478   return g->state == LAUNCHING;
1479 }
1480
1481 int
1482 guestfs_is_ready (guestfs_h *g)
1483 {
1484   return g->state == READY;
1485 }
1486
1487 int
1488 guestfs_is_busy (guestfs_h *g)
1489 {
1490   return g->state == BUSY;
1491 }
1492
1493 int
1494 guestfs_get_state (guestfs_h *g)
1495 {
1496   return g->state;
1497 }
1498
1499 int
1500 guestfs_set_ready (guestfs_h *g)
1501 {
1502   if (g->state != BUSY) {
1503     error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1504            g->state);
1505     return -1;
1506   }
1507   g->state = READY;
1508   return 0;
1509 }
1510
1511 int
1512 guestfs_set_busy (guestfs_h *g)
1513 {
1514   if (g->state != READY) {
1515     error (g, _("guestfs_set_busy: called when in state %d != READY"),
1516            g->state);
1517     return -1;
1518   }
1519   g->state = BUSY;
1520   return 0;
1521 }
1522
1523 int
1524 guestfs_end_busy (guestfs_h *g)
1525 {
1526   switch (g->state)
1527     {
1528     case BUSY:
1529       g->state = READY;
1530       break;
1531     case CONFIG:
1532     case READY:
1533       break;
1534     case LAUNCHING:
1535     case NO_HANDLE:
1536       error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1537       return -1;
1538     }
1539   return 0;
1540 }
1541
1542 /* We don't know if stdout_event or sock_read_event will be the
1543  * first to receive EOF if the qemu process dies.  This function
1544  * has the common cleanup code for both.
1545  */
1546 static void
1547 child_cleanup (guestfs_h *g)
1548 {
1549   if (g->verbose)
1550     fprintf (stderr, "stdout_event: %p: child process died\n", g);
1551   /*kill (g->pid, SIGTERM);*/
1552   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1553   waitpid (g->pid, NULL, 0);
1554   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1555   if (g->stdout_watch >= 0)
1556     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1557   if (g->sock_watch >= 0)
1558     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1559   close (g->fd[0]);
1560   close (g->fd[1]);
1561   close (g->sock);
1562   g->fd[0] = -1;
1563   g->fd[1] = -1;
1564   g->sock = -1;
1565   g->pid = 0;
1566   g->recoverypid = 0;
1567   g->start_t = 0;
1568   g->stdout_watch = -1;
1569   g->sock_watch = -1;
1570   g->state = CONFIG;
1571   if (g->subprocess_quit_cb)
1572     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1573 }
1574
1575 /* This function is called whenever qemu prints something on stdout.
1576  * Qemu's stdout is also connected to the guest's serial console, so
1577  * we see kernel messages here too.
1578  */
1579 static void
1580 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1581               int watch, int fd, int events)
1582 {
1583   char buf[4096];
1584   int n;
1585
1586 #if 0
1587   if (g->verbose)
1588     fprintf (stderr,
1589              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1590              g, g->state, fd, events);
1591 #endif
1592
1593   if (g->fd[1] != fd) {
1594     error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1595     return;
1596   }
1597
1598   n = read (fd, buf, sizeof buf);
1599   if (n == 0) {
1600     /* Hopefully this indicates the qemu child process has died. */
1601     child_cleanup (g);
1602     return;
1603   }
1604
1605   if (n == -1) {
1606     if (errno != EINTR && errno != EAGAIN)
1607       perrorf (g, "read");
1608     return;
1609   }
1610
1611   /* In verbose mode, copy all log messages to stderr. */
1612   if (g->verbose)
1613     write (2, buf, n);
1614
1615   /* It's an actual log message, send it upwards if anyone is listening. */
1616   if (g->log_message_cb)
1617     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1618 }
1619
1620 /* The function is called whenever we can read something on the
1621  * guestfsd (daemon inside the guest) communication socket.
1622  */
1623 static void
1624 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1625                  int watch, int fd, int events)
1626 {
1627   XDR xdr;
1628   u_int32_t len;
1629   int n;
1630
1631   if (g->verbose)
1632     fprintf (stderr,
1633              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1634              g, g->state, fd, events);
1635
1636   if (g->sock != fd) {
1637     error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1638     return;
1639   }
1640
1641   if (g->msg_in_size <= g->msg_in_allocated) {
1642     g->msg_in_allocated += 4096;
1643     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1644   }
1645   n = read (g->sock, g->msg_in + g->msg_in_size,
1646             g->msg_in_allocated - g->msg_in_size);
1647   if (n == 0) {
1648     /* Disconnected. */
1649     child_cleanup (g);
1650     return;
1651   }
1652
1653   if (n == -1) {
1654     if (errno != EINTR && errno != EAGAIN)
1655       perrorf (g, "read");
1656     return;
1657   }
1658
1659   g->msg_in_size += n;
1660
1661   /* Have we got enough of a message to be able to process it yet? */
1662  again:
1663   if (g->msg_in_size < 4) return;
1664
1665   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1666   if (!xdr_uint32_t (&xdr, &len)) {
1667     error (g, _("can't decode length word"));
1668     goto cleanup;
1669   }
1670
1671   /* Length is normally the length of the message, but when guestfsd
1672    * starts up it sends a "magic" value (longer than any possible
1673    * message).  Check for this.
1674    */
1675   if (len == GUESTFS_LAUNCH_FLAG) {
1676     if (g->state != LAUNCHING)
1677       error (g, _("received magic signature from guestfsd, but in state %d"),
1678              g->state);
1679     else if (g->msg_in_size != 4)
1680       error (g, _("received magic signature from guestfsd, but msg size is %d"),
1681              g->msg_in_size);
1682     else {
1683       g->state = READY;
1684       if (g->launch_done_cb)
1685         g->launch_done_cb (g, g->launch_done_cb_data);
1686     }
1687
1688     goto cleanup;
1689   }
1690
1691   /* This can happen if a cancellation happens right at the end
1692    * of us sending a FileIn parameter to the daemon.  Discard.  The
1693    * daemon should send us an error message next.
1694    */
1695   if (len == GUESTFS_CANCEL_FLAG) {
1696     g->msg_in_size -= 4;
1697     memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1698     goto again;
1699   }
1700
1701   /* If this happens, it's pretty bad and we've probably lost
1702    * synchronization.
1703    */
1704   if (len > GUESTFS_MESSAGE_MAX) {
1705     error (g, _("message length (%u) > maximum possible size (%d)"),
1706            len, GUESTFS_MESSAGE_MAX);
1707     goto cleanup;
1708   }
1709
1710   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1711
1712   /* Got the full message, begin processing it. */
1713 #if 0
1714   if (g->verbose) {
1715     int i, j;
1716
1717     for (i = 0; i < g->msg_in_size; i += 16) {
1718       printf ("%04x: ", i);
1719       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1720         printf ("%02x ", (unsigned char) g->msg_in[j]);
1721       for (; j < i+16; ++j)
1722         printf ("   ");
1723       printf ("|");
1724       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1725         if (isprint (g->msg_in[j]))
1726           printf ("%c", g->msg_in[j]);
1727         else
1728           printf (".");
1729       for (; j < i+16; ++j)
1730         printf (" ");
1731       printf ("|\n");
1732     }
1733   }
1734 #endif
1735
1736   /* Not in the expected state. */
1737   if (g->state != BUSY)
1738     error (g, _("state %d != BUSY"), g->state);
1739
1740   /* Push the message up to the higher layer. */
1741   if (g->reply_cb)
1742     g->reply_cb (g, g->reply_cb_data, &xdr);
1743   else
1744     /* This message (probably) should never be printed. */
1745     fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1746
1747   g->msg_in_size -= len + 4;
1748   memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1749   if (g->msg_in_size > 0) goto again;
1750
1751  cleanup:
1752   /* Free the message buffer if it's grown excessively large. */
1753   if (g->msg_in_allocated > 65536) {
1754     free (g->msg_in);
1755     g->msg_in = NULL;
1756     g->msg_in_size = g->msg_in_allocated = 0;
1757   } else
1758     g->msg_in_size = 0;
1759
1760   xdr_destroy (&xdr);
1761 }
1762
1763 /* The function is called whenever we can write something on the
1764  * guestfsd (daemon inside the guest) communication socket.
1765  */
1766 static void
1767 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1768                   int watch, int fd, int events)
1769 {
1770   int n, err;
1771
1772   if (g->verbose)
1773     fprintf (stderr,
1774              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1775              g, g->state, fd, events);
1776
1777   if (g->sock != fd) {
1778     error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1779     return;
1780   }
1781
1782   if (g->state != BUSY) {
1783     error (g, _("sock_write_event: state %d != BUSY"), g->state);
1784     return;
1785   }
1786
1787   if (g->verbose)
1788     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1789              g->msg_out_size - g->msg_out_pos);
1790
1791   n = write (g->sock, g->msg_out + g->msg_out_pos,
1792              g->msg_out_size - g->msg_out_pos);
1793   if (n == -1) {
1794     err = errno;
1795     if (err != EAGAIN)
1796       perrorf (g, "write");
1797     if (err == EPIPE)   /* Disconnected from guest (RHBZ#508713). */
1798       child_cleanup (g);
1799     return;
1800   }
1801
1802   if (g->verbose)
1803     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1804
1805   g->msg_out_pos += n;
1806
1807   /* More to write? */
1808   if (g->msg_out_pos < g->msg_out_size)
1809     return;
1810
1811   if (g->verbose)
1812     fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1813
1814   free (g->msg_out);
1815   g->msg_out = NULL;
1816   g->msg_out_pos = g->msg_out_size = 0;
1817
1818   /* Done writing, call the higher layer. */
1819   if (g->send_cb)
1820     g->send_cb (g, g->send_cb_data);
1821 }
1822
1823 void
1824 guestfs_set_send_callback (guestfs_h *g,
1825                            guestfs_send_cb cb, void *opaque)
1826 {
1827   g->send_cb = cb;
1828   g->send_cb_data = opaque;
1829 }
1830
1831 void
1832 guestfs_set_reply_callback (guestfs_h *g,
1833                             guestfs_reply_cb cb, void *opaque)
1834 {
1835   g->reply_cb = cb;
1836   g->reply_cb_data = opaque;
1837 }
1838
1839 void
1840 guestfs_set_log_message_callback (guestfs_h *g,
1841                                   guestfs_log_message_cb cb, void *opaque)
1842 {
1843   g->log_message_cb = cb;
1844   g->log_message_cb_data = opaque;
1845 }
1846
1847 void
1848 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1849                                       guestfs_subprocess_quit_cb cb, void *opaque)
1850 {
1851   g->subprocess_quit_cb = cb;
1852   g->subprocess_quit_cb_data = opaque;
1853 }
1854
1855 void
1856 guestfs_set_launch_done_callback (guestfs_h *g,
1857                                   guestfs_launch_done_cb cb, void *opaque)
1858 {
1859   g->launch_done_cb = cb;
1860   g->launch_done_cb_data = opaque;
1861 }
1862
1863 /* Access to the handle's main loop and the default main loop. */
1864 void
1865 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1866 {
1867   g->main_loop = main_loop;
1868 }
1869
1870 guestfs_main_loop *
1871 guestfs_get_main_loop (guestfs_h *g)
1872 {
1873   return g->main_loop;
1874 }
1875
1876 guestfs_main_loop *
1877 guestfs_get_default_main_loop (void)
1878 {
1879   return (guestfs_main_loop *) &default_main_loop;
1880 }
1881
1882 /* Change the daemon socket handler so that we are now writing.
1883  * This sets the handle to sock_write_event.
1884  */
1885 int
1886 guestfs__switch_to_sending (guestfs_h *g)
1887 {
1888   if (g->sock_watch >= 0) {
1889     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1890       error (g, _("remove_handle failed"));
1891       g->sock_watch = -1;
1892       return -1;
1893     }
1894   }
1895
1896   g->sock_watch =
1897     g->main_loop->add_handle (g->main_loop, g, g->sock,
1898                               GUESTFS_HANDLE_WRITABLE,
1899                               sock_write_event, NULL);
1900   if (g->sock_watch == -1) {
1901     error (g, _("add_handle failed"));
1902     return -1;
1903   }
1904
1905   return 0;
1906 }
1907
1908 int
1909 guestfs__switch_to_receiving (guestfs_h *g)
1910 {
1911   if (g->sock_watch >= 0) {
1912     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1913       error (g, _("remove_handle failed"));
1914       g->sock_watch = -1;
1915       return -1;
1916     }
1917   }
1918
1919   g->sock_watch =
1920     g->main_loop->add_handle (g->main_loop, g, g->sock,
1921                               GUESTFS_HANDLE_READABLE,
1922                               sock_read_event, NULL);
1923   if (g->sock_watch == -1) {
1924     error (g, _("add_handle failed"));
1925     return -1;
1926   }
1927
1928   return 0;
1929 }
1930
1931 /* Dispatch a call (len + header + args) to the remote daemon,
1932  * synchronously (ie. using the guest's main loop to wait until
1933  * it has been sent).  Returns -1 for error, or the serial
1934  * number of the message.
1935  */
1936 static void
1937 send_cb (guestfs_h *g, void *data)
1938 {
1939   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1940
1941   *((int *)data) = 1;
1942   ml->main_loop_quit (ml, g);
1943 }
1944
1945 int
1946 guestfs__send_sync (guestfs_h *g, int proc_nr,
1947                     xdrproc_t xdrp, char *args)
1948 {
1949   struct guestfs_message_header hdr;
1950   XDR xdr;
1951   u_int32_t len;
1952   int serial = g->msg_next_serial++;
1953   int sent;
1954   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1955
1956   if (g->state != BUSY) {
1957     error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
1958     return -1;
1959   }
1960
1961   /* This is probably an internal error.  Or perhaps we should just
1962    * free the buffer anyway?
1963    */
1964   if (g->msg_out != NULL) {
1965     error (g, _("guestfs__send_sync: msg_out should be NULL"));
1966     return -1;
1967   }
1968
1969   /* We have to allocate this message buffer on the heap because
1970    * it is quite large (although will be mostly unused).  We
1971    * can't allocate it on the stack because in some environments
1972    * we have quite limited stack space available, notably when
1973    * running in the JVM.
1974    */
1975   g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1976   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1977
1978   /* Serialize the header. */
1979   hdr.prog = GUESTFS_PROGRAM;
1980   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1981   hdr.proc = proc_nr;
1982   hdr.direction = GUESTFS_DIRECTION_CALL;
1983   hdr.serial = serial;
1984   hdr.status = GUESTFS_STATUS_OK;
1985
1986   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1987     error (g, _("xdr_guestfs_message_header failed"));
1988     goto cleanup1;
1989   }
1990
1991   /* Serialize the args.  If any, because some message types
1992    * have no parameters.
1993    */
1994   if (xdrp) {
1995     if (!(*xdrp) (&xdr, args)) {
1996       error (g, _("dispatch failed to marshal args"));
1997       goto cleanup1;
1998     }
1999   }
2000
2001   /* Get the actual length of the message, resize the buffer to match
2002    * the actual length, and write the length word at the beginning.
2003    */
2004   len = xdr_getpos (&xdr);
2005   xdr_destroy (&xdr);
2006
2007   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2008   g->msg_out_size = len + 4;
2009   g->msg_out_pos = 0;
2010
2011   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2012   xdr_uint32_t (&xdr, &len);
2013
2014   if (guestfs__switch_to_sending (g) == -1)
2015     goto cleanup1;
2016
2017   sent = 0;
2018   guestfs_set_send_callback (g, send_cb, &sent);
2019   if (ml->main_loop_run (ml, g) == -1)
2020     goto cleanup1;
2021   if (sent != 1) {
2022     error (g, _("send failed, see earlier error messages"));
2023     goto cleanup1;
2024   }
2025
2026   return serial;
2027
2028  cleanup1:
2029   free (g->msg_out);
2030   g->msg_out = NULL;
2031   g->msg_out_size = 0;
2032   return -1;
2033 }
2034
2035 static int cancel = 0; /* XXX Implement file cancellation. */
2036 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2037 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2038 static int send_file_cancellation_sync (guestfs_h *g);
2039 static int send_file_complete_sync (guestfs_h *g);
2040
2041 /* Synchronously send a file.
2042  * Returns:
2043  *   0 OK
2044  *   -1 error
2045  *   -2 daemon cancelled (we must read the error message)
2046  */
2047 int
2048 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2049 {
2050   char buf[GUESTFS_MAX_CHUNK_SIZE];
2051   int fd, r, err;
2052
2053   fd = open (filename, O_RDONLY);
2054   if (fd == -1) {
2055     perrorf (g, "open: %s", filename);
2056     send_file_cancellation_sync (g);
2057     /* Daemon sees cancellation and won't reply, so caller can
2058      * just return here.
2059      */
2060     return -1;
2061   }
2062
2063   /* Send file in chunked encoding. */
2064   while (!cancel) {
2065     r = read (fd, buf, sizeof buf);
2066     if (r == -1 && (errno == EINTR || errno == EAGAIN))
2067       continue;
2068     if (r <= 0) break;
2069     err = send_file_data_sync (g, buf, r);
2070     if (err < 0) {
2071       if (err == -2)            /* daemon sent cancellation */
2072         send_file_cancellation_sync (g);
2073       return err;
2074     }
2075   }
2076
2077   if (cancel) {                 /* cancel from either end */
2078     send_file_cancellation_sync (g);
2079     return -1;
2080   }
2081
2082   if (r == -1) {
2083     perrorf (g, "read: %s", filename);
2084     send_file_cancellation_sync (g);
2085     return -1;
2086   }
2087
2088   /* End of file, but before we send that, we need to close
2089    * the file and check for errors.
2090    */
2091   if (close (fd) == -1) {
2092     perrorf (g, "close: %s", filename);
2093     send_file_cancellation_sync (g);
2094     return -1;
2095   }
2096
2097   return send_file_complete_sync (g);
2098 }
2099
2100 /* Send a chunk of file data. */
2101 static int
2102 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2103 {
2104   return send_file_chunk_sync (g, 0, buf, len);
2105 }
2106
2107 /* Send a cancellation message. */
2108 static int
2109 send_file_cancellation_sync (guestfs_h *g)
2110 {
2111   return send_file_chunk_sync (g, 1, NULL, 0);
2112 }
2113
2114 /* Send a file complete chunk. */
2115 static int
2116 send_file_complete_sync (guestfs_h *g)
2117 {
2118   char buf[1];
2119   return send_file_chunk_sync (g, 0, buf, 0);
2120 }
2121
2122 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2123  * for it to go).
2124  */
2125 static int check_for_daemon_cancellation (guestfs_h *g);
2126
2127 static int
2128 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2129 {
2130   u_int32_t len;
2131   int sent;
2132   guestfs_chunk chunk;
2133   XDR xdr;
2134   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2135
2136   if (g->state != BUSY) {
2137     error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2138     return -1;
2139   }
2140
2141   /* This is probably an internal error.  Or perhaps we should just
2142    * free the buffer anyway?
2143    */
2144   if (g->msg_out != NULL) {
2145     error (g, _("guestfs__send_sync: msg_out should be NULL"));
2146     return -1;
2147   }
2148
2149   /* Did the daemon send a cancellation message? */
2150   if (check_for_daemon_cancellation (g)) {
2151     if (g->verbose)
2152       fprintf (stderr, "got daemon cancellation\n");
2153     return -2;
2154   }
2155
2156   /* Allocate the chunk buffer.  Don't use the stack to avoid
2157    * excessive stack usage and unnecessary copies.
2158    */
2159   g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2160   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2161
2162   /* Serialize the chunk. */
2163   chunk.cancel = cancel;
2164   chunk.data.data_len = buflen;
2165   chunk.data.data_val = (char *) buf;
2166
2167   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2168     error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2169            buf, buflen);
2170     xdr_destroy (&xdr);
2171     goto cleanup1;
2172   }
2173
2174   len = xdr_getpos (&xdr);
2175   xdr_destroy (&xdr);
2176
2177   /* Reduce the size of the outgoing message buffer to the real length. */
2178   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2179   g->msg_out_size = len + 4;
2180   g->msg_out_pos = 0;
2181
2182   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2183   xdr_uint32_t (&xdr, &len);
2184
2185   if (guestfs__switch_to_sending (g) == -1)
2186     goto cleanup1;
2187
2188   sent = 0;
2189   guestfs_set_send_callback (g, send_cb, &sent);
2190   if (ml->main_loop_run (ml, g) == -1)
2191     goto cleanup1;
2192   if (sent != 1) {
2193     error (g, _("send file chunk failed, see earlier error messages"));
2194     goto cleanup1;
2195   }
2196
2197   return 0;
2198
2199  cleanup1:
2200   free (g->msg_out);
2201   g->msg_out = NULL;
2202   g->msg_out_size = 0;
2203   return -1;
2204 }
2205
2206 /* At this point we are sending FileIn file(s) to the guest, and not
2207  * expecting to read anything, so if we do read anything, it must be
2208  * a cancellation message.  This checks for this case without blocking.
2209  */
2210 static int
2211 check_for_daemon_cancellation (guestfs_h *g)
2212 {
2213   fd_set rset;
2214   struct timeval tv;
2215   int r;
2216   char buf[4];
2217   uint32_t flag;
2218   XDR xdr;
2219
2220   FD_ZERO (&rset);
2221   FD_SET (g->sock, &rset);
2222   tv.tv_sec = 0;
2223   tv.tv_usec = 0;
2224   r = select (g->sock+1, &rset, NULL, NULL, &tv);
2225   if (r == -1) {
2226     perrorf (g, "select");
2227     return 0;
2228   }
2229   if (r == 0)
2230     return 0;
2231
2232   /* Read the message from the daemon. */
2233   r = xread (g->sock, buf, sizeof buf);
2234   if (r == -1) {
2235     perrorf (g, "read");
2236     return 0;
2237   }
2238
2239   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2240   xdr_uint32_t (&xdr, &flag);
2241   xdr_destroy (&xdr);
2242
2243   if (flag != GUESTFS_CANCEL_FLAG) {
2244     error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2245            flag, GUESTFS_CANCEL_FLAG);
2246     return 0;
2247   }
2248
2249   return 1;
2250 }
2251
2252 /* Synchronously receive a file. */
2253
2254 /* Returns -1 = error, 0 = EOF, 1 = more data */
2255 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2256
2257 int
2258 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2259 {
2260   void *buf;
2261   int fd, r;
2262   size_t len;
2263
2264   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2265   if (fd == -1) {
2266     perrorf (g, "open: %s", filename);
2267     goto cancel;
2268   }
2269
2270   /* Receive the file in chunked encoding. */
2271   while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2272     if (xwrite (fd, buf, len) == -1) {
2273       perrorf (g, "%s: write", filename);
2274       free (buf);
2275       goto cancel;
2276     }
2277     free (buf);
2278     if (r == 0) break; /* End of file. */
2279   }
2280
2281   if (r == -1) {
2282     error (g, _("%s: error in chunked encoding"), filename);
2283     return -1;
2284   }
2285
2286   if (close (fd) == -1) {
2287     perrorf (g, "close: %s", filename);
2288     return -1;
2289   }
2290
2291   return 0;
2292
2293  cancel: ;
2294   /* Send cancellation message to daemon, then wait until it
2295    * cancels (just throwing away data).
2296    */
2297   XDR xdr;
2298   char fbuf[4];
2299   uint32_t flag = GUESTFS_CANCEL_FLAG;
2300
2301   if (g->verbose)
2302     fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2303              __func__);
2304
2305   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2306   xdr_uint32_t (&xdr, &flag);
2307   xdr_destroy (&xdr);
2308
2309   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2310     perrorf (g, _("write to daemon socket"));
2311     return -1;
2312   }
2313
2314   while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2315     ;                           /* just discard it */
2316
2317   return -1;
2318 }
2319
2320 /* Note that the reply callback can be called multiple times before
2321  * the main loop quits and we get back to the synchronous code.  So
2322  * we have to be prepared to save multiple chunks on a list here.
2323  */
2324 struct receive_file_ctx {
2325   int count;                    /* 0 if receive_file_cb not called, or
2326                                  * else count number of chunks.
2327                                  */
2328   guestfs_chunk *chunks;        /* Array of chunks. */
2329 };
2330
2331 static void
2332 free_chunks (struct receive_file_ctx *ctx)
2333 {
2334   int i;
2335
2336   for (i = 0; i < ctx->count; ++i)
2337     free (ctx->chunks[i].data.data_val);
2338
2339   free (ctx->chunks);
2340 }
2341
2342 static void
2343 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2344 {
2345   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2346   struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2347   guestfs_chunk chunk;
2348
2349   if (ctx->count == -1)         /* Parse error occurred previously. */
2350     return;
2351
2352   ml->main_loop_quit (ml, g);
2353
2354   memset (&chunk, 0, sizeof chunk);
2355
2356   if (!xdr_guestfs_chunk (xdr, &chunk)) {
2357     error (g, _("failed to parse file chunk"));
2358     free_chunks (ctx);
2359     ctx->chunks = NULL;
2360     ctx->count = -1;
2361     return;
2362   }
2363
2364   /* Copy the chunk to the list. */
2365   ctx->chunks = safe_realloc (g, ctx->chunks,
2366                               sizeof (guestfs_chunk) * (ctx->count+1));
2367   ctx->chunks[ctx->count] = chunk;
2368   ctx->count++;
2369 }
2370
2371 /* Receive a chunk of file data. */
2372 /* Returns -1 = error, 0 = EOF, 1 = more data */
2373 static int
2374 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2375 {
2376   struct receive_file_ctx ctx;
2377   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2378   int i;
2379   size_t len;
2380
2381   ctx.count = 0;
2382   ctx.chunks = NULL;
2383
2384   guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2385   (void) ml->main_loop_run (ml, g);
2386   guestfs_set_reply_callback (g, NULL, NULL);
2387
2388   if (ctx.count == 0) {
2389     error (g, _("receive_file_data_sync: reply callback not called\n"));
2390     return -1;
2391   }
2392
2393   if (ctx.count == -1) {
2394     error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2395     /* callback already freed the chunks */
2396     return -1;
2397   }
2398
2399   if (g->verbose)
2400     fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2401
2402   /* Process each chunk in the list. */
2403   if (buf) *buf = NULL;         /* Accumulate data in this buffer. */
2404   len = 0;
2405
2406   for (i = 0; i < ctx.count; ++i) {
2407     if (ctx.chunks[i].cancel) {
2408       error (g, _("file receive cancelled by daemon"));
2409       free_chunks (&ctx);
2410       if (buf) free (*buf);
2411       if (len_r) *len_r = 0;
2412       return -1;
2413     }
2414
2415     if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2416       free_chunks (&ctx);
2417       if (len_r) *len_r = len;
2418       return 0;
2419     }
2420
2421     if (buf) {
2422       *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2423       memcpy (*buf+len, ctx.chunks[i].data.data_val,
2424               ctx.chunks[i].data.data_len);
2425     }
2426     len += ctx.chunks[i].data.data_len;
2427   }
2428
2429   if (len_r) *len_r = len;
2430   free_chunks (&ctx);
2431   return 1;
2432 }
2433
2434 /* This is the default main loop implementation, using select(2). */
2435
2436 static int
2437 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2438                    guestfs_handle_event_cb cb, void *data)
2439 {
2440   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2441
2442   if (fd < 0 || fd >= FD_SETSIZE) {
2443     error (g, _("fd %d is out of range"), fd);
2444     return -1;
2445   }
2446
2447   if ((events & ~(GUESTFS_HANDLE_READABLE |
2448                   GUESTFS_HANDLE_WRITABLE |
2449                   GUESTFS_HANDLE_HANGUP |
2450                   GUESTFS_HANDLE_ERROR)) != 0) {
2451     error (g, _("set of events (0x%x) contains unknown events"), events);
2452     return -1;
2453   }
2454
2455   if (events == 0) {
2456     error (g, _("set of events is empty"));
2457     return -1;
2458   }
2459
2460   if (FD_ISSET (fd, &ml->rset) ||
2461       FD_ISSET (fd, &ml->wset) ||
2462       FD_ISSET (fd, &ml->xset)) {
2463     error (g, _("fd %d is already registered"), fd);
2464     return -1;
2465   }
2466
2467   if (cb == NULL) {
2468     error (g, _("callback is NULL"));
2469     return -1;
2470   }
2471
2472   if ((events & GUESTFS_HANDLE_READABLE))
2473     FD_SET (fd, &ml->rset);
2474   if ((events & GUESTFS_HANDLE_WRITABLE))
2475     FD_SET (fd, &ml->wset);
2476   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2477     FD_SET (fd, &ml->xset);
2478
2479   if (fd > ml->max_fd) {
2480     ml->max_fd = fd;
2481     ml->handle_cb_data =
2482       safe_realloc (g, ml->handle_cb_data,
2483                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2484   }
2485   ml->handle_cb_data[fd].cb = cb;
2486   ml->handle_cb_data[fd].g = g;
2487   ml->handle_cb_data[fd].data = data;
2488
2489   ml->nr_fds++;
2490
2491   /* Any integer >= 0 can be the handle, and this is as good as any ... */
2492   return fd;
2493 }
2494
2495 static int
2496 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2497 {
2498   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2499
2500   if (fd < 0 || fd >= FD_SETSIZE) {
2501     error (g, _("fd %d is out of range"), fd);
2502     return -1;
2503   }
2504
2505   if (!FD_ISSET (fd, &ml->rset) &&
2506       !FD_ISSET (fd, &ml->wset) &&
2507       !FD_ISSET (fd, &ml->xset)) {
2508     error (g, _("fd %d was not registered"), fd);
2509     return -1;
2510   }
2511
2512   FD_CLR (fd, &ml->rset);
2513   FD_CLR (fd, &ml->wset);
2514   FD_CLR (fd, &ml->xset);
2515
2516   if (fd == ml->max_fd) {
2517     ml->max_fd--;
2518     ml->handle_cb_data =
2519       safe_realloc (g, ml->handle_cb_data,
2520                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2521   }
2522
2523   ml->nr_fds--;
2524
2525   return 0;
2526 }
2527
2528 static int
2529 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2530                     guestfs_handle_timeout_cb cb, void *data)
2531 {
2532   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2533
2534   abort ();                     /* XXX not implemented yet */
2535 }
2536
2537 static int
2538 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2539 {
2540   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2541
2542   abort ();                     /* XXX not implemented yet */
2543 }
2544
2545 /* The 'g' parameter is just used for error reporting.  Events
2546  * for multiple handles can be dispatched by running the main
2547  * loop.
2548  */
2549 static int
2550 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2551 {
2552   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2553   int fd, r, events;
2554   fd_set rset2, wset2, xset2;
2555
2556   if (ml->is_running) {
2557     error (g, _("select_main_loop_run: this cannot be called recursively"));
2558     return -1;
2559   }
2560
2561   ml->is_running = 1;
2562
2563   while (ml->is_running) {
2564     if (ml->nr_fds == 0)
2565       break;
2566
2567     rset2 = ml->rset;
2568     wset2 = ml->wset;
2569     xset2 = ml->xset;
2570     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2571     if (r == -1) {
2572       if (errno == EINTR || errno == EAGAIN)
2573         continue;
2574       perrorf (g, "select");
2575       ml->is_running = 0;
2576       return -1;
2577     }
2578
2579     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2580       events = 0;
2581       if (FD_ISSET (fd, &rset2))
2582         events |= GUESTFS_HANDLE_READABLE;
2583       if (FD_ISSET (fd, &wset2))
2584         events |= GUESTFS_HANDLE_WRITABLE;
2585       if (FD_ISSET (fd, &xset2))
2586         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2587       if (events) {
2588         r--;
2589         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2590                                    ml->handle_cb_data[fd].g,
2591                                    ml->handle_cb_data[fd].data,
2592                                    fd, fd, events);
2593       }
2594     }
2595   }
2596
2597   ml->is_running = 0;
2598   return 0;
2599 }
2600
2601 static int
2602 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2603 {
2604   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2605
2606   /* Note that legitimately ml->is_running can be zero when
2607    * this function is called.
2608    */
2609
2610   ml->is_running = 0;
2611   return 0;
2612 }