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