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