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