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