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