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