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