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