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