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