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