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