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