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>
40 static void usage (void);
42 /* Also in guestfs.c */
43 #define VMCHANNEL_PORT "6666"
44 #define VMCHANNEL_ADDR "10.0.2.4"
49 main (int argc, char *argv[])
51 static const char *options = "fh:p:?";
52 static struct option long_options[] = {
53 { "foreground", 0, 0, 'f' },
54 { "help", 0, 0, '?' },
55 { "host", 1, 0, 'h' },
56 { "port", 1, 0, 'p' },
61 const char *host = NULL;
62 const char *port = NULL;
67 struct addrinfo *res, *rr;
68 struct addrinfo hints;
74 c = getopt_long (argc, argv, options, long_options, NULL);
95 fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
105 /* If host and port aren't set yet, try /proc/cmdline. */
106 if (!host || !port) {
107 fp = fopen ("/proc/cmdline", "r");
109 perror ("/proc/cmdline");
112 n = fread (buf, 1, sizeof buf - 1, fp);
116 /* Set the verbose flag. Not quite right because this will only
117 * set the flag if host and port aren't set on the command line.
118 * Don't worry about this for now. (XXX)
120 verbose = strstr (buf, "guestfs_verbose=1") != NULL;
122 printf ("verbose daemon enabled\n");
124 p = strstr (buf, "guestfs=");
128 p2 = strchr (p, ':');
132 r = strcspn (p2, " \n");
140 /* Can't parse /proc/cmdline, so use built-in defaults. */
141 if (!host || !port) {
142 host = VMCHANNEL_ADDR;
143 port = VMCHANNEL_PORT;
146 /* Make sure SIGPIPE doesn't kill us. */
147 memset (&sa, 0, sizeof sa);
148 sa.sa_handler = SIG_IGN;
150 if (sigaction (SIGPIPE, &sa, NULL) == -1)
151 perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
153 /* Set up a basic environment. After we are called by /init the
154 * environment is essentially empty.
155 * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
157 setenv ("PATH", "/usr/bin:/bin", 1);
158 setenv ("SHELL", "/bin/sh", 1);
159 setenv ("LANG", "C", 1);
161 /* Resolve the hostname. */
162 memset (&hints, 0, sizeof hints);
163 hints.ai_socktype = SOCK_STREAM;
164 hints.ai_flags = AI_ADDRCONFIG;
165 r = getaddrinfo (host, port, &hints, &res);
167 fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
171 /* Connect to the given TCP socket. */
173 for (rr = res; rr != NULL; rr = rr->ai_next) {
174 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
176 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
187 fprintf (stderr, "connection to %s:%s failed\n", host, port);
191 /* Send the magic length message which indicates that
192 * userspace is up inside the guest.
194 len = GUESTFS_LAUNCH_FLAG;
195 xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
196 if (!xdr_uint32_t (&xdr, &len)) {
197 fprintf (stderr, "xdr_uint32_t failed\n");
201 (void) xwrite (sock, buf, xdr_getpos (&xdr));
205 /* Fork into the background. */
207 if (daemon (0, 1) == -1) {
213 /* Enter the main loop, reading and performing actions. */
220 xwrite (int sock, const void *buf, size_t len)
225 r = write (sock, buf, len);
238 xread (int sock, void *buf, size_t len)
243 r = read (sock, buf, len);
249 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
262 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
266 add_string (char ***argv, int *size, int *alloc, const char *str)
271 if (*size >= *alloc) {
273 new_argv = realloc (*argv, *alloc * sizeof (char *));
274 if (new_argv == NULL) {
275 reply_with_perror ("realloc");
276 free_strings (*argv);
283 new_str = strdup (str);
284 if (new_str == NULL) {
285 reply_with_perror ("strdup");
286 free_strings (*argv);
291 (*argv)[*size] = new_str;
298 count_strings (char * const* const argv)
302 for (argc = 0; argv[argc] != NULL; ++argc)
308 compare (const void *vp1, const void *vp2)
310 char * const *p1 = (char * const *) vp1;
311 char * const *p2 = (char * const *) vp2;
312 return strcmp (*p1, *p2);
316 sort_strings (char **argv, int len)
318 qsort (argv, len, sizeof (char *), compare);
322 free_strings (char **argv)
326 for (argc = 0; argv[argc] != NULL; ++argc)
332 free_stringslen (char **argv, int len)
336 for (i = 0; i < len; ++i)
341 /* This is a more sane version of 'system(3)' for running external
342 * commands. It uses fork/execvp, so we don't need to worry about
343 * quoting of parameters, and it allows us to capture any error
344 * messages in a buffer.
347 command (char **stdoutput, char **stderror, const char *name, ...)
354 /* Collect the command line arguments into an array. */
356 argv = malloc (sizeof (char *) * i);
361 argv[0] = (char *) name;
364 va_start (args, name);
366 while ((s = va_arg (args, char *)) != NULL) {
367 p = realloc (argv, sizeof (char *) * (++i));
381 r = commandv (stdoutput, stderror, argv);
383 /* NB: Mustn't free the strings which are on the stack. */
389 /* Same as 'command', but we allow the status code from the
390 * subcommand to be non-zero, and return that status code.
391 * We still return -1 if there was some other error.
394 commandr (char **stdoutput, char **stderror, const char *name, ...)
401 /* Collect the command line arguments into an array. */
403 argv = malloc (sizeof (char *) * i);
408 argv[0] = (char *) name;
411 va_start (args, name);
413 while ((s = va_arg (args, char *)) != NULL) {
414 p = realloc (argv, sizeof (char *) * (++i));
428 r = commandrv (stdoutput, stderror, argv);
430 /* NB: Mustn't free the strings which are on the stack. */
436 /* Same as 'command', but passing an argv. */
438 commandv (char **stdoutput, char **stderror, char * const* const argv)
442 r = commandrv (stdoutput, stderror, argv);
450 commandrv (char **stdoutput, char **stderror, char * const* const argv)
452 int so_size = 0, se_size = 0;
453 int so_fd[2], se_fd[2];
459 if (stdoutput) *stdoutput = NULL;
460 if (stderror) *stderror = NULL;
463 printf ("%s", argv[0]);
464 for (i = 1; argv[i] != NULL; ++i)
465 printf (" %s", argv[i]);
469 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
484 if (pid == 0) { /* Child process. */
493 execvp (argv[0], argv);
498 /* Parent process. */
503 FD_SET (so_fd[0], &rset);
504 FD_SET (se_fd[0], &rset);
509 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
513 if (stdoutput) free (*stdoutput);
514 if (stderror) free (*stderror);
517 waitpid (pid, NULL, 0);
521 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
522 r = read (so_fd[0], buf, sizeof buf);
527 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
529 if (r > 0 && stdoutput) {
531 p = realloc (*stdoutput, so_size);
537 memcpy (*stdoutput + so_size - r, buf, r);
541 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
542 r = read (se_fd[0], buf, sizeof buf);
547 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
549 if (r > 0 && stderror) {
551 p = realloc (*stderror, se_size);
557 memcpy (*stderror + se_size - r, buf, r);
565 /* Make sure the output buffers are \0-terminated. Also remove any
566 * trailing \n characters from the error buffer (not from stdout).
569 *stdoutput = realloc (*stdoutput, so_size+1);
570 if (*stdoutput == NULL) {
574 (*stdoutput)[so_size] = '\0';
577 *stderror = realloc (*stderror, se_size+1);
578 if (*stderror == NULL) {
582 (*stderror)[se_size] = '\0';
584 while (se_size >= 0 && (*stderror)[se_size] == '\n')
585 (*stderror)[se_size--] = '\0';
589 /* Get the exit status of the command. */
590 waitpid (pid, &r, 0);
593 return WEXITSTATUS (r);
598 /* Split an output string into a NULL-terminated list of lines.
599 * Typically this is used where we have run an external command
600 * which has printed out a list of things, and we want to return
603 * The corner cases here are quite tricky. Note in particular:
607 * "a\nb" -> ["a"; "b"]
608 * "a\nb\n" -> ["a"; "b"]
609 * "a\nb\n\n" -> ["a"; "b"; ""]
611 * The original string is written over and destroyed by this
612 * function (which is usually OK because it's the 'out' string
613 * from command()). You can free the original string, because
614 * add_string() strdups the strings.
617 split_lines (char *str)
620 int size = 0, alloc = 0;
623 if (strcmp (str, "") == 0)
628 /* Empty last line? */
632 pend = strchr (p, '\n');
638 if (add_string (&lines, &size, &alloc, p) == -1) {
646 if (add_string (&lines, &size, &alloc, NULL) == -1)
652 /* Quote 'in' for the shell, and write max len-1 bytes to out. The
653 * result will be NUL-terminated, even if it is truncated.
655 * Returns number of bytes needed, so if result >= len then the buffer
656 * should have been longer.
658 * XXX This doesn't quote \n correctly (but is still safe).
661 shell_quote (char *out, int len, const char *in)
663 #define SAFE(c) (isalnum((c)) || \
664 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
666 int outlen = strlen (in);
668 /* Calculate how much output space this really needs. */
669 for (i = 0; in[i]; ++i)
670 if (!SAFE (in[i])) outlen++;
672 /* Now copy the string, but only up to len-1 bytes. */
673 for (i = 0, j = 0; in[i]; ++i) {
674 int is_safe = SAFE (in[i]);
676 /* Enough space left to write this character? */
677 if (j >= len-1 || (!is_safe && j >= len-2))
680 if (!is_safe) out[j++] = '\\';