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