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