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