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