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