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