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