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