1 /* libguestfs - the guestfsd daemon
2 * Copyright (C) 2009 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program 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
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #define _BSD_SOURCE /* for daemon(3) */
27 #include <rpc/types.h>
31 #include <sys/param.h>
32 #include <sys/select.h>
33 #include <sys/types.h>
43 static void usage (void);
44 static char *read_cmdline (void);
46 /* Also in guestfs.c */
47 #define GUESTFWD_ADDR "10.0.2.4"
48 #define GUESTFWD_PORT "6666"
52 static int print_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
53 static int print_sysroot_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
54 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
55 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes, int *size);
57 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
58 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes);
60 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
64 /* Location to mount root device. */
65 const char *sysroot = "/sysroot"; /* No trailing slash. */
69 main (int argc, char *argv[])
71 static const char *options = "f?";
72 static const struct option long_options[] = {
73 { "foreground", 0, 0, 'f' },
74 { "help", 0, 0, '?' },
81 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
82 /* http://udrepper.livejournal.com/20948.html */
83 register_printf_specifier ('Q', print_shell_quote, print_arginfo);
84 register_printf_specifier ('R', print_sysroot_shell_quote, print_arginfo);
86 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
87 register_printf_function ('Q', print_shell_quote, print_arginfo);
88 register_printf_function ('R', print_sysroot_shell_quote, print_arginfo);
90 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
95 c = getopt_long (argc, argv, options, long_options, NULL);
108 fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
118 cmdline = read_cmdline ();
120 /* Set the verbose flag. */
121 verbose = cmdline && strstr (cmdline, "guestfs_verbose=1") != NULL;
123 printf ("verbose daemon enabled\n");
127 printf ("linux commmand line: %s\n", cmdline);
129 printf ("could not read linux command line\n");
132 /* Make sure SIGPIPE doesn't kill us. */
134 memset (&sa, 0, sizeof sa);
135 sa.sa_handler = SIG_IGN;
137 if (sigaction (SIGPIPE, &sa, NULL) == -1)
138 perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
140 /* Set up a basic environment. After we are called by /init the
141 * environment is essentially empty.
142 * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
144 setenv ("PATH", "/usr/bin:/bin", 1);
145 setenv ("SHELL", "/bin/sh", 1);
146 setenv ("LC_ALL", "C", 1);
148 /* We document that umask defaults to 022 (it should be this anyway). */
151 /* Resolve the hostname. */
152 struct addrinfo *res, *rr;
153 struct addrinfo hints;
155 memset (&hints, 0, sizeof hints);
156 hints.ai_socktype = SOCK_STREAM;
157 hints.ai_flags = AI_ADDRCONFIG;
158 r = getaddrinfo (GUESTFWD_ADDR, GUESTFWD_PORT, &hints, &res);
160 fprintf (stderr, "%s:%s: %s\n",
161 GUESTFWD_ADDR, GUESTFWD_PORT, gai_strerror (r));
165 /* Connect to the given TCP socket. */
167 for (rr = res; rr != NULL; rr = rr->ai_next) {
168 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
170 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
181 fprintf (stderr, "connection to %s:%s failed\n",
182 GUESTFWD_ADDR, GUESTFWD_PORT);
186 /* Send the magic length message which indicates that
187 * userspace is up inside the guest.
191 uint32_t len = GUESTFS_LAUNCH_FLAG;
192 xdrmem_create (&xdr, lenbuf, sizeof lenbuf, XDR_ENCODE);
193 xdr_uint32_t (&xdr, &len);
195 if (xwrite (sock, lenbuf, sizeof lenbuf) == -1)
200 /* Fork into the background. */
202 if (daemon (0, 1) == -1) {
208 /* Enter the main loop, reading and performing actions. */
214 /* Read /proc/cmdline. */
218 int fd = open ("/proc/cmdline", O_RDONLY);
220 perror ("/proc/cmdline");
230 n = read (fd, buf, sizeof buf);
239 char *newr = realloc (r, len + n + 1); /* + 1 is for terminating NUL */
247 memcpy (&r[len], buf, n);
254 if (close (fd) == -1) {
263 /* Turn "/path" into "/sysroot/path".
265 * Caller must check for NULL and call reply_with_perror ("malloc")
266 * if it is. Caller must also free the string.
268 * See also the custom %R printf formatter which does shell quoting too.
271 sysroot_path (const char *path)
274 int len = strlen (path) + sysroot_len + 1;
280 snprintf (r, len, "%s%s", sysroot, path);
285 xwrite (int sock, const void *v_buf, size_t len)
288 const char *buf = v_buf;
291 r = write (sock, buf, len);
304 xread (int sock, void *v_buf, size_t len)
310 r = read (sock, buf, len);
316 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
329 fprintf (stderr, "guestfsd [-f]\n");
333 add_string (char ***argv, int *size, int *alloc, const char *str)
338 if (*size >= *alloc) {
340 new_argv = realloc (*argv, *alloc * sizeof (char *));
341 if (new_argv == NULL) {
342 reply_with_perror ("realloc");
343 free_strings (*argv);
350 new_str = strdup (str);
351 if (new_str == NULL) {
352 reply_with_perror ("strdup");
353 free_strings (*argv);
358 (*argv)[*size] = new_str;
365 count_strings (char *const *argv)
369 for (argc = 0; argv[argc] != NULL; ++argc)
375 compare (const void *vp1, const void *vp2)
377 char * const *p1 = (char * const *) vp1;
378 char * const *p2 = (char * const *) vp2;
379 return strcmp (*p1, *p2);
383 sort_strings (char **argv, int len)
385 qsort (argv, len, sizeof (char *), compare);
389 free_strings (char **argv)
393 for (argc = 0; argv[argc] != NULL; ++argc)
399 free_stringslen (char **argv, int len)
403 for (i = 0; i < len; ++i)
408 /* This is a more sane version of 'system(3)' for running external
409 * commands. It uses fork/execvp, so we don't need to worry about
410 * quoting of parameters, and it allows us to capture any error
411 * messages in a buffer.
414 command (char **stdoutput, char **stderror, const char *name, ...)
421 /* Collect the command line arguments into an array. */
423 argv = malloc (sizeof (char *) * i);
428 argv[0] = (char *) name;
431 va_start (args, name);
433 while ((s = va_arg (args, char *)) != NULL) {
434 const char **p = realloc (argv, sizeof (char *) * (++i));
448 r = commandv (stdoutput, stderror, (char **) argv);
450 /* NB: Mustn't free the strings which are on the stack. */
456 /* Same as 'command', but we allow the status code from the
457 * subcommand to be non-zero, and return that status code.
458 * We still return -1 if there was some other error.
461 commandr (char **stdoutput, char **stderror, const char *name, ...)
468 /* Collect the command line arguments into an array. */
470 argv = malloc (sizeof (char *) * i);
475 argv[0] = (char *) name;
478 va_start (args, name);
480 while ((s = va_arg (args, char *)) != NULL) {
481 const char **p = realloc (argv, sizeof (char *) * (++i));
495 r = commandrv (stdoutput, stderror, argv);
497 /* NB: Mustn't free the strings which are on the stack. */
503 /* Same as 'command', but passing an argv. */
505 commandv (char **stdoutput, char **stderror, char *const *argv)
509 r = commandrv (stdoutput, stderror, (void *) argv);
517 commandrv (char **stdoutput, char **stderror, char const* const *argv)
519 int so_size = 0, se_size = 0;
520 int so_fd[2], se_fd[2];
527 if (stdoutput) *stdoutput = NULL;
528 if (stderror) *stderror = NULL;
531 printf ("%s", argv[0]);
532 for (i = 1; argv[i] != NULL; ++i)
533 printf (" %s", argv[i]);
537 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
552 if (pid == 0) { /* Child process. */
561 execvp (argv[0], (void *) argv);
566 /* Parent process. */
571 FD_SET (so_fd[0], &rset);
572 FD_SET (se_fd[0], &rset);
577 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
581 if (stdoutput) free (*stdoutput);
582 if (stderror) free (*stderror);
585 waitpid (pid, NULL, 0);
589 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
590 r = read (so_fd[0], buf, sizeof buf);
595 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
597 if (r > 0 && stdoutput) {
599 p = realloc (*stdoutput, so_size);
605 memcpy (*stdoutput + so_size - r, buf, r);
609 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
610 r = read (se_fd[0], buf, sizeof buf);
615 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
617 if (r > 0 && stderror) {
619 p = realloc (*stderror, se_size);
625 memcpy (*stderror + se_size - r, buf, r);
633 /* Make sure the output buffers are \0-terminated. Also remove any
634 * trailing \n characters from the error buffer (not from stdout).
637 void *q = realloc (*stdoutput, so_size+1);
644 (*stdoutput)[so_size] = '\0';
647 void *q = realloc (*stderror, se_size+1);
654 (*stderror)[se_size] = '\0';
656 while (se_size >= 0 && (*stderror)[se_size] == '\n')
657 (*stderror)[se_size--] = '\0';
661 /* Get the exit status of the command. */
662 if (waitpid (pid, &r, 0) != pid) {
668 return WEXITSTATUS (r);
673 /* Split an output string into a NULL-terminated list of lines.
674 * Typically this is used where we have run an external command
675 * which has printed out a list of things, and we want to return
678 * The corner cases here are quite tricky. Note in particular:
682 * "a\nb" -> ["a"; "b"]
683 * "a\nb\n" -> ["a"; "b"]
684 * "a\nb\n\n" -> ["a"; "b"; ""]
686 * The original string is written over and destroyed by this
687 * function (which is usually OK because it's the 'out' string
688 * from command()). You can free the original string, because
689 * add_string() strdups the strings.
692 split_lines (char *str)
695 int size = 0, alloc = 0;
698 if (strcmp (str, "") == 0)
703 /* Empty last line? */
707 pend = strchr (p, '\n');
713 if (add_string (&lines, &size, &alloc, p) == -1) {
721 if (add_string (&lines, &size, &alloc, NULL) == -1)
727 /* printf helper function so we can use %Q ("quoted") and %R to print
728 * shell-quoted strings. See HACKING file for more details.
731 print_shell_quote (FILE *stream,
732 const struct printf_info *info ATTRIBUTE_UNUSED,
733 const void *const *args)
735 #define SAFE(c) (isalnum((c)) || \
736 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
738 const char *str = *((const char **) (args[0]));
740 for (i = len = 0; str[i]; ++i) {
745 putc (str[i], stream);
753 print_sysroot_shell_quote (FILE *stream,
754 const struct printf_info *info,
755 const void *const *args)
757 fputs (sysroot, stream);
758 return sysroot_len + print_shell_quote (stream, info, args);
761 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
763 print_arginfo (const struct printf_info *info ATTRIBUTE_UNUSED,
764 size_t n, int *argtypes, int *size)
767 argtypes[0] = PA_STRING;
768 size[0] = sizeof (const char *);
773 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
775 print_arginfo (const struct printf_info *info, size_t n, int *argtypes)
778 argtypes[0] = PA_STRING;
782 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
786 /* Perform device name translation. Don't call this directly -
787 * use the RESOLVE_DEVICE macro.
789 * See guestfs(3) for the algorithm.
791 * We have to open the device and test for ENXIO, because
792 * the device nodes themselves will exist in the appliance.
795 device_name_translation (char *device, const char *func)
799 fd = open (device, O_RDONLY);
805 if (errno != ENXIO && errno != ENOENT) {
807 reply_with_perror ("%s: %s", func, device);
811 /* If the name begins with "/dev/sd" then try the alternatives. */
812 if (strncmp (device, "/dev/sd", 7) != 0)
815 device[5] = 'h'; /* /dev/hd (old IDE driver) */
816 fd = open (device, O_RDONLY);
822 device[5] = 'v'; /* /dev/vd (for virtio devices) */
823 fd = open (device, O_RDONLY);
829 device[5] = 's'; /* Restore original device name. */
833 /* LVM and other commands aren't synchronous, especially when udev is
834 * involved. eg. You can create or remove some device, but the /dev
835 * device node won't appear until some time later. This means that
836 * you get an error if you run one command followed by another.
837 * Use 'udevadm settle' after certain commands, but don't be too
838 * fussed if it fails.
843 command (NULL, NULL, "/sbin/udevadm", "settle", NULL);