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