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