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);
45 /* Also in guestfs.c */
46 #define VMCHANNEL_PORT "6666"
47 #define VMCHANNEL_ADDR "10.0.2.4"
51 static int print_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
52 static int print_sysroot_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
53 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
54 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes, int *size);
56 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
57 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes);
59 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
63 /* Location to mount root device. */
64 const char *sysroot = "/sysroot"; /* No trailing slash. */
68 main (int argc, char *argv[])
70 static const char *options = "fh:p:?";
71 static const struct option long_options[] = {
72 { "foreground", 0, 0, 'f' },
73 { "help", 0, 0, '?' },
74 { "host", 1, 0, 'h' },
75 { "port", 1, 0, 'p' },
80 const char *host = NULL;
81 const char *port = NULL;
86 struct addrinfo *res, *rr;
87 struct addrinfo hints;
92 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
93 /* http://udrepper.livejournal.com/20948.html */
94 register_printf_specifier ('Q', print_shell_quote, print_arginfo);
95 register_printf_specifier ('R', print_sysroot_shell_quote, print_arginfo);
97 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
98 register_printf_function ('Q', print_shell_quote, print_arginfo);
99 register_printf_function ('R', print_sysroot_shell_quote, print_arginfo);
101 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
106 c = getopt_long (argc, argv, options, long_options, NULL);
127 fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
137 /* If host and port aren't set yet, try /proc/cmdline. */
138 if (!host || !port) {
139 fp = fopen ("/proc/cmdline", "r");
141 perror ("/proc/cmdline");
144 n = fread (buf, 1, sizeof buf - 1, fp);
148 /* Set the verbose flag. Not quite right because this will only
149 * set the flag if host and port aren't set on the command line.
150 * Don't worry about this for now. (XXX)
152 verbose = strstr (buf, "guestfs_verbose=1") != NULL;
154 printf ("verbose daemon enabled\n");
156 p = strstr (buf, "guestfs=");
160 p2 = strchr (p, ':');
164 r = strcspn (p2, " \n");
172 /* Can't parse /proc/cmdline, so use built-in defaults. */
173 if (!host || !port) {
174 host = VMCHANNEL_ADDR;
175 port = VMCHANNEL_PORT;
178 /* Make sure SIGPIPE doesn't kill us. */
179 memset (&sa, 0, sizeof sa);
180 sa.sa_handler = SIG_IGN;
182 if (sigaction (SIGPIPE, &sa, NULL) == -1)
183 perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
185 /* Set up a basic environment. After we are called by /init the
186 * environment is essentially empty.
187 * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
189 setenv ("PATH", "/usr/bin:/bin", 1);
190 setenv ("SHELL", "/bin/sh", 1);
191 setenv ("LC_ALL", "C", 1);
193 /* We document that umask defaults to 022 (it should be this anyway). */
196 /* Resolve the hostname. */
197 memset (&hints, 0, sizeof hints);
198 hints.ai_socktype = SOCK_STREAM;
199 hints.ai_flags = AI_ADDRCONFIG;
200 r = getaddrinfo (host, port, &hints, &res);
202 fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
206 /* Connect to the given TCP socket. */
208 for (rr = res; rr != NULL; rr = rr->ai_next) {
209 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
211 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
222 fprintf (stderr, "connection to %s:%s failed\n", host, port);
226 /* Send the magic length message which indicates that
227 * userspace is up inside the guest.
229 len = GUESTFS_LAUNCH_FLAG;
230 xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
231 if (!xdr_uint32_t (&xdr, &len)) {
232 fprintf (stderr, "xdr_uint32_t failed\n");
236 (void) xwrite (sock, buf, xdr_getpos (&xdr));
240 /* Fork into the background. */
242 if (daemon (0, 1) == -1) {
248 /* Enter the main loop, reading and performing actions. */
254 /* Turn "/path" into "/sysroot/path".
256 * Caller must check for NULL and call reply_with_perror ("malloc")
257 * if it is. Caller must also free the string.
259 * See also the custom %R printf formatter which does shell quoting too.
262 sysroot_path (const char *path)
265 int len = strlen (path) + sysroot_len + 1;
271 snprintf (r, len, "%s%s", sysroot, path);
276 xwrite (int sock, const void *v_buf, size_t len)
279 const char *buf = v_buf;
282 r = write (sock, buf, len);
295 xread (int sock, void *v_buf, size_t len)
301 r = read (sock, buf, len);
307 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
320 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
324 add_string (char ***argv, int *size, int *alloc, const char *str)
329 if (*size >= *alloc) {
331 new_argv = realloc (*argv, *alloc * sizeof (char *));
332 if (new_argv == NULL) {
333 reply_with_perror ("realloc");
334 free_strings (*argv);
341 new_str = strdup (str);
342 if (new_str == NULL) {
343 reply_with_perror ("strdup");
344 free_strings (*argv);
349 (*argv)[*size] = new_str;
356 count_strings (char *const *argv)
360 for (argc = 0; argv[argc] != NULL; ++argc)
366 compare (const void *vp1, const void *vp2)
368 char * const *p1 = (char * const *) vp1;
369 char * const *p2 = (char * const *) vp2;
370 return strcmp (*p1, *p2);
374 sort_strings (char **argv, int len)
376 qsort (argv, len, sizeof (char *), compare);
380 free_strings (char **argv)
384 for (argc = 0; argv[argc] != NULL; ++argc)
390 free_stringslen (char **argv, int len)
394 for (i = 0; i < len; ++i)
399 /* This is a more sane version of 'system(3)' for running external
400 * commands. It uses fork/execvp, so we don't need to worry about
401 * quoting of parameters, and it allows us to capture any error
402 * messages in a buffer.
405 command (char **stdoutput, char **stderror, const char *name, ...)
412 /* Collect the command line arguments into an array. */
414 argv = malloc (sizeof (char *) * i);
419 argv[0] = (char *) name;
422 va_start (args, name);
424 while ((s = va_arg (args, char *)) != NULL) {
425 const char **p = realloc (argv, sizeof (char *) * (++i));
439 r = commandv (stdoutput, stderror, (char **) argv);
441 /* NB: Mustn't free the strings which are on the stack. */
447 /* Same as 'command', but we allow the status code from the
448 * subcommand to be non-zero, and return that status code.
449 * We still return -1 if there was some other error.
452 commandr (char **stdoutput, char **stderror, const char *name, ...)
459 /* Collect the command line arguments into an array. */
461 argv = malloc (sizeof (char *) * i);
466 argv[0] = (char *) name;
469 va_start (args, name);
471 while ((s = va_arg (args, char *)) != NULL) {
472 const char **p = realloc (argv, sizeof (char *) * (++i));
486 r = commandrv (stdoutput, stderror, argv);
488 /* NB: Mustn't free the strings which are on the stack. */
494 /* Same as 'command', but passing an argv. */
496 commandv (char **stdoutput, char **stderror, char *const *argv)
500 r = commandrv (stdoutput, stderror, (void *) argv);
508 commandrv (char **stdoutput, char **stderror, char const* const *argv)
510 int so_size = 0, se_size = 0;
511 int so_fd[2], se_fd[2];
518 if (stdoutput) *stdoutput = NULL;
519 if (stderror) *stderror = NULL;
522 printf ("%s", argv[0]);
523 for (i = 1; argv[i] != NULL; ++i)
524 printf (" %s", argv[i]);
528 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
543 if (pid == 0) { /* Child process. */
552 execvp (argv[0], (void *) argv);
557 /* Parent process. */
562 FD_SET (so_fd[0], &rset);
563 FD_SET (se_fd[0], &rset);
568 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
572 if (stdoutput) free (*stdoutput);
573 if (stderror) free (*stderror);
576 waitpid (pid, NULL, 0);
580 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
581 r = read (so_fd[0], buf, sizeof buf);
586 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
588 if (r > 0 && stdoutput) {
590 p = realloc (*stdoutput, so_size);
596 memcpy (*stdoutput + so_size - r, buf, r);
600 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
601 r = read (se_fd[0], buf, sizeof buf);
606 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
608 if (r > 0 && stderror) {
610 p = realloc (*stderror, se_size);
616 memcpy (*stderror + se_size - r, buf, r);
624 /* Make sure the output buffers are \0-terminated. Also remove any
625 * trailing \n characters from the error buffer (not from stdout).
628 void *q = realloc (*stdoutput, so_size+1);
635 (*stdoutput)[so_size] = '\0';
638 void *q = realloc (*stderror, se_size+1);
645 (*stderror)[se_size] = '\0';
647 while (se_size >= 0 && (*stderror)[se_size] == '\n')
648 (*stderror)[se_size--] = '\0';
652 /* Get the exit status of the command. */
653 if (waitpid (pid, &r, 0) != pid) {
659 return WEXITSTATUS (r);
664 /* Split an output string into a NULL-terminated list of lines.
665 * Typically this is used where we have run an external command
666 * which has printed out a list of things, and we want to return
669 * The corner cases here are quite tricky. Note in particular:
673 * "a\nb" -> ["a"; "b"]
674 * "a\nb\n" -> ["a"; "b"]
675 * "a\nb\n\n" -> ["a"; "b"; ""]
677 * The original string is written over and destroyed by this
678 * function (which is usually OK because it's the 'out' string
679 * from command()). You can free the original string, because
680 * add_string() strdups the strings.
683 split_lines (char *str)
686 int size = 0, alloc = 0;
689 if (strcmp (str, "") == 0)
694 /* Empty last line? */
698 pend = strchr (p, '\n');
704 if (add_string (&lines, &size, &alloc, p) == -1) {
712 if (add_string (&lines, &size, &alloc, NULL) == -1)
718 /* printf helper function so we can use %Q ("quoted") and %R to print
719 * shell-quoted strings. See HACKING file for more details.
722 print_shell_quote (FILE *stream,
723 const struct printf_info *info ATTRIBUTE_UNUSED,
724 const void *const *args)
726 #define SAFE(c) (isalnum((c)) || \
727 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
729 const char *str = *((const char **) (args[0]));
731 for (i = len = 0; str[i]; ++i) {
736 putc (str[i], stream);
744 print_sysroot_shell_quote (FILE *stream,
745 const struct printf_info *info,
746 const void *const *args)
748 fputs (sysroot, stream);
749 return sysroot_len + print_shell_quote (stream, info, args);
752 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
754 print_arginfo (const struct printf_info *info ATTRIBUTE_UNUSED,
755 size_t n, int *argtypes, int *size)
758 argtypes[0] = PA_STRING;
759 size[0] = sizeof (const char *);
764 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
766 print_arginfo (const struct printf_info *info, size_t n, int *argtypes)
769 argtypes[0] = PA_STRING;
773 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
777 /* Perform device name translation. Don't call this directly -
778 * use the RESOLVE_DEVICE macro.
780 * See guestfs(3) for the algorithm.
782 * We have to open the device and test for ENXIO, because
783 * the device nodes themselves will exist in the appliance.
786 device_name_translation (char *device, const char *func)
790 fd = open (device, O_RDONLY);
796 if (errno != ENXIO && errno != ENOENT) {
798 reply_with_perror ("%s: %s", func, device);
802 /* If the name begins with "/dev/sd" then try the alternatives. */
803 if (strncmp (device, "/dev/sd", 7) != 0)
806 device[5] = 'h'; /* /dev/hd (old IDE driver) */
807 fd = open (device, O_RDONLY);
813 device[5] = 'v'; /* /dev/vd (for virtio devices) */
814 fd = open (device, O_RDONLY);
820 device[5] = 's'; /* Restore original device name. */
824 /* LVM and other commands aren't synchronous, especially when udev is
825 * involved. eg. You can create or remove some device, but the /dev
826 * device node won't appear until some time later. This means that
827 * you get an error if you run one command followed by another.
828 * Use 'udevadm settle' after certain commands, but don't be too
829 * fussed if it fails.
834 command (NULL, NULL, "/sbin/udevadm", "settle", NULL);