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