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