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