Begin to add the 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 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   if (guestfs__switch_to_receiving (g) == -1)
833     goto cleanup3;
834
835   g->state = LAUNCHING;
836   return 0;
837
838  cleanup3:
839   if (g->stdout_watch >= 0)
840     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
841   if (g->sock_watch >= 0)
842     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
843
844  cleanup2:
845   close (g->sock);
846
847  cleanup1:
848   close (wfd[1]);
849   close (rfd[0]);
850   kill (g->pid, 9);
851   waitpid (g->pid, NULL, 0);
852   g->fd[0] = -1;
853   g->fd[1] = -1;
854   g->sock = -1;
855   g->pid = 0;
856   g->start_t = 0;
857   g->stdout_watch = -1;
858   g->sock_watch = -1;
859
860  cleanup0:
861   free (kernel);
862   free (initrd);
863   return -1;
864 }
865
866 static void
867 finish_wait_ready (guestfs_h *g, void *vp)
868 {
869   if (g->verbose)
870     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
871
872   *((int *)vp) = 1;
873   g->main_loop->main_loop_quit (g->main_loop, g);
874 }
875
876 int
877 guestfs_wait_ready (guestfs_h *g)
878 {
879   int finished = 0, r;
880
881   if (g->state == READY) return 0;
882
883   if (g->state == BUSY) {
884     error (g, "qemu has finished launching already");
885     return -1;
886   }
887
888   if (g->state != LAUNCHING) {
889     error (g, "qemu has not been launched yet");
890     return -1;
891   }
892
893   g->launch_done_cb = finish_wait_ready;
894   g->launch_done_cb_data = &finished;
895   r = g->main_loop->main_loop_run (g->main_loop, g);
896   g->launch_done_cb = NULL;
897   g->launch_done_cb_data = NULL;
898
899   if (r == -1) return -1;
900
901   if (finished != 1) {
902     error (g, "guestfs_wait_ready failed, see earlier error messages");
903     return -1;
904   }
905
906   /* This is possible in some really strange situations, such as
907    * guestfsd starts up OK but then qemu immediately exits.  Check for
908    * it because the caller is probably expecting to be able to send
909    * commands after this function returns.
910    */
911   if (g->state != READY) {
912     error (g, "qemu launched and contacted daemon, but state != READY");
913     return -1;
914   }
915
916   return 0;
917 }
918
919 int
920 guestfs_kill_subprocess (guestfs_h *g)
921 {
922   if (g->state == CONFIG) {
923     error (g, "no subprocess to kill");
924     return -1;
925   }
926
927   if (g->verbose)
928     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
929
930   kill (g->pid, SIGTERM);
931
932   return 0;
933 }
934
935 /* Access current state. */
936 int
937 guestfs_is_config (guestfs_h *g)
938 {
939   return g->state == CONFIG;
940 }
941
942 int
943 guestfs_is_launching (guestfs_h *g)
944 {
945   return g->state == LAUNCHING;
946 }
947
948 int
949 guestfs_is_ready (guestfs_h *g)
950 {
951   return g->state == READY;
952 }
953
954 int
955 guestfs_is_busy (guestfs_h *g)
956 {
957   return g->state == BUSY;
958 }
959
960 int
961 guestfs_get_state (guestfs_h *g)
962 {
963   return g->state;
964 }
965
966 /* Structure-freeing functions.  These rely on the fact that the
967  * structure format is identical to the XDR format.  See note in
968  * generator.ml.
969  */
970 void
971 guestfs_free_int_bool (struct guestfs_int_bool *x)
972 {
973   free (x);
974 }
975
976 void
977 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
978 {
979   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
980   free (x);
981 }
982
983 void
984 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
985 {
986   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
987   free (x);
988 }
989
990 void
991 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
992 {
993   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
994   free (x);
995 }
996
997 /* This function is called whenever qemu prints something on stdout.
998  * Qemu's stdout is also connected to the guest's serial console, so
999  * we see kernel messages here too.
1000  */
1001 static void
1002 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1003               int watch, int fd, int events)
1004 {
1005   char buf[4096];
1006   int n;
1007
1008 #if 0
1009   if (g->verbose)
1010     fprintf (stderr,
1011              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1012              g, g->state, fd, events);
1013 #endif
1014
1015   if (g->fd[1] != fd) {
1016     error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1017     return;
1018   }
1019
1020   n = read (fd, buf, sizeof buf);
1021   if (n == 0) {
1022     /* Hopefully this indicates the qemu child process has died. */
1023     if (g->verbose)
1024       fprintf (stderr, "stdout_event: %p: child process died\n", g);
1025     /*kill (g->pid, SIGTERM);*/
1026     waitpid (g->pid, NULL, 0);
1027     if (g->stdout_watch >= 0)
1028       g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1029     if (g->sock_watch >= 0)
1030       g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1031     close (g->fd[0]);
1032     close (g->fd[1]);
1033     close (g->sock);
1034     g->fd[0] = -1;
1035     g->fd[1] = -1;
1036     g->sock = -1;
1037     g->pid = 0;
1038     g->start_t = 0;
1039     g->stdout_watch = -1;
1040     g->sock_watch = -1;
1041     g->state = CONFIG;
1042     if (g->subprocess_quit_cb)
1043       g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1044     return;
1045   }
1046
1047   if (n == -1) {
1048     if (errno != EAGAIN)
1049       perrorf (g, "read");
1050     return;
1051   }
1052
1053   /* In verbose mode, copy all log messages to stderr. */
1054   if (g->verbose)
1055     write (2, buf, n);
1056
1057   /* It's an actual log message, send it upwards if anyone is listening. */
1058   if (g->log_message_cb)
1059     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1060 }
1061
1062 /* The function is called whenever we can read something on the
1063  * guestfsd (daemon inside the guest) communication socket.
1064  */
1065 static void
1066 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1067                  int watch, int fd, int events)
1068 {
1069   XDR xdr;
1070   unsigned len;
1071   int n;
1072
1073   if (g->verbose)
1074     fprintf (stderr,
1075              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1076              g, g->state, fd, events);
1077
1078   if (g->sock != fd) {
1079     error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1080     return;
1081   }
1082
1083   if (g->msg_in_size <= g->msg_in_allocated) {
1084     g->msg_in_allocated += 4096;
1085     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1086   }
1087   n = read (g->sock, g->msg_in + g->msg_in_size,
1088             g->msg_in_allocated - g->msg_in_size);
1089   if (n == 0)
1090     /* Disconnected?  Ignore it because stdout_watch will get called
1091      * and will do the cleanup.
1092      */
1093     return;
1094
1095   if (n == -1) {
1096     if (errno != EAGAIN)
1097       perrorf (g, "read");
1098     return;
1099   }
1100
1101   g->msg_in_size += n;
1102
1103   /* Have we got enough of a message to be able to process it yet? */
1104   if (g->msg_in_size < 4) return;
1105
1106   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1107   if (!xdr_uint32_t (&xdr, &len)) {
1108     error (g, "can't decode length word");
1109     goto cleanup;
1110   }
1111
1112   /* Length is normally the length of the message, but when guestfsd
1113    * starts up it sends a "magic" value (longer than any possible
1114    * message).  Check for this.
1115    */
1116   if (len == 0xf5f55ff5) {
1117     if (g->state != LAUNCHING)
1118       error (g, "received magic signature from guestfsd, but in state %d",
1119              g->state);
1120     else if (g->msg_in_size != 4)
1121       error (g, "received magic signature from guestfsd, but msg size is %d",
1122              g->msg_in_size);
1123     else {
1124       g->state = READY;
1125       if (g->launch_done_cb)
1126         g->launch_done_cb (g, g->launch_done_cb_data);
1127     }
1128
1129     goto cleanup;
1130   }
1131
1132   /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1133   if (len > GUESTFS_MESSAGE_MAX) {
1134     error (g, "message length (%u) > maximum possible size (%d)",
1135            len, GUESTFS_MESSAGE_MAX);
1136     goto cleanup;
1137   }
1138
1139   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1140
1141   /* This should not happen, and if it does it probably means we've
1142    * lost all hope of synchronization.
1143    */
1144   if (g->msg_in_size-4 > len) {
1145     error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1146     goto cleanup;
1147   }
1148
1149   /* Got the full message, begin processing it. */
1150   if (g->verbose) {
1151     int i, j;
1152
1153     for (i = 0; i < g->msg_in_size; i += 16) {
1154       printf ("%04x: ", i);
1155       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1156         printf ("%02x ", (unsigned char) g->msg_in[j]);
1157       for (; j < i+16; ++j)
1158         printf ("   ");
1159       printf ("|");
1160       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1161         if (isprint (g->msg_in[j]))
1162           printf ("%c", g->msg_in[j]);
1163         else
1164           printf (".");
1165       for (; j < i+16; ++j)
1166         printf (" ");
1167       printf ("|\n");
1168     }
1169   }
1170
1171   /* Not in the expected state. */
1172   if (g->state != BUSY)
1173     error (g, "state %d != BUSY", g->state);
1174
1175   /* Push the message up to the higher layer. */
1176   g->state = READY;
1177   if (g->reply_cb)
1178     g->reply_cb (g, g->reply_cb_data, &xdr);
1179
1180  cleanup:
1181   /* Free the message buffer if it's grown excessively large. */
1182   if (g->msg_in_allocated > 65536) {
1183     free (g->msg_in);
1184     g->msg_in = NULL;
1185     g->msg_in_size = g->msg_in_allocated = 0;
1186   } else
1187     g->msg_in_size = 0;
1188
1189   xdr_destroy (&xdr);
1190 }
1191
1192 /* The function is called whenever we can write something on the
1193  * guestfsd (daemon inside the guest) communication socket.
1194  */
1195 static void
1196 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1197                   int watch, int fd, int events)
1198 {
1199   int n;
1200
1201   if (g->verbose)
1202     fprintf (stderr,
1203              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1204              g, g->state, fd, events);
1205
1206   if (g->sock != fd) {
1207     error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1208     return;
1209   }
1210
1211   if (g->state != BUSY) {
1212     error (g, "sock_write_event: state %d != BUSY", g->state);
1213     return;
1214   }
1215
1216   if (g->verbose)
1217     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1218              g->msg_out_size - g->msg_out_pos);
1219
1220   n = write (g->sock, g->msg_out + g->msg_out_pos,
1221              g->msg_out_size - g->msg_out_pos);
1222   if (n == -1) {
1223     if (errno != EAGAIN)
1224       perrorf (g, "write");
1225     return;
1226   }
1227
1228   if (g->verbose)
1229     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1230
1231   g->msg_out_pos += n;
1232
1233   /* More to write? */
1234   if (g->msg_out_pos < g->msg_out_size)
1235     return;
1236
1237   if (g->verbose)
1238     fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1239
1240   free (g->msg_out);
1241   g->msg_out = NULL;
1242   g->msg_out_pos = g->msg_out_size = 0;
1243
1244   /* Done writing, call the higher layer. */
1245   if (g->send_cb)
1246     g->send_cb (g, g->send_cb_data);
1247 }
1248
1249 void
1250 guestfs_set_send_callback (guestfs_h *g,
1251                            guestfs_send_cb cb, void *opaque)
1252 {
1253   g->send_cb = cb;
1254   g->send_cb_data = opaque;
1255 }
1256
1257 void
1258 guestfs_set_reply_callback (guestfs_h *g,
1259                             guestfs_reply_cb cb, void *opaque)
1260 {
1261   g->reply_cb = cb;
1262   g->reply_cb_data = opaque;
1263 }
1264
1265 void
1266 guestfs_set_log_message_callback (guestfs_h *g,
1267                                   guestfs_log_message_cb cb, void *opaque)
1268 {
1269   g->log_message_cb = cb;
1270   g->log_message_cb_data = opaque;
1271 }
1272
1273 void
1274 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1275                                       guestfs_subprocess_quit_cb cb, void *opaque)
1276 {
1277   g->subprocess_quit_cb = cb;
1278   g->subprocess_quit_cb_data = opaque;
1279 }
1280
1281 void
1282 guestfs_set_launch_done_callback (guestfs_h *g,
1283                                   guestfs_launch_done_cb cb, void *opaque)
1284 {
1285   g->launch_done_cb = cb;
1286   g->launch_done_cb_data = opaque;
1287 }
1288
1289 /* Access to the handle's main loop and the default main loop. */
1290 void
1291 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1292 {
1293   g->main_loop = main_loop;
1294 }
1295
1296 guestfs_main_loop *
1297 guestfs_get_main_loop (guestfs_h *g)
1298 {
1299   return g->main_loop;
1300 }
1301
1302 guestfs_main_loop *
1303 guestfs_get_default_main_loop (void)
1304 {
1305   return (guestfs_main_loop *) &default_main_loop;
1306 }
1307
1308 /* Dispatch a call (len + header + args) to the remote daemon.  This
1309  * function just queues the call in msg_out, to be sent when we next
1310  * enter the main loop.  Returns -1 for error, or the message serial
1311  * number.
1312  */
1313 int
1314 guestfs__send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1315 {
1316   char buffer[GUESTFS_MESSAGE_MAX];
1317   struct guestfs_message_header hdr;
1318   XDR xdr;
1319   unsigned len;
1320   int serial = g->msg_next_serial++;
1321
1322   if (g->state != READY) {
1323     error (g, "dispatch: state %d != READY", g->state);
1324     return -1;
1325   }
1326
1327   /* Serialize the header. */
1328   hdr.prog = GUESTFS_PROGRAM;
1329   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1330   hdr.proc = proc_nr;
1331   hdr.direction = GUESTFS_DIRECTION_CALL;
1332   hdr.serial = serial;
1333   hdr.status = GUESTFS_STATUS_OK;
1334
1335   xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1336   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1337     error (g, "xdr_guestfs_message_header failed");
1338     return -1;
1339   }
1340
1341   /* Serialize the args.  If any, because some message types
1342    * have no parameters.
1343    */
1344   if (xdrp) {
1345     if (!(*xdrp) (&xdr, args)) {
1346       error (g, "dispatch failed to marshal args");
1347       return -1;
1348     }
1349   }
1350
1351   len = xdr_getpos (&xdr);
1352   xdr_destroy (&xdr);
1353
1354   /* Allocate the outgoing message buffer. */
1355   g->msg_out = safe_malloc (g, len + 4);
1356
1357   g->msg_out_size = len + 4;
1358   g->msg_out_pos = 0;
1359   g->state = BUSY;
1360
1361   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1362   if (!xdr_uint32_t (&xdr, &len)) {
1363     error (g, "xdr_uint32_t failed in dispatch");
1364     goto cleanup1;
1365   }
1366
1367   memcpy (g->msg_out + 4, buffer, len);
1368
1369   if (guestfs__switch_to_sending (g) == -1)
1370     goto cleanup1;
1371
1372   return serial;
1373
1374  cleanup1:
1375   free (g->msg_out);
1376   g->msg_out = NULL;
1377   g->msg_out_size = 0;
1378   g->state = READY;
1379   return -1;
1380 }
1381
1382 /* Change the daemon socket handler so that we are now writing.
1383  * This sets the handle to sock_write_event.
1384  */
1385 int
1386 guestfs__switch_to_sending (guestfs_h *g)
1387 {
1388   if (g->sock_watch >= 0) {
1389     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1390       error (g, "remove_handle failed");
1391       g->sock_watch = -1;
1392       return -1;
1393     }
1394   }
1395
1396   g->sock_watch =
1397     g->main_loop->add_handle (g->main_loop, g, g->sock,
1398                               GUESTFS_HANDLE_WRITABLE,
1399                               sock_write_event, NULL);
1400   if (g->sock_watch == -1) {
1401     error (g, "add_handle failed");
1402     return -1;
1403   }
1404
1405   return 0;
1406 }
1407
1408 int
1409 guestfs__switch_to_receiving (guestfs_h *g)
1410 {
1411   if (g->sock_watch >= 0) {
1412     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1413       error (g, "remove_handle failed");
1414       g->sock_watch = -1;
1415       return -1;
1416     }
1417   }
1418
1419   g->sock_watch =
1420     g->main_loop->add_handle (g->main_loop, g, g->sock,
1421                               GUESTFS_HANDLE_READABLE,
1422                               sock_read_event, NULL);
1423   if (g->sock_watch == -1) {
1424     error (g, "add_handle failed");
1425     return -1;
1426   }
1427
1428   return 0;
1429 }
1430
1431 int
1432 guestfs__send_file_sync (guestfs_main_loop *ml, guestfs_h *g,
1433                          const char *filename)
1434 {
1435   return -1;
1436 }
1437
1438 int
1439 guestfs__receive_file_sync (guestfs_main_loop *ml, guestfs_h *g,
1440                             const char *filename)
1441 {
1442   return -1;
1443 }
1444
1445 #if 0
1446 static int cancel = 0; /* XXX Implement file cancellation. */
1447
1448 int
1449 guestfs__send_file (guestfs_h *g, const char *filename)
1450 {
1451   char buf[GUESTFS_MAX_CHUNK_SIZE];
1452   int fd, r;
1453
1454   fd = open (filename, O_RDONLY);
1455   if (fd == -1) {
1456     perrorf (g, "open: %s", filename);
1457     send_file_cancellation (g);
1458     /* Daemon sees cancellation and won't reply, so caller can
1459      * just return here.
1460      */
1461     return -1;
1462   }
1463
1464   /* Send file in chunked encoding. */
1465   while (!cancel && (r = read (fd, buf, sizeof buf)) > 0) {
1466     if (send_file_data (g, buf, r) == -1)
1467       return -1;
1468   }
1469
1470   if (cancel) {
1471     send_file_cancellation (g);
1472     return -1;
1473   }
1474
1475   if (r == -1) {
1476     perrorf (g, "read: %s", filename);
1477     send_file_cancellation (g);
1478     return -1;
1479   }
1480
1481   /* End of file, but before we send that, we need to close
1482    * the file and check for errors.
1483    */
1484   if (close (fd) == -1) {
1485     perrorf (g, "close: %s", filename);
1486     send_file_cancellation (g);
1487     return -1;
1488   }
1489
1490   return send_file_complete (g);
1491 }
1492
1493 /* Send a chunk, cancellation or end of file, wait for it to go. */
1494 static int
1495 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len)
1496 {
1497   void *data;
1498   guestfs_chunk chunk;
1499   XDR xdr;
1500
1501   if (g->state != BUSY) {
1502     error (g, "send_file_chunk: state %d != READY", g->state);
1503     return -1;
1504   }
1505
1506   /* Serialize the chunk. */
1507   chunk.cancel = cancel;
1508   chunk.data.data_len = len;
1509   chunk.data.data_val = (char *) buf;
1510
1511   data = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 48);
1512   xdrmem_create (&xdr, data, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1513   if (xdr_guestfs_chunk (&xdr, &chunk)) {
1514     error (g, "xdr_guestfs_chunk failed");
1515     free (data);
1516     return -1;
1517   }
1518
1519   chunkdatalen = xdr_getpos (&xdr);
1520   xdr_destroy (&xdr);
1521
1522   len = xdr_getpos (&xdr);
1523   xdr_destroy (&xdr);
1524
1525   data = safe_realloc (g, data, len);
1526   g->msg_out = data;
1527   g->msg_out_size = len;
1528   g->msg_out_pos = 0;
1529
1530   if (guestfs__switch_to_sending (g) == -1)
1531     goto cleanup1;
1532
1533   return 0;
1534
1535  cleanup1:
1536   free (g->msg_out);
1537   g->msg_out = NULL;
1538   g->msg_out_size = 0;
1539   g->state = READY;
1540   return -1;
1541 }
1542
1543 /* Send a chunk of file data. */
1544 static int
1545 send_file_data (guestfs_h *g, const char *buf, size_t len)
1546 {
1547   return send_file_chunk (g, 0, buf, len);
1548 }
1549
1550 /* Send a cancellation message. */
1551 static int
1552 send_file_cancellation (guestfs_h *g)
1553 {
1554   char buf[1];
1555   return send_file_chunk (g, 1, buf, 0);
1556 }
1557
1558 /* Send a file complete chunk. */
1559 static int
1560 send_file_complete (guestfs_h *g)
1561 {
1562   char buf[0];
1563   return send_file_chunk (g, 0, buf, 0);
1564 }
1565 #endif
1566
1567 /* This is the default main loop implementation, using select(2). */
1568
1569 static int
1570 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
1571                    guestfs_handle_event_cb cb, void *data)
1572 {
1573   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1574
1575   if (fd < 0 || fd >= FD_SETSIZE) {
1576     error (g, "fd %d is out of range", fd);
1577     return -1;
1578   }
1579
1580   if ((events & ~(GUESTFS_HANDLE_READABLE |
1581                   GUESTFS_HANDLE_WRITABLE |
1582                   GUESTFS_HANDLE_HANGUP |
1583                   GUESTFS_HANDLE_ERROR)) != 0) {
1584     error (g, "set of events (0x%x) contains unknown events", events);
1585     return -1;
1586   }
1587
1588   if (events == 0) {
1589     error (g, "set of events is empty");
1590     return -1;
1591   }
1592
1593   if (FD_ISSET (fd, &ml->rset) ||
1594       FD_ISSET (fd, &ml->wset) ||
1595       FD_ISSET (fd, &ml->xset)) {
1596     error (g, "fd %d is already registered", fd);
1597     return -1;
1598   }
1599
1600   if (cb == NULL) {
1601     error (g, "callback is NULL");
1602     return -1;
1603   }
1604
1605   if ((events & GUESTFS_HANDLE_READABLE))
1606     FD_SET (fd, &ml->rset);
1607   if ((events & GUESTFS_HANDLE_WRITABLE))
1608     FD_SET (fd, &ml->wset);
1609   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1610     FD_SET (fd, &ml->xset);
1611
1612   if (fd > ml->max_fd) {
1613     ml->max_fd = fd;
1614     ml->handle_cb_data =
1615       safe_realloc (g, ml->handle_cb_data,
1616                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1617   }
1618   ml->handle_cb_data[fd].cb = cb;
1619   ml->handle_cb_data[fd].g = g;
1620   ml->handle_cb_data[fd].data = data;
1621
1622   ml->nr_fds++;
1623
1624   /* Any integer >= 0 can be the handle, and this is as good as any ... */
1625   return fd;
1626 }
1627
1628 static int
1629 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
1630 {
1631   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1632
1633   if (fd < 0 || fd >= FD_SETSIZE) {
1634     error (g, "fd %d is out of range", fd);
1635     return -1;
1636   }
1637
1638   if (!FD_ISSET (fd, &ml->rset) &&
1639       !FD_ISSET (fd, &ml->wset) &&
1640       !FD_ISSET (fd, &ml->xset)) {
1641     error (g, "fd %d was not registered", fd);
1642     return -1;
1643   }
1644
1645   FD_CLR (fd, &ml->rset);
1646   FD_CLR (fd, &ml->wset);
1647   FD_CLR (fd, &ml->xset);
1648
1649   if (fd == ml->max_fd) {
1650     ml->max_fd--;
1651     ml->handle_cb_data =
1652       safe_realloc (g, ml->handle_cb_data,
1653                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
1654   }
1655
1656   ml->nr_fds--;
1657
1658   return 0;
1659 }
1660
1661 static int
1662 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
1663                     guestfs_handle_timeout_cb cb, void *data)
1664 {
1665   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1666
1667   abort ();                     /* XXX not implemented yet */
1668 }
1669
1670 static int
1671 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
1672 {
1673   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
1674
1675   abort ();                     /* XXX not implemented yet */
1676 }
1677
1678 /* The 'g' parameter is just used for error reporting.  Events
1679  * for multiple handles can be dispatched by running the main
1680  * loop.
1681  */
1682 static int
1683 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
1684 {
1685   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1686   int fd, r, events;
1687   fd_set rset2, wset2, xset2;
1688
1689   if (ml->is_running) {
1690     error (g, "select_main_loop_run: this cannot be called recursively");
1691     return -1;
1692   }
1693
1694   ml->is_running = 1;
1695
1696   while (ml->is_running) {
1697     if (ml->nr_fds == 0)
1698       break;
1699
1700     rset2 = ml->rset;
1701     wset2 = ml->wset;
1702     xset2 = ml->xset;
1703     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
1704     if (r == -1) {
1705       perrorf (g, "select");
1706       ml->is_running = 0;
1707       return -1;
1708     }
1709
1710     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
1711       events = 0;
1712       if (FD_ISSET (fd, &rset2))
1713         events |= GUESTFS_HANDLE_READABLE;
1714       if (FD_ISSET (fd, &wset2))
1715         events |= GUESTFS_HANDLE_WRITABLE;
1716       if (FD_ISSET (fd, &xset2))
1717         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1718       if (events) {
1719         r--;
1720         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
1721                                    ml->handle_cb_data[fd].g,
1722                                    ml->handle_cb_data[fd].data,
1723                                    fd, fd, events);
1724       }
1725     }
1726   }
1727
1728   ml->is_running = 0;
1729   return 0;
1730 }
1731
1732 static int
1733 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
1734 {
1735   struct select_main_loop *ml = (struct select_main_loop *) mlv;
1736
1737   if (!ml->is_running) {
1738     error (g, "cannot quit, we are not running in a main loop");
1739     return -1;
1740   }
1741
1742   ml->is_running = 0;
1743   return 0;
1744 }