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