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>
42 static void usage (void);
44 /* Also in guestfs.c */
45 #define VMCHANNEL_PORT "6666"
46 #define VMCHANNEL_ADDR "10.0.2.4"
51 main (int argc, char *argv[])
53 static const char *options = "fh:p:?";
54 static struct option long_options[] = {
55 { "foreground", 0, 0, 'f' },
56 { "help", 0, 0, '?' },
57 { "host", 1, 0, 'h' },
58 { "port", 1, 0, 'p' },
63 const char *host = NULL;
64 const char *port = NULL;
69 struct addrinfo *res, *rr;
70 struct addrinfo hints;
76 c = getopt_long (argc, argv, options, long_options, NULL);
97 fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
107 /* If host and port aren't set yet, try /proc/cmdline. */
108 if (!host || !port) {
109 fp = fopen ("/proc/cmdline", "r");
111 perror ("/proc/cmdline");
114 n = fread (buf, 1, sizeof buf - 1, fp);
118 /* Set the verbose flag. Not quite right because this will only
119 * set the flag if host and port aren't set on the command line.
120 * Don't worry about this for now. (XXX)
122 verbose = strstr (buf, "guestfs_verbose=1") != NULL;
124 printf ("verbose daemon enabled\n");
126 p = strstr (buf, "guestfs=");
130 p2 = strchr (p, ':');
134 r = strcspn (p2, " \n");
142 /* Can't parse /proc/cmdline, so use built-in defaults. */
143 if (!host || !port) {
144 host = VMCHANNEL_ADDR;
145 port = VMCHANNEL_PORT;
148 /* Make sure SIGPIPE doesn't kill us. */
149 memset (&sa, 0, sizeof sa);
150 sa.sa_handler = SIG_IGN;
152 if (sigaction (SIGPIPE, &sa, NULL) == -1)
153 perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
155 /* Set up a basic environment. After we are called by /init the
156 * environment is essentially empty.
157 * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
159 setenv ("PATH", "/usr/bin:/bin", 1);
160 setenv ("SHELL", "/bin/sh", 1);
161 setenv ("LANG", "C", 1);
163 /* Resolve the hostname. */
164 memset (&hints, 0, sizeof hints);
165 hints.ai_socktype = SOCK_STREAM;
166 hints.ai_flags = AI_ADDRCONFIG;
167 r = getaddrinfo (host, port, &hints, &res);
169 fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
173 /* Connect to the given TCP socket. */
175 for (rr = res; rr != NULL; rr = rr->ai_next) {
176 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
178 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
189 fprintf (stderr, "connection to %s:%s failed\n", host, port);
193 /* Send the magic length message which indicates that
194 * userspace is up inside the guest.
196 len = GUESTFS_LAUNCH_FLAG;
197 xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
198 if (!xdr_uint32_t (&xdr, &len)) {
199 fprintf (stderr, "xdr_uint32_t failed\n");
203 (void) xwrite (sock, buf, xdr_getpos (&xdr));
207 /* Fork into the background. */
209 if (daemon (0, 1) == -1) {
215 /* Enter the main loop, reading and performing actions. */
222 xwrite (int sock, const void *buf, size_t len)
227 r = write (sock, buf, len);
240 xread (int sock, void *buf, size_t len)
245 r = read (sock, buf, len);
251 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
264 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
268 add_string (char ***argv, int *size, int *alloc, const char *str)
273 if (*size >= *alloc) {
275 new_argv = realloc (*argv, *alloc * sizeof (char *));
276 if (new_argv == NULL) {
277 reply_with_perror ("realloc");
278 free_strings (*argv);
285 new_str = strdup (str);
286 if (new_str == NULL) {
287 reply_with_perror ("strdup");
288 free_strings (*argv);
293 (*argv)[*size] = new_str;
300 count_strings (char * const* const argv)
304 for (argc = 0; argv[argc] != NULL; ++argc)
310 compare (const void *vp1, const void *vp2)
312 char * const *p1 = (char * const *) vp1;
313 char * const *p2 = (char * const *) vp2;
314 return strcmp (*p1, *p2);
318 sort_strings (char **argv, int len)
320 qsort (argv, len, sizeof (char *), compare);
324 free_strings (char **argv)
328 for (argc = 0; argv[argc] != NULL; ++argc)
334 free_stringslen (char **argv, int len)
338 for (i = 0; i < len; ++i)
343 /* This is a more sane version of 'system(3)' for running external
344 * commands. It uses fork/execvp, so we don't need to worry about
345 * quoting of parameters, and it allows us to capture any error
346 * messages in a buffer.
349 command (char **stdoutput, char **stderror, const char *name, ...)
356 /* Collect the command line arguments into an array. */
358 argv = malloc (sizeof (char *) * i);
363 argv[0] = (char *) name;
366 va_start (args, name);
368 while ((s = va_arg (args, char *)) != NULL) {
369 p = realloc (argv, sizeof (char *) * (++i));
383 r = commandv (stdoutput, stderror, argv);
385 /* NB: Mustn't free the strings which are on the stack. */
391 /* Same as 'command', but we allow the status code from the
392 * subcommand to be non-zero, and return that status code.
393 * We still return -1 if there was some other error.
396 commandr (char **stdoutput, char **stderror, const char *name, ...)
403 /* Collect the command line arguments into an array. */
405 argv = malloc (sizeof (char *) * i);
410 argv[0] = (char *) name;
413 va_start (args, name);
415 while ((s = va_arg (args, char *)) != NULL) {
416 p = realloc (argv, sizeof (char *) * (++i));
430 r = commandrv (stdoutput, stderror, argv);
432 /* NB: Mustn't free the strings which are on the stack. */
438 /* Same as 'command', but passing an argv. */
440 commandv (char **stdoutput, char **stderror, char * const* const argv)
444 r = commandrv (stdoutput, stderror, argv);
452 commandrv (char **stdoutput, char **stderror, char * const* const argv)
454 int so_size = 0, se_size = 0;
455 int so_fd[2], se_fd[2];
461 if (stdoutput) *stdoutput = NULL;
462 if (stderror) *stderror = NULL;
465 printf ("%s", argv[0]);
466 for (i = 1; argv[i] != NULL; ++i)
467 printf (" %s", argv[i]);
471 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
486 if (pid == 0) { /* Child process. */
495 execvp (argv[0], argv);
500 /* Parent process. */
505 FD_SET (so_fd[0], &rset);
506 FD_SET (se_fd[0], &rset);
511 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
515 if (stdoutput) free (*stdoutput);
516 if (stderror) free (*stderror);
519 waitpid (pid, NULL, 0);
523 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
524 r = read (so_fd[0], buf, sizeof buf);
529 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
531 if (r > 0 && stdoutput) {
533 p = realloc (*stdoutput, so_size);
539 memcpy (*stdoutput + so_size - r, buf, r);
543 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
544 r = read (se_fd[0], buf, sizeof buf);
549 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
551 if (r > 0 && stderror) {
553 p = realloc (*stderror, se_size);
559 memcpy (*stderror + se_size - r, buf, r);
567 /* Make sure the output buffers are \0-terminated. Also remove any
568 * trailing \n characters from the error buffer (not from stdout).
571 *stdoutput = realloc (*stdoutput, so_size+1);
572 if (*stdoutput == NULL) {
576 (*stdoutput)[so_size] = '\0';
579 *stderror = realloc (*stderror, se_size+1);
580 if (*stderror == NULL) {
584 (*stderror)[se_size] = '\0';
586 while (se_size >= 0 && (*stderror)[se_size] == '\n')
587 (*stderror)[se_size--] = '\0';
591 /* Get the exit status of the command. */
592 waitpid (pid, &r, 0);
595 return WEXITSTATUS (r);
600 /* Split an output string into a NULL-terminated list of lines.
601 * Typically this is used where we have run an external command
602 * which has printed out a list of things, and we want to return
605 * The corner cases here are quite tricky. Note in particular:
609 * "a\nb" -> ["a"; "b"]
610 * "a\nb\n" -> ["a"; "b"]
611 * "a\nb\n\n" -> ["a"; "b"; ""]
613 * The original string is written over and destroyed by this
614 * function (which is usually OK because it's the 'out' string
615 * from command()). You can free the original string, because
616 * add_string() strdups the strings.
619 split_lines (char *str)
622 int size = 0, alloc = 0;
625 if (strcmp (str, "") == 0)
630 /* Empty last line? */
634 pend = strchr (p, '\n');
640 if (add_string (&lines, &size, &alloc, p) == -1) {
648 if (add_string (&lines, &size, &alloc, NULL) == -1)
654 /* Quote 'in' for the shell, and write max len-1 bytes to out. The
655 * result will be NUL-terminated, even if it is truncated.
657 * Returns number of bytes needed, so if result >= len then the buffer
658 * should have been longer.
660 * XXX This doesn't quote \n correctly (but is still safe).
663 shell_quote (char *out, int len, const char *in)
665 #define SAFE(c) (isalnum((c)) || \
666 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
668 int outlen = strlen (in);
670 /* Calculate how much output space this really needs. */
671 for (i = 0; in[i]; ++i)
672 if (!SAFE (in[i])) outlen++;
674 /* Now copy the string, but only up to len-1 bytes. */
675 for (i = 0, j = 0; in[i]; ++i) {
676 int is_safe = SAFE (in[i]);
678 /* Enough space left to write this character? */
679 if (j >= len-1 || (!is_safe && j >= len-2))
682 if (!is_safe) out[j++] = '\\';
691 /* Perform device name translation. Don't call this directly -
692 * use the IS_DEVICE macro.
694 * See guestfs(3) for the algorithm.
696 * We have to open the device and test for ENXIO, because
697 * the device nodes themselves will exist in the appliance.
700 device_name_translation (char *device, const char *func)
704 fd = open (device, O_RDONLY);
710 if (errno != ENXIO) {
712 reply_with_perror ("%s: %s", func, device);
716 /* If the name begins with "/dev/sd" then try the alternatives. */
717 if (strncmp (device, "/dev/sd", 7) != 0)
720 device[5] = 'h'; /* /dev/hd (old IDE driver) */
721 fd = open (device, O_RDONLY);
727 device[5] = 'v'; /* /dev/vd (for virtio devices) */
728 fd = open (device, O_RDONLY);
734 device[5] = 's'; /* Restore original device name. */