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