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