Implement upload and download commands.
[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     add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
734     add_cmdline (g, "-kernel");
735     add_cmdline (g, (char *) kernel);
736     add_cmdline (g, "-initrd");
737     add_cmdline (g, (char *) initrd);
738     add_cmdline (g, "-append");
739     add_cmdline (g, append);
740     add_cmdline (g, "-nographic");
741     add_cmdline (g, "-serial");
742     add_cmdline (g, "stdio");
743     add_cmdline (g, "-net");
744     add_cmdline (g, vmchannel);
745     add_cmdline (g, "-net");
746     add_cmdline (g, "user,vlan=0");
747     add_cmdline (g, "-net");
748     add_cmdline (g, "nic,vlan=0");
749     incr_cmdline_size (g);
750     g->cmdline[g->cmdline_size-1] = NULL;
751
752     if (g->verbose) {
753       fprintf (stderr, "%s", QEMU);
754       for (i = 0; g->cmdline[i]; ++i)
755         fprintf (stderr, " %s", g->cmdline[i]);
756       fprintf (stderr, "\n");
757     }
758
759     /* Set up stdin, stdout. */
760     close (0);
761     close (1);
762     close (wfd[1]);
763     close (rfd[0]);
764     dup (wfd[0]);
765     dup (rfd[1]);
766     close (wfd[0]);
767     close (rfd[1]);
768
769 #if 0
770     /* Set up a new process group, so we can signal this process
771      * and all subprocesses (eg. if qemu is really a shell script).
772      */
773     setpgid (0, 0);
774 #endif
775
776     execv (QEMU, g->cmdline);   /* Run qemu. */
777     perror (QEMU);
778     _exit (1);
779   }
780
781   /* Parent (library). */
782   g->pid = r;
783
784   /* Start the clock ... */
785   time (&g->start_t);
786
787   /* Close the other ends of the pipe. */
788   close (wfd[0]);
789   close (rfd[1]);
790
791   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
792       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
793     perrorf (g, "fcntl");
794     goto cleanup1;
795   }
796
797   g->fd[0] = wfd[1];            /* stdin of child */
798   g->fd[1] = rfd[0];            /* stdout of child */
799
800   /* Open the Unix socket.  The vmchannel implementation that got
801    * merged with qemu sucks in a number of ways.  Both ends do
802    * connect(2), which means that no one knows what, if anything, is
803    * connected to the other end, or if it becomes disconnected.  Even
804    * worse, we have to wait some indeterminate time for qemu to create
805    * the socket and connect to it (which happens very early in qemu's
806    * start-up), so any code that uses vmchannel is inherently racy.
807    * Hence this silly loop.
808    */
809   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
810   if (g->sock == -1) {
811     perrorf (g, "socket");
812     goto cleanup1;
813   }
814
815   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
816     perrorf (g, "fcntl");
817     goto cleanup2;
818   }
819
820   addr.sun_family = AF_UNIX;
821   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
822   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
823
824   tries = 100;
825   while (tries > 0) {
826     /* Always sleep at least once to give qemu a small chance to start up. */
827     usleep (10000);
828
829     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
830     if ((r == -1 && errno == EINPROGRESS) || r == 0)
831       goto connected;
832
833     if (errno != ENOENT)
834       perrorf (g, "connect");
835     tries--;
836   }
837
838   error (g, "failed to connect to vmchannel socket");
839   goto cleanup2;
840
841  connected:
842   /* Watch the file descriptors. */
843   free (g->msg_in);
844   g->msg_in = NULL;
845   g->msg_in_size = g->msg_in_allocated = 0;
846
847   free (g->msg_out);
848   g->msg_out = NULL;
849   g->msg_out_size = 0;
850   g->msg_out_pos = 0;
851
852   g->stdout_watch =
853     g->main_loop->add_handle (g->main_loop, g, g->fd[1],
854                               GUESTFS_HANDLE_READABLE,
855                               stdout_event, NULL);
856   if (g->stdout_watch == -1) {
857     error (g, "could not watch qemu stdout");
858     goto cleanup3;
859   }
860
861   if (guestfs__switch_to_receiving (g) == -1)
862     goto cleanup3;
863
864   g->state = LAUNCHING;
865   return 0;
866
867  cleanup3:
868   if (g->stdout_watch >= 0)
869     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
870   if (g->sock_watch >= 0)
871     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
872
873  cleanup2:
874   close (g->sock);
875
876  cleanup1:
877   close (wfd[1]);
878   close (rfd[0]);
879   kill (g->pid, 9);
880   waitpid (g->pid, NULL, 0);
881   g->fd[0] = -1;
882   g->fd[1] = -1;
883   g->sock = -1;
884   g->pid = 0;
885   g->start_t = 0;
886   g->stdout_watch = -1;
887   g->sock_watch = -1;
888
889  cleanup0:
890   free (kernel);
891   free (initrd);
892   return -1;
893 }
894
895 static void
896 finish_wait_ready (guestfs_h *g, void *vp)
897 {
898   if (g->verbose)
899     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
900
901   *((int *)vp) = 1;
902   g->main_loop->main_loop_quit (g->main_loop, g);
903 }
904
905 int
906 guestfs_wait_ready (guestfs_h *g)
907 {
908   int finished = 0, r;
909
910   if (g->state == READY) return 0;
911
912   if (g->state == BUSY) {
913     error (g, "qemu has finished launching already");
914     return -1;
915   }
916
917   if (g->state != LAUNCHING) {
918     error (g, "qemu has not been launched yet");
919     return -1;
920   }
921
922   g->launch_done_cb = finish_wait_ready;
923   g->launch_done_cb_data = &finished;
924   r = g->main_loop->main_loop_run (g->main_loop, g);
925   g->launch_done_cb = NULL;
926   g->launch_done_cb_data = NULL;
927
928   if (r == -1) return -1;
929
930   if (finished != 1) {
931     error (g, "guestfs_wait_ready failed, see earlier error messages");
932     return -1;
933   }
934
935   /* This is possible in some really strange situations, such as
936    * guestfsd starts up OK but then qemu immediately exits.  Check for
937    * it because the caller is probably expecting to be able to send
938    * commands after this function returns.
939    */
940   if (g->state != READY) {
941     error (g, "qemu launched and contacted daemon, but state != READY");
942     return -1;
943   }
944
945   return 0;
946 }
947
948 int
949 guestfs_kill_subprocess (guestfs_h *g)
950 {
951   if (g->state == CONFIG) {
952     error (g, "no subprocess to kill");
953     return -1;
954   }
955
956   if (g->verbose)
957     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
958
959   kill (g->pid, SIGTERM);
960
961   return 0;
962 }
963
964 /* Access current state. */
965 int
966 guestfs_is_config (guestfs_h *g)
967 {
968   return g->state == CONFIG;
969 }
970
971 int
972 guestfs_is_launching (guestfs_h *g)
973 {
974   return g->state == LAUNCHING;
975 }
976
977 int
978 guestfs_is_ready (guestfs_h *g)
979 {
980   return g->state == READY;
981 }
982
983 int
984 guestfs_is_busy (guestfs_h *g)
985 {
986   return g->state == BUSY;
987 }
988
989 int
990 guestfs_get_state (guestfs_h *g)
991 {
992   return g->state;
993 }
994
995 int
996 guestfs_set_ready (guestfs_h *g)
997 {
998   if (g->state != BUSY) {
999     error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1000     return -1;
1001   }
1002   g->state = READY;
1003   return 0;
1004 }
1005
1006 int
1007 guestfs_set_busy (guestfs_h *g)
1008 {
1009   if (g->state != READY) {
1010     error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1011     return -1;
1012   }
1013   g->state = BUSY;
1014   return 0;
1015 }
1016
1017 /* Structure-freeing functions.  These rely on the fact that the
1018  * structure format is identical to the XDR format.  See note in
1019  * generator.ml.
1020  */
1021 void
1022 guestfs_free_int_bool (struct guestfs_int_bool *x)
1023 {
1024   free (x);
1025 }
1026
1027 void
1028 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1029 {
1030   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1031   free (x);
1032 }
1033
1034 void
1035 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1036 {
1037   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1038   free (x);
1039 }
1040
1041 void
1042 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1043 {
1044   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1045   free (x);
1046 }
1047
1048 /* This function is called whenever qemu prints something on stdout.
1049  * Qemu's stdout is also connected to the guest's serial console, so
1050  * we see kernel messages here too.
1051  */
1052 static void
1053 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1054               int watch, int fd, int events)
1055 {
1056   char buf[4096];
1057   int n;
1058
1059 #if 0
1060   if (g->verbose)
1061     fprintf (stderr,
1062              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1063              g, g->state, fd, events);
1064 #endif
1065
1066   if (g->fd[1] != fd) {
1067     error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1068     return;
1069   }
1070
1071   n = read (fd, buf, sizeof buf);
1072   if (n == 0) {
1073     /* Hopefully this indicates the qemu child process has died. */
1074     if (g->verbose)
1075       fprintf (stderr, "stdout_event: %p: child process died\n", g);
1076     /*kill (g->pid, SIGTERM);*/
1077     waitpid (g->pid, NULL, 0);
1078     if (g->stdout_watch >= 0)
1079       g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1080     if (g->sock_watch >= 0)
1081       g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1082     close (g->fd[0]);
1083     close (g->fd[1]);
1084     close (g->sock);
1085     g->fd[0] = -1;
1086     g->fd[1] = -1;
1087     g->sock = -1;
1088     g->pid = 0;
1089     g->start_t = 0;
1090     g->stdout_watch = -1;
1091     g->sock_watch = -1;
1092     g->state = CONFIG;
1093     if (g->subprocess_quit_cb)
1094       g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1095     return;
1096   }
1097
1098   if (n == -1) {
1099     if (errno != EAGAIN)
1100       perrorf (g, "read");
1101     return;
1102   }
1103
1104   /* In verbose mode, copy all log messages to stderr. */
1105   if (g->verbose)
1106     write (2, buf, n);
1107
1108   /* It's an actual log message, send it upwards if anyone is listening. */
1109   if (g->log_message_cb)
1110     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1111 }
1112
1113 /* The function is called whenever we can read something on the
1114  * guestfsd (daemon inside the guest) communication socket.
1115  */
1116 static void
1117 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1118                  int watch, int fd, int events)
1119 {
1120   XDR xdr;
1121   unsigned len;
1122   int n;
1123
1124   if (g->verbose)
1125     fprintf (stderr,
1126              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1127              g, g->state, fd, events);
1128
1129   if (g->sock != fd) {
1130     error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1131     return;
1132   }
1133
1134   if (g->msg_in_size <= g->msg_in_allocated) {
1135     g->msg_in_allocated += 4096;
1136     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1137   }
1138   n = read (g->sock, g->msg_in + g->msg_in_size,
1139             g->msg_in_allocated - g->msg_in_size);
1140   if (n == 0)
1141     /* Disconnected?  Ignore it because stdout_watch will get called
1142      * and will do the cleanup.
1143      */
1144     return;
1145
1146   if (n == -1) {
1147     if (errno != EAGAIN)
1148       perrorf (g, "read");
1149     return;
1150   }
1151
1152   g->msg_in_size += n;
1153
1154   /* Have we got enough of a message to be able to process it yet? */
1155  again:
1156   if (g->msg_in_size < 4) return;
1157
1158   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1159   if (!xdr_uint32_t (&xdr, &len)) {
1160     error (g, "can't decode length word");
1161     goto cleanup;
1162   }
1163
1164   /* Length is normally the length of the message, but when guestfsd
1165    * starts up it sends a "magic" value (longer than any possible
1166    * message).  Check for this.
1167    */
1168   if (len == GUESTFS_LAUNCH_FLAG) {
1169     if (g->state != LAUNCHING)
1170       error (g, "received magic signature from guestfsd, but in state %d",
1171              g->state);
1172     else if (g->msg_in_size != 4)
1173       error (g, "received magic signature from guestfsd, but msg size is %d",
1174              g->msg_in_size);
1175     else {
1176       g->state = READY;
1177       if (g->launch_done_cb)
1178         g->launch_done_cb (g, g->launch_done_cb_data);
1179     }
1180
1181     goto cleanup;
1182   }
1183
1184   /* This can happen if a cancellation happens right at the end
1185    * of us sending a FileIn parameter to the daemon.  Discard.  The
1186    * daemon should send us an error message next.
1187    */
1188   if (len == GUESTFS_CANCEL_FLAG) {
1189     g->msg_in_size -= 4;
1190     memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1191     goto again;
1192   }
1193
1194   /* If this happens, it's pretty bad and we've probably lost
1195    * synchronization.
1196    */
1197   if (len > GUESTFS_MESSAGE_MAX) {
1198     error (g, "message length (%u) > maximum possible size (%d)",
1199            len, GUESTFS_MESSAGE_MAX);
1200     goto cleanup;
1201   }
1202
1203   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1204
1205   /* Got the full message, begin processing it. */
1206   if (g->verbose) {
1207     int i, j;
1208
1209     for (i = 0; i < g->msg_in_size; i += 16) {
1210       printf ("%04x: ", i);
1211       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1212         printf ("%02x ", (unsigned char) g->msg_in[j]);
1213       for (; j < i+16; ++j)
1214         printf ("   ");
1215       printf ("|");
1216       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1217         if (isprint (g->msg_in[j]))
1218           printf ("%c", g->msg_in[j]);
1219         else
1220           printf (".");
1221       for (; j < i+16; ++j)
1222         printf (" ");
1223       printf ("|\n");
1224     }
1225   }
1226
1227   /* Not in the expected state. */
1228   if (g->state != BUSY)
1229     error (g, "state %d != BUSY", g->state);
1230
1231   /* Push the message up to the higher layer. */
1232   if (g->reply_cb)
1233     g->reply_cb (g, g->reply_cb_data, &xdr);
1234
1235   g->msg_in_size -= len + 4;
1236   memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1237   if (g->msg_in_size > 0) goto again;
1238
1239  cleanup:
1240   /* Free the message buffer if it's grown excessively large. */
1241   if (g->msg_in_allocated > 65536) {
1242     free (g->msg_in);
1243     g->msg_in = NULL;
1244     g->msg_in_size = g->msg_in_allocated = 0;
1245   } else
1246     g->msg_in_size = 0;
1247
1248   xdr_destroy (&xdr);
1249 }
1250
1251 /* The function is called whenever we can write something on the
1252  * guestfsd (daemon inside the guest) communication socket.
1253  */
1254 static void
1255 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1256                   int watch, int fd, int events)
1257 {
1258   int n;
1259
1260   if (g->verbose)
1261     fprintf (stderr,
1262              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1263              g, g->state, fd, events);
1264
1265   if (g->sock != fd) {
1266     error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1267     return;
1268   }
1269
1270   if (g->state != BUSY) {
1271     error (g, "sock_write_event: state %d != BUSY", g->state);
1272     return;
1273   }
1274
1275   if (g->verbose)
1276     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1277              g->msg_out_size - g->msg_out_pos);
1278
1279   n = write (g->sock, g->msg_out + g->msg_out_pos,
1280              g->msg_out_size - g->msg_out_pos);
1281   if (n == -1) {
1282     if (errno != EAGAIN)
1283       perrorf (g, "write");
1284     return;
1285   }
1286
1287   if (g->verbose)
1288     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1289
1290   g->msg_out_pos += n;
1291
1292   /* More to write? */
1293   if (g->msg_out_pos < g->msg_out_size)
1294     return;
1295
1296   if (g->verbose)
1297     fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1298
1299   free (g->msg_out);
1300   g->msg_out = NULL;
1301   g->msg_out_pos = g->msg_out_size = 0;
1302
1303   /* Done writing, call the higher layer. */
1304   if (g->send_cb)
1305     g->send_cb (g, g->send_cb_data);
1306 }
1307
1308 void
1309 guestfs_set_send_callback (guestfs_h *g,
1310                            guestfs_send_cb cb, void *opaque)
1311 {
1312   g->send_cb = cb;
1313   g->send_cb_data = opaque;
1314 }
1315
1316 void
1317 guestfs_set_reply_callback (guestfs_h *g,
1318                             guestfs_reply_cb cb, void *opaque)
1319 {
1320   g->reply_cb = cb;
1321   g->reply_cb_data = opaque;
1322 }
1323
1324 void
1325 guestfs_set_log_message_callback (guestfs_h *g,
1326                                   guestfs_log_message_cb cb, void *opaque)
1327 {
1328   g->log_message_cb = cb;
1329   g->log_message_cb_data = opaque;
1330 }
1331
1332 void
1333 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1334                                       guestfs_subprocess_quit_cb cb, void *opaque)
1335 {
1336   g->subprocess_quit_cb = cb;
1337   g->subprocess_quit_cb_data = opaque;
1338 }
1339
1340 void
1341 guestfs_set_launch_done_callback (guestfs_h *g,
1342                                   guestfs_launch_done_cb cb, void *opaque)
1343 {
1344   g->launch_done_cb = cb;
1345   g->launch_done_cb_data = opaque;
1346 }
1347
1348 /* Access to the handle's main loop and the default main loop. */
1349 void
1350 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1351 {
1352   g->main_loop = main_loop;
1353 }
1354
1355 guestfs_main_loop *
1356 guestfs_get_main_loop (guestfs_h *g)
1357 {
1358   return g->main_loop;
1359 }
1360
1361 guestfs_main_loop *
1362 guestfs_get_default_main_loop (void)
1363 {
1364   return (guestfs_main_loop *) &default_main_loop;
1365 }
1366
1367 /* Change the daemon socket handler so that we are now writing.
1368  * This sets the handle to sock_write_event.
1369  */
1370 int
1371 guestfs__switch_to_sending (guestfs_h *g)
1372 {
1373   if (g->sock_watch >= 0) {
1374     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1375       error (g, "remove_handle failed");
1376       g->sock_watch = -1;
1377       return -1;
1378     }
1379   }
1380
1381   g->sock_watch =
1382     g->main_loop->add_handle (g->main_loop, g, g->sock,
1383                               GUESTFS_HANDLE_WRITABLE,
1384                               sock_write_event, NULL);
1385   if (g->sock_watch == -1) {
1386     error (g, "add_handle failed");
1387     return -1;
1388   }
1389
1390   return 0;
1391 }
1392
1393 int
1394 guestfs__switch_to_receiving (guestfs_h *g)
1395 {
1396   if (g->sock_watch >= 0) {
1397     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1398       error (g, "remove_handle failed");
1399       g->sock_watch = -1;
1400       return -1;
1401     }
1402   }
1403
1404   g->sock_watch =
1405     g->main_loop->add_handle (g->main_loop, g, g->sock,
1406                               GUESTFS_HANDLE_READABLE,
1407                               sock_read_event, NULL);
1408   if (g->sock_watch == -1) {
1409     error (g, "add_handle failed");
1410     return -1;
1411   }
1412
1413   return 0;
1414 }
1415
1416 /* Dispatch a call (len + header + args) to the remote daemon,
1417  * synchronously (ie. using the guest's main loop to wait until
1418  * it has been sent).  Returns -1 for error, or the serial
1419  * number of the message.
1420  */
1421 static void
1422 send_cb (guestfs_h *g, void *data)
1423 {
1424   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1425
1426   *((int *)data) = 1;
1427   ml->main_loop_quit (ml, g);
1428 }
1429
1430 int
1431 guestfs__send_sync (guestfs_h *g, int proc_nr,
1432                     xdrproc_t xdrp, char *args)
1433 {
1434   char buffer[GUESTFS_MESSAGE_MAX];
1435   struct guestfs_message_header hdr;
1436   XDR xdr;
1437   unsigned len;
1438   int serial = g->msg_next_serial++;
1439   int sent;
1440   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1441
1442   if (g->state != BUSY) {
1443     error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1444     return -1;
1445   }
1446
1447   /* Serialize the header. */
1448   hdr.prog = GUESTFS_PROGRAM;
1449   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1450   hdr.proc = proc_nr;
1451   hdr.direction = GUESTFS_DIRECTION_CALL;
1452   hdr.serial = serial;
1453   hdr.status = GUESTFS_STATUS_OK;
1454
1455   xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1456   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1457     error (g, "xdr_guestfs_message_header failed");
1458     return -1;
1459   }
1460
1461   /* Serialize the args.  If any, because some message types
1462    * have no parameters.
1463    */
1464   if (xdrp) {
1465     if (!(*xdrp) (&xdr, args)) {
1466       error (g, "dispatch failed to marshal args");
1467       return -1;
1468     }
1469   }
1470
1471   len = xdr_getpos (&xdr);
1472   xdr_destroy (&xdr);
1473
1474   /* Allocate the outgoing message buffer. */
1475   g->msg_out = safe_malloc (g, len + 4);
1476
1477   g->msg_out_size = len + 4;
1478   g->msg_out_pos = 0;
1479
1480   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1481   xdr_uint32_t (&xdr, &len);
1482
1483   memcpy (g->msg_out + 4, buffer, len);
1484
1485   if (guestfs__switch_to_sending (g) == -1)
1486     goto cleanup1;
1487
1488   sent = 0;
1489   guestfs_set_send_callback (g, send_cb, &sent);
1490   if (ml->main_loop_run (ml, g) == -1)
1491     goto cleanup1;
1492   if (sent != 1) {
1493     error (g, "send failed, see earlier error messages");
1494     goto cleanup1;
1495   }
1496
1497   return serial;
1498
1499  cleanup1:
1500   free (g->msg_out);
1501   g->msg_out = NULL;
1502   g->msg_out_size = 0;
1503   return -1;
1504 }
1505
1506 static int cancel = 0; /* XXX Implement file cancellation. */
1507 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1508 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1509 static int send_file_cancellation_sync (guestfs_h *g);
1510 static int send_file_complete_sync (guestfs_h *g);
1511
1512 /* Synchronously send a file.
1513  * Returns:
1514  *   0 OK
1515  *   -1 error
1516  *   -2 daemon cancelled (we must read the error message)
1517  */
1518 int
1519 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1520 {
1521   char buf[GUESTFS_MAX_CHUNK_SIZE];
1522   int fd, r, err;
1523
1524   fd = open (filename, O_RDONLY);
1525   if (fd == -1) {
1526     perrorf (g, "open: %s", filename);
1527     send_file_cancellation_sync (g);
1528     /* Daemon sees cancellation and won't reply, so caller can
1529      * just return here.
1530      */
1531     return -1;
1532   }
1533
1534   /* Send file in chunked encoding. */
1535   while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1536     err = send_file_data_sync (g, buf, r);
1537     if (err < 0)
1538       return err;
1539   }
1540
1541   if (cancel) {
1542     send_file_cancellation_sync (g);
1543     return -1;
1544   }
1545
1546   if (r == -1) {
1547     perrorf (g, "read: %s", filename);
1548     send_file_cancellation_sync (g);
1549     return -1;
1550   }
1551
1552   /* End of file, but before we send that, we need to close
1553    * the file and check for errors.
1554    */
1555   if (close (fd) == -1) {
1556     perrorf (g, "close: %s", filename);
1557     send_file_cancellation_sync (g);
1558     return -1;
1559   }
1560
1561   return send_file_complete_sync (g);
1562 }
1563
1564 /* Send a chunk of file data. */
1565 static int
1566 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1567 {
1568   return send_file_chunk_sync (g, 0, buf, len);
1569 }
1570
1571 /* Send a cancellation message. */
1572 static int
1573 send_file_cancellation_sync (guestfs_h *g)
1574 {
1575   return send_file_chunk_sync (g, 1, NULL, 0);
1576 }
1577
1578 /* Send a file complete chunk. */
1579 static int
1580 send_file_complete_sync (guestfs_h *g)
1581 {
1582   char buf[1];
1583   return send_file_chunk_sync (g, 0, buf, 0);
1584 }
1585
1586 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1587  * for it to go).
1588  */
1589 static int check_for_daemon_cancellation (guestfs_h *g);
1590
1591 static int
1592 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len)
1593 {
1594   char data[GUESTFS_MAX_CHUNK_SIZE + 48];
1595   unsigned datalen;
1596   int sent;
1597   guestfs_chunk chunk;
1598   XDR xdr;
1599   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1600
1601   if (g->state != BUSY) {
1602     error (g, "send_file_chunk_sync: state %d != READY", g->state);
1603     return -1;
1604   }
1605
1606   /* Did the daemon send a cancellation message? */
1607   if (check_for_daemon_cancellation (g))
1608     return -2;
1609
1610   /* Serialize the chunk. */
1611   chunk.cancel = cancel;
1612   chunk.data.data_len = len;
1613   chunk.data.data_val = (char *) buf;
1614
1615   xdrmem_create (&xdr, data, sizeof data, XDR_ENCODE);
1616   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1617     error (g, "xdr_guestfs_chunk failed (buf = %p, len = %zu)", buf, len);
1618     xdr_destroy (&xdr);
1619     return -1;
1620   }
1621
1622   datalen = xdr_getpos (&xdr);
1623   xdr_destroy (&xdr);
1624
1625   /* Allocate outgoing message buffer. */
1626   g->msg_out = safe_malloc (g, datalen + 4);
1627   g->msg_out_size = datalen + 4;
1628   g->msg_out_pos = 0;
1629
1630   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1631   xdr_uint32_t (&xdr, &datalen);
1632
1633   memcpy (g->msg_out + 4, data, datalen);
1634
1635   if (guestfs__switch_to_sending (g) == -1)
1636     goto cleanup1;
1637
1638   sent = 0;
1639   guestfs_set_send_callback (g, send_cb, &sent);
1640   if (ml->main_loop_run (ml, g) == -1)
1641     goto cleanup1;
1642   if (sent != 1) {
1643     error (g, "send file chunk failed, see earlier error messages");
1644     goto cleanup1;
1645   }
1646
1647   return 0;
1648
1649  cleanup1:
1650   free (g->msg_out);
1651   g->msg_out = NULL;
1652   g->msg_out_size = 0;
1653   return -1;
1654 }
1655
1656 /* At this point we are sending FileIn file(s) to the guest, and not
1657  * expecting to read anything, so if we do read anything, it must be
1658  * a cancellation message.  This checks for this case without blocking.
1659  */
1660 static int
1661 check_for_daemon_cancellation (guestfs_h *g)
1662 {
1663   fd_set rset;
1664   struct timeval tv;
1665   int r;
1666   char buf[4];
1667   uint32_t flag;
1668   XDR xdr;
1669
1670   FD_ZERO (&rset);
1671   FD_SET (g->sock, &rset);
1672   tv.tv_sec = 0;
1673   tv.tv_usec = 0;
1674   r = select (g->sock+1, &rset, NULL, NULL, &tv);
1675   if (r == -1) {
1676     perrorf (g, "select");
1677     return 0;
1678   }
1679   if (r == 0)
1680     return 0;
1681
1682   /* Read the message from the daemon. */
1683   r = xread (g->sock, buf, sizeof buf);
1684   if (r == -1) {
1685     perrorf (g, "read");
1686     return 0;
1687   }
1688
1689   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1690   xdr_uint32_t (&xdr, &flag);
1691   xdr_destroy (&xdr);
1692
1693   if (flag != GUESTFS_CANCEL_FLAG) {
1694     error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1695            flag, GUESTFS_CANCEL_FLAG);
1696     return 0;
1697   }
1698
1699   return 1;
1700 }
1701
1702 /* Synchronously receive a file. */
1703
1704 static int receive_file_data_sync (guestfs_h *g, void **buf);
1705
1706 int
1707 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1708 {
1709   void *buf;
1710   int fd, r;
1711
1712   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1713   if (fd == -1) {
1714     perrorf (g, "open: %s", filename);
1715     goto cancel;
1716   }
1717
1718   /* Receive the file in chunked encoding. */
1719   while ((r = receive_file_data_sync (g, &buf)) > 0) {
1720     if (xwrite (fd, buf, r) == -1) {
1721       perrorf (g, "%s: write", filename);
1722       free (buf);
1723       goto cancel;
1724     }
1725     free (buf);
1726   }
1727
1728   if (r == -1) {
1729     error (g, "%s: error in chunked encoding", filename);
1730     return -1;
1731   }
1732
1733   if (close (fd) == -1) {
1734     perrorf (g, "close: %s", filename);
1735     return -1;
1736   }
1737
1738   return 0;
1739
1740  cancel: ;
1741   /* Send cancellation message to daemon, then wait until it
1742    * cancels (just throwing away data).
1743    */
1744   XDR xdr;
1745   char fbuf[4];
1746   uint32_t flag = GUESTFS_CANCEL_FLAG;
1747
1748   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1749   xdr_uint32_t (&xdr, &flag);
1750   xdr_destroy (&xdr);
1751
1752   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1753     perrorf (g, "write to daemon socket");
1754     return -1;
1755   }
1756
1757   while ((r = receive_file_data_sync (g, &buf)) > 0)
1758     free (buf);                 /* just discard it */
1759
1760   return -1;
1761 }
1762
1763 struct receive_file_ctx {
1764   int code;
1765   void **buf;
1766 };
1767
1768 static void
1769 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1770 {
1771   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1772   struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1773   guestfs_chunk chunk;
1774
1775   ml->main_loop_quit (ml, g);
1776
1777   memset (&chunk, 0, sizeof chunk);
1778
1779   if (!xdr_guestfs_chunk (xdr, &chunk)) {
1780     error (g, "failed to parse file chunk");
1781     ctx->code = -1;
1782     return;
1783   }
1784   if (chunk.cancel) {
1785     error (g, "file receive cancelled by daemon");
1786     ctx->code = -2;
1787     return;
1788   }
1789   if (chunk.data.data_len == 0) { /* end of transfer */
1790     ctx->code = 0;
1791     return;
1792   }
1793
1794   ctx->code = chunk.data.data_len;
1795   *ctx->buf = chunk.data.data_val; /* caller frees */
1796 }
1797
1798 /* Receive a chunk of file data. */
1799 static int
1800 receive_file_data_sync (guestfs_h *g, void **buf)
1801 {
1802   struct receive_file_ctx ctx;
1803   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1804
1805   ctx.code = -3;
1806   ctx.buf = buf;
1807
1808   guestfs_set_reply_callback (g, receive_file_cb, &ctx);
1809   (void) ml->main_loop_run (ml, g);
1810   guestfs_set_reply_callback (g, NULL, NULL);
1811
1812   if (g->verbose)
1813     fprintf (stderr, "receive_file_data_sync: code %d\n", ctx.code);
1814
1815   switch (ctx.code) {
1816   case 0:                       /* end of file */
1817     return 0;
1818   case -1: case -2:
1819     return -1;
1820   case -3:
1821     error (g, "failed to call receive_file_cb");
1822     return -1;
1823   default:                      /* received n bytes of data */
1824     return ctx.code;
1825   }
1826 }
1827
1828 /* This is the default main loop implementation, using select(2). */
1829
1830 static int
1831 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1832                    guestfs_handle_event_cb cb, void *data)
1833 {
1834   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1835
1836   if (fd < 0 || fd >= FD_SETSIZE) {
1837     error (g, "fd %d is out of range", fd);
1838     return -1;
1839   }
1840
1841   if ((events & ~(GUESTFS_HANDLE_READABLE |
1842                   GUESTFS_HANDLE_WRITABLE |
1843                   GUESTFS_HANDLE_HANGUP |
1844                   GUESTFS_HANDLE_ERROR)) != 0) {
1845     error (g, "set of events (0x%x) contains unknown events", events);
1846     return -1;
1847   }
1848
1849   if (events == 0) {
1850     error (g, "set of events is empty");
1851     return -1;
1852   }
1853
1854   if (FD_ISSET (fd, &ml->rset) ||
1855       FD_ISSET (fd, &ml->wset) ||
1856       FD_ISSET (fd, &ml->xset)) {
1857     error (g, "fd %d is already registered", fd);
1858     return -1;
1859   }
1860
1861   if (cb == NULL) {
1862     error (g, "callback is NULL");
1863     return -1;
1864   }
1865
1866   if ((events & GUESTFS_HANDLE_READABLE))
1867     FD_SET (fd, &ml->rset);
1868   if ((events & GUESTFS_HANDLE_WRITABLE))
1869     FD_SET (fd, &ml->wset);
1870   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1871     FD_SET (fd, &ml->xset);
1872
1873   if (fd > ml->max_fd) {
1874     ml->max_fd = fd;
1875     ml->handle_cb_data =
1876       safe_realloc (g, ml->handle_cb_data,
1877                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1878   }
1879   ml->handle_cb_data[fd].cb = cb;
1880   ml->handle_cb_data[fd].g = g;
1881   ml->handle_cb_data[fd].data = data;
1882
1883   ml->nr_fds++;
1884
1885   /* Any integer >= 0 can be the handle, and this is as good as any ... */
1886   return fd;
1887 }
1888
1889 static int
1890 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1891 {
1892   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1893
1894   if (fd < 0 || fd >= FD_SETSIZE) {
1895     error (g, "fd %d is out of range", fd);
1896     return -1;
1897   }
1898
1899   if (!FD_ISSET (fd, &ml->rset) &&
1900       !FD_ISSET (fd, &ml->wset) &&
1901       !FD_ISSET (fd, &ml->xset)) {
1902     error (g, "fd %d was not registered", fd);
1903     return -1;
1904   }
1905
1906   FD_CLR (fd, &ml->rset);
1907   FD_CLR (fd, &ml->wset);
1908   FD_CLR (fd, &ml->xset);
1909
1910   if (fd == ml->max_fd) {
1911     ml->max_fd--;
1912     ml->handle_cb_data =
1913       safe_realloc (g, ml->handle_cb_data,
1914                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1915   }
1916
1917   ml->nr_fds--;
1918
1919   return 0;
1920 }
1921
1922 static int
1923 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1924                     guestfs_handle_timeout_cb cb, void *data)
1925 {
1926   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1927
1928   abort ();                     /* XXX not implemented yet */
1929 }
1930
1931 static int
1932 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1933 {
1934   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1935
1936   abort ();                     /* XXX not implemented yet */
1937 }
1938
1939 /* The 'g' parameter is just used for error reporting.  Events
1940  * for multiple handles can be dispatched by running the main
1941  * loop.
1942  */
1943 static int
1944 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1945 {
1946   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1947   int fd, r, events;
1948   fd_set rset2, wset2, xset2;
1949
1950   if (ml->is_running) {
1951     error (g, "select_main_loop_run: this cannot be called recursively");
1952     return -1;
1953   }
1954
1955   ml->is_running = 1;
1956
1957   while (ml->is_running) {
1958     if (ml->nr_fds == 0)
1959       break;
1960
1961     rset2 = ml->rset;
1962     wset2 = ml->wset;
1963     xset2 = ml->xset;
1964     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1965     if (r == -1) {
1966       perrorf (g, "select");
1967       ml->is_running = 0;
1968       return -1;
1969     }
1970
1971     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1972       events = 0;
1973       if (FD_ISSET (fd, &rset2))
1974         events |= GUESTFS_HANDLE_READABLE;
1975       if (FD_ISSET (fd, &wset2))
1976         events |= GUESTFS_HANDLE_WRITABLE;
1977       if (FD_ISSET (fd, &xset2))
1978         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1979       if (events) {
1980         r--;
1981         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1982                                    ml->handle_cb_data[fd].g,
1983                                    ml->handle_cb_data[fd].data,
1984                                    fd, fd, events);
1985       }
1986     }
1987   }
1988
1989   ml->is_running = 0;
1990   return 0;
1991 }
1992
1993 static int
1994 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1995 {
1996   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1997
1998   /* Note that legitimately ml->is_running can be zero when
1999    * this function is called.
2000    */
2001
2002   ml->is_running = 0;
2003   return 0;
2004 }