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