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