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 /* We document that umask defaults to 022 (it should be this anyway). */
166 /* Resolve the hostname. */
167 memset (&hints, 0, sizeof hints);
168 hints.ai_socktype = SOCK_STREAM;
169 hints.ai_flags = AI_ADDRCONFIG;
170 r = getaddrinfo (host, port, &hints, &res);
172 fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
176 /* Connect to the given TCP socket. */
178 for (rr = res; rr != NULL; rr = rr->ai_next) {
179 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
181 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
192 fprintf (stderr, "connection to %s:%s failed\n", host, port);
196 /* Send the magic length message which indicates that
197 * userspace is up inside the guest.
199 len = GUESTFS_LAUNCH_FLAG;
200 xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
201 if (!xdr_uint32_t (&xdr, &len)) {
202 fprintf (stderr, "xdr_uint32_t failed\n");
206 (void) xwrite (sock, buf, xdr_getpos (&xdr));
210 /* Fork into the background. */
212 if (daemon (0, 1) == -1) {
218 /* Enter the main loop, reading and performing actions. */
225 xwrite (int sock, const void *buf, size_t len)
230 r = write (sock, buf, len);
243 xread (int sock, void *buf, size_t len)
248 r = read (sock, buf, len);
254 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
267 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
271 add_string (char ***argv, int *size, int *alloc, const char *str)
276 if (*size >= *alloc) {
278 new_argv = realloc (*argv, *alloc * sizeof (char *));
279 if (new_argv == NULL) {
280 reply_with_perror ("realloc");
281 free_strings (*argv);
288 new_str = strdup (str);
289 if (new_str == NULL) {
290 reply_with_perror ("strdup");
291 free_strings (*argv);
296 (*argv)[*size] = new_str;
303 count_strings (char * const* const argv)
307 for (argc = 0; argv[argc] != NULL; ++argc)
313 compare (const void *vp1, const void *vp2)
315 char * const *p1 = (char * const *) vp1;
316 char * const *p2 = (char * const *) vp2;
317 return strcmp (*p1, *p2);
321 sort_strings (char **argv, int len)
323 qsort (argv, len, sizeof (char *), compare);
327 free_strings (char **argv)
331 for (argc = 0; argv[argc] != NULL; ++argc)
337 free_stringslen (char **argv, int len)
341 for (i = 0; i < len; ++i)
346 /* This is a more sane version of 'system(3)' for running external
347 * commands. It uses fork/execvp, so we don't need to worry about
348 * quoting of parameters, and it allows us to capture any error
349 * messages in a buffer.
352 command (char **stdoutput, char **stderror, const char *name, ...)
359 /* Collect the command line arguments into an array. */
361 argv = malloc (sizeof (char *) * i);
366 argv[0] = (char *) name;
369 va_start (args, name);
371 while ((s = va_arg (args, char *)) != NULL) {
372 p = realloc (argv, sizeof (char *) * (++i));
386 r = commandv (stdoutput, stderror, argv);
388 /* NB: Mustn't free the strings which are on the stack. */
394 /* Same as 'command', but we allow the status code from the
395 * subcommand to be non-zero, and return that status code.
396 * We still return -1 if there was some other error.
399 commandr (char **stdoutput, char **stderror, const char *name, ...)
406 /* Collect the command line arguments into an array. */
408 argv = malloc (sizeof (char *) * i);
413 argv[0] = (char *) name;
416 va_start (args, name);
418 while ((s = va_arg (args, char *)) != NULL) {
419 p = realloc (argv, sizeof (char *) * (++i));
433 r = commandrv (stdoutput, stderror, argv);
435 /* NB: Mustn't free the strings which are on the stack. */
441 /* Same as 'command', but passing an argv. */
443 commandv (char **stdoutput, char **stderror, char * const* const argv)
447 r = commandrv (stdoutput, stderror, argv);
455 commandrv (char **stdoutput, char **stderror, char * const* const argv)
457 int so_size = 0, se_size = 0;
458 int so_fd[2], se_fd[2];
465 if (stdoutput) *stdoutput = NULL;
466 if (stderror) *stderror = NULL;
469 printf ("%s", argv[0]);
470 for (i = 1; argv[i] != NULL; ++i)
471 printf (" %s", argv[i]);
475 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
490 if (pid == 0) { /* Child process. */
499 execvp (argv[0], argv);
504 /* Parent process. */
509 FD_SET (so_fd[0], &rset);
510 FD_SET (se_fd[0], &rset);
515 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
519 if (stdoutput) free (*stdoutput);
520 if (stderror) free (*stderror);
523 waitpid (pid, NULL, 0);
527 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
528 r = read (so_fd[0], buf, sizeof buf);
533 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
535 if (r > 0 && stdoutput) {
537 p = realloc (*stdoutput, so_size);
543 memcpy (*stdoutput + so_size - r, buf, r);
547 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
548 r = read (se_fd[0], buf, sizeof buf);
553 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
555 if (r > 0 && stderror) {
557 p = realloc (*stderror, se_size);
563 memcpy (*stderror + se_size - r, buf, r);
571 /* Make sure the output buffers are \0-terminated. Also remove any
572 * trailing \n characters from the error buffer (not from stdout).
575 *stdoutput = realloc (*stdoutput, so_size+1);
576 if (*stdoutput == NULL) {
580 (*stdoutput)[so_size] = '\0';
583 *stderror = realloc (*stderror, se_size+1);
584 if (*stderror == NULL) {
588 (*stderror)[se_size] = '\0';
590 while (se_size >= 0 && (*stderror)[se_size] == '\n')
591 (*stderror)[se_size--] = '\0';
595 /* Get the exit status of the command. */
596 if (waitpid (pid, &r, 0) != pid) {
602 return WEXITSTATUS (r);
607 /* Split an output string into a NULL-terminated list of lines.
608 * Typically this is used where we have run an external command
609 * which has printed out a list of things, and we want to return
612 * The corner cases here are quite tricky. Note in particular:
616 * "a\nb" -> ["a"; "b"]
617 * "a\nb\n" -> ["a"; "b"]
618 * "a\nb\n\n" -> ["a"; "b"; ""]
620 * The original string is written over and destroyed by this
621 * function (which is usually OK because it's the 'out' string
622 * from command()). You can free the original string, because
623 * add_string() strdups the strings.
626 split_lines (char *str)
629 int size = 0, alloc = 0;
632 if (strcmp (str, "") == 0)
637 /* Empty last line? */
641 pend = strchr (p, '\n');
647 if (add_string (&lines, &size, &alloc, p) == -1) {
655 if (add_string (&lines, &size, &alloc, NULL) == -1)
661 /* Quote 'in' for the shell, and write max len-1 bytes to out. The
662 * result will be NUL-terminated, even if it is truncated.
664 * Returns number of bytes needed, so if result >= len then the buffer
665 * should have been longer.
667 * XXX This doesn't quote \n correctly (but is still safe).
670 shell_quote (char *out, int len, const char *in)
672 #define SAFE(c) (isalnum((c)) || \
673 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
675 int outlen = strlen (in);
677 /* Calculate how much output space this really needs. */
678 for (i = 0; in[i]; ++i)
679 if (!SAFE (in[i])) outlen++;
681 /* Now copy the string, but only up to len-1 bytes. */
682 for (i = 0, j = 0; in[i]; ++i) {
683 int is_safe = SAFE (in[i]);
685 /* Enough space left to write this character? */
686 if (j >= len-1 || (!is_safe && j >= len-2))
689 if (!is_safe) out[j++] = '\\';
698 /* Perform device name translation. Don't call this directly -
699 * use the IS_DEVICE macro.
701 * See guestfs(3) for the algorithm.
703 * We have to open the device and test for ENXIO, because
704 * the device nodes themselves will exist in the appliance.
707 device_name_translation (char *device, const char *func)
711 fd = open (device, O_RDONLY);
717 if (errno != ENXIO) {
719 reply_with_perror ("%s: %s", func, device);
723 /* If the name begins with "/dev/sd" then try the alternatives. */
724 if (strncmp (device, "/dev/sd", 7) != 0)
727 device[5] = 'h'; /* /dev/hd (old IDE driver) */
728 fd = open (device, O_RDONLY);
734 device[5] = 'v'; /* /dev/vd (for virtio devices) */
735 fd = open (device, O_RDONLY);
741 device[5] = 's'; /* Restore original device name. */