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