2 * Copyright (C) 2009 Red Hat Inc.
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.
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.
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
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22 #define _GNU_SOURCE /* for vasprintf, GNU strerror_r */
37 #ifdef HAVE_SYS_TYPES_H
38 #include <sys/types.h>
41 #ifdef HAVE_SYS_WAIT_H
45 #ifdef HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
53 #include <sys/select.h>
57 static void error (guestfs_h *g, const char *fs, ...);
58 static void perrorf (guestfs_h *g, const char *fs, ...);
59 static void *safe_malloc (guestfs_h *g, int nbytes);
60 static void *safe_realloc (guestfs_h *g, void *ptr, int nbytes);
61 static char *safe_strdup (guestfs_h *g, const char *str);
63 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
64 static void stdout_event (void *data, int watch, int fd, int events);
65 static void sock_read_event (void *data, int watch, int fd, int events);
66 //static void sock_write_event (void *data, int watch, int fd, int events);
68 static int select_add_handle (guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
69 static int select_remove_handle (guestfs_h *g, int watch);
70 static int select_add_timeout (guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
71 static int select_remove_timeout (guestfs_h *g, int timer);
72 static void select_main_loop_run (guestfs_h *g);
73 static void select_main_loop_quit (guestfs_h *g);
75 #define UNIX_PATH_MAX 108
77 #define VMCHANNEL_PORT 6666
78 #define VMCHANNEL_ADDR "10.0.2.4"
80 /* Current main loop. */
81 static guestfs_main_loop main_loop = {
82 .add_handle = select_add_handle,
83 .remove_handle = select_remove_handle,
84 .add_timeout = select_add_timeout,
85 .remove_timeout = select_remove_timeout,
86 .main_loop_run = select_main_loop_run,
87 .main_loop_quit = select_main_loop_quit,
90 /* GuestFS handle and connection. */
91 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
95 /* State: see the state machine diagram in the man page guestfs(3). */
98 int fd[2]; /* Stdin/stdout of qemu. */
99 int sock; /* Daemon communications socket. */
100 int pid; /* Qemu PID. */
101 time_t start_t; /* The time when we started qemu. */
103 int stdout_watch; /* Watches qemu stdout for log messages. */
104 int sock_watch; /* Watches daemon comm socket. */
106 char *tmpdir; /* Temporary directory containing socket. */
108 char **cmdline; /* Qemu command line. */
114 guestfs_abort_cb abort_cb;
115 guestfs_error_handler_cb error_cb;
116 void * error_cb_data;
117 guestfs_reply_cb reply_cb;
118 void * reply_cb_data;
119 guestfs_log_message_cb log_message_cb;
120 void * log_message_cb_data;
121 guestfs_subprocess_quit_cb subprocess_quit_cb;
122 void * subprocess_quit_cb_data;
123 guestfs_launch_done_cb launch_done_cb;
124 void * launch_done_cb_data;
126 /* These callbacks are called before reply_cb and launch_done_cb,
127 * and are used to implement the high-level API without needing to
128 * interfere with callbacks that the user might have set.
130 guestfs_reply_cb reply_cb_internal;
131 void * reply_cb_internal_data;
132 guestfs_launch_done_cb launch_done_cb_internal;
133 void * launch_done_cb_internal_data;
137 guestfs_create (void)
142 g = malloc (sizeof (*g));
145 memset (g, 0, sizeof (*g));
152 g->stdout_watch = -1;
156 g->error_cb = default_error_cb;
157 g->error_cb_data = NULL;
159 str = getenv ("LIBGUESTFS_DEBUG");
160 g->verbose = str != NULL && strcmp (str, "1") == 0;
166 guestfs_close (guestfs_h *g)
171 if (g->state == NO_HANDLE) {
172 /* Not safe to call 'error' here, so ... */
173 fprintf (stderr, "guestfs_close: called twice on the same handle\n");
177 /* Remove any handlers that might be called back before we kill the
180 g->log_message_cb = NULL;
182 if (g->state != CONFIG)
183 guestfs_kill_subprocess (g);
186 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
195 for (i = 0; i < g->cmdline_size; ++i)
196 free (g->cmdline[i]);
200 /* Mark the handle as dead before freeing it. */
201 g->state = NO_HANDLE;
207 default_error_cb (guestfs_h *g, void *data, const char *msg)
209 fprintf (stderr, "libguestfs: %s\n", msg);
213 error (guestfs_h *g, const char *fs, ...)
218 if (!g->error_cb) return;
221 vasprintf (&msg, fs, args);
224 g->error_cb (g, g->error_cb_data, msg);
230 perrorf (guestfs_h *g, const char *fs, ...)
236 if (!g->error_cb) return;
239 vasprintf (&msg, fs, args);
244 strerror_r (err, buf, sizeof buf);
248 buf = strerror_r (err, _buf, sizeof _buf);
251 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
255 g->error_cb (g, g->error_cb_data, msg);
261 safe_malloc (guestfs_h *g, int nbytes)
263 void *ptr = malloc (nbytes);
264 if (!ptr) g->abort_cb ();
269 safe_realloc (guestfs_h *g, void *ptr, int nbytes)
271 void *p = realloc (ptr, nbytes);
272 if (!p) g->abort_cb ();
277 safe_strdup (guestfs_h *g, const char *str)
279 char *s = strdup (str);
280 if (!s) g->abort_cb ();
285 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
291 guestfs_get_out_of_memory_handler (guestfs_h *g)
297 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
300 g->error_cb_data = data;
303 guestfs_error_handler_cb
304 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
306 if (data_rtn) *data_rtn = g->error_cb_data;
311 guestfs_set_verbose (guestfs_h *g, int v)
317 guestfs_get_verbose (guestfs_h *g)
322 /* Add a string to the current command line. */
324 incr_cmdline_size (guestfs_h *g)
326 if (g->cmdline == NULL) {
327 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
329 g->cmdline = safe_malloc (g, sizeof (char *));
330 g->cmdline[0] = NULL;
334 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
338 add_cmdline (guestfs_h *g, const char *str)
340 if (g->state != CONFIG) {
341 error (g, "command line cannot be altered after qemu subprocess launched");
345 incr_cmdline_size (g);
346 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
351 guestfs_config (guestfs_h *g,
352 const char *qemu_param, const char *qemu_value)
354 if (qemu_param[0] != '-') {
355 error (g, "guestfs_config: parameter must begin with '-' character");
359 /* A bit fascist, but the user will probably break the extra
360 * parameters that we add if they try to set any of these.
362 if (strcmp (qemu_param, "-kernel") == 0 ||
363 strcmp (qemu_param, "-initrd") == 0 ||
364 strcmp (qemu_param, "-nographic") == 0 ||
365 strcmp (qemu_param, "-serial") == 0 ||
366 strcmp (qemu_param, "-vnc") == 0 ||
367 strcmp (qemu_param, "-full-screen") == 0 ||
368 strcmp (qemu_param, "-std-vga") == 0 ||
369 strcmp (qemu_param, "-vnc") == 0) {
370 error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
374 if (add_cmdline (g, qemu_param) != 0) return -1;
376 if (qemu_value != NULL) {
377 if (add_cmdline (g, qemu_value) != 0) return -1;
384 guestfs_add_drive (guestfs_h *g, const char *filename)
386 int len = strlen (filename) + 64;
389 if (strchr (filename, ',') != NULL) {
390 error (g, "filename cannot contain ',' (comma) character");
394 snprintf (buf, len, "file=%s", filename);
396 return guestfs_config (g, "-drive", buf);
400 guestfs_add_cdrom (guestfs_h *g, const char *filename)
402 if (strchr (filename, ',') != NULL) {
403 error (g, "filename cannot contain ',' (comma) character");
407 return guestfs_config (g, "-cdrom", filename);
411 guestfs_launch (guestfs_h *g)
413 static const char *dir_template = "/tmp/libguestfsXXXXXX";
417 /*const char *qemu = QEMU;*/ /* XXX */
418 const char *qemu = "/usr/bin/qemu-system-x86_64";
419 const char *kernel = "vmlinuz.fedora-10.x86_64";
420 const char *initrd = "initramfs.fedora-10.x86_64.img";
422 struct sockaddr_un addr;
424 /* XXX Choose which qemu to run. */
425 /* XXX Choose initrd, etc. */
429 error (g, "you must call guestfs_add_drive before guestfs_launch");
433 if (g->state != CONFIG) {
434 error (g, "qemu has already been launched");
438 /* Make the temporary directory containing the socket. */
440 g->tmpdir = safe_strdup (g, dir_template);
441 if (mkdtemp (g->tmpdir) == NULL) {
442 perrorf (g, "%s: cannot create temporary directory", dir_template);
447 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
449 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
464 if (r == 0) { /* Child (qemu). */
468 /* Set up the full command line. Do this in the subprocess so we
469 * don't need to worry about cleaning up.
471 g->cmdline[0] = (char *) qemu;
473 /* Construct the -net channel parameter for qemu. */
474 snprintf (vmchannel, sizeof vmchannel,
475 "channel,%d:unix:%s,server,nowait",
476 VMCHANNEL_PORT, unixsock);
478 /* Linux kernel command line. */
479 snprintf (append, sizeof append,
480 "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
482 add_cmdline (g, "-m");
483 add_cmdline (g, "384"); /* XXX Choose best size. */
484 add_cmdline (g, "-kernel");
485 add_cmdline (g, (char *) kernel);
486 add_cmdline (g, "-initrd");
487 add_cmdline (g, (char *) initrd);
488 add_cmdline (g, "-append");
489 add_cmdline (g, append);
490 add_cmdline (g, "-nographic");
491 add_cmdline (g, "-serial");
492 add_cmdline (g, "stdio");
493 add_cmdline (g, "-net");
494 add_cmdline (g, vmchannel);
495 add_cmdline (g, "-net");
496 add_cmdline (g, "user,vlan=0");
497 add_cmdline (g, "-net");
498 add_cmdline (g, "nic,vlan=0");
499 incr_cmdline_size (g);
500 g->cmdline[g->cmdline_size-1] = NULL;
503 fprintf (stderr, "%s", qemu);
504 for (i = 0; g->cmdline[i]; ++i)
505 fprintf (stderr, " %s", g->cmdline[i]);
506 fprintf (stderr, "\n");
509 /* Set up stdin, stdout. */
518 /* Set up a new process group, so we can signal this process
519 * and all subprocesses (eg. if qemu is really a shell script).
524 execv (qemu, g->cmdline); /* Run qemu. */
529 /* Parent (library). */
532 /* Start the clock ... */
535 /* Close the other ends of the pipe. */
539 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
540 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
541 perrorf (g, "fcntl");
545 g->fd[0] = wfd[1]; /* stdin of child */
546 g->fd[1] = rfd[0]; /* stdout of child */
548 /* Open the Unix socket. The vmchannel implementation that got
549 * merged with qemu sucks in a number of ways. Both ends do
550 * connect(2), which means that no one knows what, if anything, is
551 * connected to the other end, or if it becomes disconnected. Even
552 * worse, we have to wait some indeterminate time for qemu to create
553 * the socket and connect to it (which happens very early in qemu's
554 * start-up), so any code that uses vmchannel is inherently racy.
555 * Hence this silly loop.
557 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
559 perrorf (g, "socket");
563 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
564 perrorf (g, "fcntl");
568 addr.sun_family = AF_UNIX;
569 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
570 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
574 /* Always sleep at least once to give qemu a small chance to start up. */
577 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
578 if ((r == -1 && errno == EINPROGRESS) || r == 0)
581 perrorf (g, "connect");
585 error (g, "failed to connect to vmchannel socket");
589 /* Watch the file descriptors. */
591 main_loop.add_handle (g, g->fd[1],
592 GUESTFS_HANDLE_READABLE,
594 if (g->stdout_watch == -1) {
595 error (g, "could not watch qemu stdout");
600 main_loop.add_handle (g, g->sock,
601 GUESTFS_HANDLE_READABLE |
602 GUESTFS_HANDLE_HANGUP |
603 GUESTFS_HANDLE_ERROR,
605 if (g->sock_watch == -1) {
606 error (g, "could not watch daemon communications socket");
610 g->state = LAUNCHING;
614 if (g->stdout_watch >= 0)
615 main_loop.remove_handle (g, g->stdout_watch);
616 if (g->sock_watch >= 0)
617 main_loop.remove_handle (g, g->sock_watch);
626 waitpid (g->pid, NULL, 0);
632 g->stdout_watch = -1;
638 finish_wait_ready (guestfs_h *g, void *vp)
641 main_loop.main_loop_quit (g);
645 guestfs_wait_ready (guestfs_h *g)
649 if (g->state == READY) return 0;
651 if (g->state == BUSY) {
652 error (g, "qemu has finished launching already");
656 if (g->state != LAUNCHING) {
657 error (g, "qemu has not been launched yet");
661 g->launch_done_cb_internal = finish_wait_ready;
662 g->launch_done_cb_internal_data = &r;
663 main_loop.main_loop_run (g);
664 g->launch_done_cb_internal = NULL;
665 g->launch_done_cb_internal_data = NULL;
668 error (g, "guestfs_wait_ready failed, see earlier error messages");
672 /* This is possible in some really strange situations, such as
673 * guestfsd starts up OK but then qemu immediately exits. Check for
674 * it because the caller is probably expecting to be able to send
675 * commands after this function returns.
677 if (g->state != READY) {
678 error (g, "qemu launched and contacted daemon, but state != READY");
686 guestfs_kill_subprocess (guestfs_h *g)
688 if (g->state == CONFIG) {
689 error (g, "no subprocess to kill");
694 fprintf (stderr, "sending SIGTERM to process group %d\n", g->pid);
696 kill (g->pid, SIGTERM);
701 /* This function is called whenever qemu prints something on stdout.
702 * Qemu's stdout is also connected to the guest's serial console, so
703 * we see kernel messages here too.
706 stdout_event (void *data, int watch, int fd, int events)
708 guestfs_h *g = (guestfs_h *) data;
715 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
716 g, g->state, fd, events);
719 if (g->fd[1] != fd) {
720 error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
724 n = read (fd, buf, sizeof buf);
726 /* Hopefully this indicates the qemu child process has died. */
728 fprintf (stderr, "stdout_event: %p: child process died\n", g);
729 /*kill (g->pid, SIGTERM);*/
730 waitpid (g->pid, NULL, 0);
731 if (g->stdout_watch >= 0)
732 main_loop.remove_handle (g, g->stdout_watch);
733 if (g->sock_watch >= 0)
734 main_loop.remove_handle (g, g->sock_watch);
743 g->stdout_watch = -1;
746 if (g->subprocess_quit_cb)
747 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
757 /* In verbose mode, copy all log messages to stderr. */
761 /* It's an actual log message, send it upwards if anyone is listening. */
762 if (g->log_message_cb)
763 g->log_message_cb (g, g->log_message_cb_data, buf, n);
766 /* The function is called whenever we can read something on the
767 * guestfsd (daemon inside the guest) communication socket.
770 sock_read_event (void *data, int watch, int fd, int events)
772 /*guestfs_h *g = (guestfs_h *) data;*/
782 /* This is the default main loop implementation, using select(2). */
784 struct handle_cb_data {
785 guestfs_handle_event_cb cb;
792 static int select_init_done = 0;
793 static int max_fd = -1;
794 static struct handle_cb_data *handle_cb_data = NULL;
799 if (!select_init_done) {
804 select_init_done = 1;
809 select_add_handle (guestfs_h *g, int fd, int events,
810 guestfs_handle_event_cb cb, void *data)
814 if (fd < 0 || fd >= FD_SETSIZE) {
815 error (g, "fd %d is out of range", fd);
819 if ((events & ~(GUESTFS_HANDLE_READABLE |
820 GUESTFS_HANDLE_WRITABLE |
821 GUESTFS_HANDLE_HANGUP |
822 GUESTFS_HANDLE_ERROR)) != 0) {
823 error (g, "set of events (0x%x) contains unknown events", events);
828 error (g, "set of events is empty");
832 if (FD_ISSET (fd, &rset) || FD_ISSET (fd, &wset) || FD_ISSET (fd, &xset)) {
833 error (g, "fd %d is already registered", fd);
838 error (g, "callback is NULL");
842 if ((events & GUESTFS_HANDLE_READABLE))
844 if ((events & GUESTFS_HANDLE_WRITABLE))
846 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
851 handle_cb_data = safe_realloc (g, handle_cb_data,
852 sizeof (struct handle_cb_data) * (max_fd+1));
854 handle_cb_data[fd].cb = cb;
855 handle_cb_data[fd].data = data;
857 /* Any integer >= 0 can be the handle, and this is as good as any ... */
862 select_remove_handle (guestfs_h *g, int fd)
866 if (fd < 0 || fd >= FD_SETSIZE) {
867 error (g, "fd %d is out of range", fd);
871 if (!FD_ISSET (fd, &rset) && !FD_ISSET (fd, &wset) && !FD_ISSET (fd, &xset)) {
872 error (g, "fd %d was not registered", fd);
882 handle_cb_data = safe_realloc (g, handle_cb_data,
883 sizeof (struct handle_cb_data) * (max_fd+1));
890 select_add_timeout (guestfs_h *g, int interval,
891 guestfs_handle_timeout_cb cb, void *data)
895 abort (); /* XXX not implemented yet */
899 select_remove_timeout (guestfs_h *g, int timer)
903 abort (); /* XXX not implemented yet */
906 /* Note that main loops can be nested. */
907 static int level = 0;
910 select_main_loop_run (guestfs_h *g)
912 int old_level, fd, r, events;
913 fd_set rset2, wset2, xset2;
918 while (level > old_level) {
922 r = select (max_fd+1, &rset2, &wset2, &xset2, NULL);
924 perrorf (g, "select");
929 for (fd = 0; r > 0 && fd <= max_fd; ++fd) {
931 if (FD_ISSET (fd, &rset2))
932 events |= GUESTFS_HANDLE_READABLE;
933 if (FD_ISSET (fd, &wset2))
934 events |= GUESTFS_HANDLE_WRITABLE;
935 if (FD_ISSET (fd, &xset2))
936 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
939 handle_cb_data[fd].cb (handle_cb_data[fd].data,
947 select_main_loop_quit (guestfs_h *g)
952 error (g, "cannot quit, we are not in a main loop");