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