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 ("LANG", "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 *buf, size_t len)
281 r = write (sock, buf, len);
294 xread (int sock, void *buf, size_t len)
299 r = read (sock, buf, len);
305 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
318 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
322 add_string (char ***argv, int *size, int *alloc, const char *str)
327 if (*size >= *alloc) {
329 new_argv = realloc (*argv, *alloc * sizeof (char *));
330 if (new_argv == NULL) {
331 reply_with_perror ("realloc");
332 free_strings (*argv);
339 new_str = strdup (str);
340 if (new_str == NULL) {
341 reply_with_perror ("strdup");
342 free_strings (*argv);
347 (*argv)[*size] = new_str;
354 count_strings (char * const* const argv)
358 for (argc = 0; argv[argc] != NULL; ++argc)
364 compare (const void *vp1, const void *vp2)
366 char * const *p1 = (char * const *) vp1;
367 char * const *p2 = (char * const *) vp2;
368 return strcmp (*p1, *p2);
372 sort_strings (char **argv, int len)
374 qsort (argv, len, sizeof (char *), compare);
378 free_strings (char **argv)
382 for (argc = 0; argv[argc] != NULL; ++argc)
388 free_stringslen (char **argv, int len)
392 for (i = 0; i < len; ++i)
397 /* This is a more sane version of 'system(3)' for running external
398 * commands. It uses fork/execvp, so we don't need to worry about
399 * quoting of parameters, and it allows us to capture any error
400 * messages in a buffer.
403 command (char **stdoutput, char **stderror, const char *name, ...)
410 /* Collect the command line arguments into an array. */
412 argv = malloc (sizeof (char *) * i);
417 argv[0] = (char *) name;
420 va_start (args, name);
422 while ((s = va_arg (args, char *)) != NULL) {
423 p = realloc (argv, sizeof (char *) * (++i));
437 r = commandv (stdoutput, stderror, argv);
439 /* NB: Mustn't free the strings which are on the stack. */
445 /* Same as 'command', but we allow the status code from the
446 * subcommand to be non-zero, and return that status code.
447 * We still return -1 if there was some other error.
450 commandr (char **stdoutput, char **stderror, const char *name, ...)
457 /* Collect the command line arguments into an array. */
459 argv = malloc (sizeof (char *) * i);
464 argv[0] = (char *) name;
467 va_start (args, name);
469 while ((s = va_arg (args, char *)) != NULL) {
470 p = realloc (argv, sizeof (char *) * (++i));
484 r = commandrv (stdoutput, stderror, argv);
486 /* NB: Mustn't free the strings which are on the stack. */
492 /* Same as 'command', but passing an argv. */
494 commandv (char **stdoutput, char **stderror, char * const* const argv)
498 r = commandrv (stdoutput, stderror, argv);
506 commandrv (char **stdoutput, char **stderror, char * const* const argv)
508 int so_size = 0, se_size = 0;
509 int so_fd[2], se_fd[2];
516 if (stdoutput) *stdoutput = NULL;
517 if (stderror) *stderror = NULL;
520 printf ("%s", argv[0]);
521 for (i = 1; argv[i] != NULL; ++i)
522 printf (" %s", argv[i]);
526 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
541 if (pid == 0) { /* Child process. */
550 execvp (argv[0], argv);
555 /* Parent process. */
560 FD_SET (so_fd[0], &rset);
561 FD_SET (se_fd[0], &rset);
566 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
570 if (stdoutput) free (*stdoutput);
571 if (stderror) free (*stderror);
574 waitpid (pid, NULL, 0);
578 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
579 r = read (so_fd[0], buf, sizeof buf);
584 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
586 if (r > 0 && stdoutput) {
588 p = realloc (*stdoutput, so_size);
594 memcpy (*stdoutput + so_size - r, buf, r);
598 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
599 r = read (se_fd[0], buf, sizeof buf);
604 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
606 if (r > 0 && stderror) {
608 p = realloc (*stderror, se_size);
614 memcpy (*stderror + se_size - r, buf, r);
622 /* Make sure the output buffers are \0-terminated. Also remove any
623 * trailing \n characters from the error buffer (not from stdout).
626 void *q = realloc (*stdoutput, so_size+1);
633 (*stdoutput)[so_size] = '\0';
636 void *q = realloc (*stderror, se_size+1);
643 (*stderror)[se_size] = '\0';
645 while (se_size >= 0 && (*stderror)[se_size] == '\n')
646 (*stderror)[se_size--] = '\0';
650 /* Get the exit status of the command. */
651 if (waitpid (pid, &r, 0) != pid) {
657 return WEXITSTATUS (r);
662 /* Split an output string into a NULL-terminated list of lines.
663 * Typically this is used where we have run an external command
664 * which has printed out a list of things, and we want to return
667 * The corner cases here are quite tricky. Note in particular:
671 * "a\nb" -> ["a"; "b"]
672 * "a\nb\n" -> ["a"; "b"]
673 * "a\nb\n\n" -> ["a"; "b"; ""]
675 * The original string is written over and destroyed by this
676 * function (which is usually OK because it's the 'out' string
677 * from command()). You can free the original string, because
678 * add_string() strdups the strings.
681 split_lines (char *str)
684 int size = 0, alloc = 0;
687 if (strcmp (str, "") == 0)
692 /* Empty last line? */
696 pend = strchr (p, '\n');
702 if (add_string (&lines, &size, &alloc, p) == -1) {
710 if (add_string (&lines, &size, &alloc, NULL) == -1)
716 /* printf helper function so we can use %Q ("quoted") and %R to print
717 * shell-quoted strings. See HACKING file for more details.
720 print_shell_quote (FILE *stream,
721 const struct printf_info *info,
722 const void *const *args)
724 #define SAFE(c) (isalnum((c)) || \
725 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
727 const char *str = *((const char **) (args[0]));
729 for (i = len = 0; str[i]; ++i) {
734 putc (str[i], stream);
742 print_sysroot_shell_quote (FILE *stream,
743 const struct printf_info *info,
744 const void *const *args)
746 #define SAFE(c) (isalnum((c)) || \
747 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
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,
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 IS_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);