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