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