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