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"
50 /* Location to mount root device. */
51 const char *sysroot = "/sysroot"; /* No trailing slash. */
55 main (int argc, char *argv[])
57 static const char *options = "fh:p:?";
58 static struct option long_options[] = {
59 { "foreground", 0, 0, 'f' },
60 { "help", 0, 0, '?' },
61 { "host", 1, 0, 'h' },
62 { "port", 1, 0, 'p' },
67 const char *host = NULL;
68 const char *port = NULL;
73 struct addrinfo *res, *rr;
74 struct addrinfo hints;
80 c = getopt_long (argc, argv, options, long_options, NULL);
101 fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
111 /* If host and port aren't set yet, try /proc/cmdline. */
112 if (!host || !port) {
113 fp = fopen ("/proc/cmdline", "r");
115 perror ("/proc/cmdline");
118 n = fread (buf, 1, sizeof buf - 1, fp);
122 /* Set the verbose flag. Not quite right because this will only
123 * set the flag if host and port aren't set on the command line.
124 * Don't worry about this for now. (XXX)
126 verbose = strstr (buf, "guestfs_verbose=1") != NULL;
128 printf ("verbose daemon enabled\n");
130 p = strstr (buf, "guestfs=");
134 p2 = strchr (p, ':');
138 r = strcspn (p2, " \n");
146 /* Can't parse /proc/cmdline, so use built-in defaults. */
147 if (!host || !port) {
148 host = VMCHANNEL_ADDR;
149 port = VMCHANNEL_PORT;
152 /* Make sure SIGPIPE doesn't kill us. */
153 memset (&sa, 0, sizeof sa);
154 sa.sa_handler = SIG_IGN;
156 if (sigaction (SIGPIPE, &sa, NULL) == -1)
157 perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
159 /* Set up a basic environment. After we are called by /init the
160 * environment is essentially empty.
161 * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
163 setenv ("PATH", "/usr/bin:/bin", 1);
164 setenv ("SHELL", "/bin/sh", 1);
165 setenv ("LANG", "C", 1);
167 /* We document that umask defaults to 022 (it should be this anyway). */
170 /* Resolve the hostname. */
171 memset (&hints, 0, sizeof hints);
172 hints.ai_socktype = SOCK_STREAM;
173 hints.ai_flags = AI_ADDRCONFIG;
174 r = getaddrinfo (host, port, &hints, &res);
176 fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
180 /* Connect to the given TCP socket. */
182 for (rr = res; rr != NULL; rr = rr->ai_next) {
183 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
185 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
196 fprintf (stderr, "connection to %s:%s failed\n", host, port);
200 /* Send the magic length message which indicates that
201 * userspace is up inside the guest.
203 len = GUESTFS_LAUNCH_FLAG;
204 xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
205 if (!xdr_uint32_t (&xdr, &len)) {
206 fprintf (stderr, "xdr_uint32_t failed\n");
210 (void) xwrite (sock, buf, xdr_getpos (&xdr));
214 /* Fork into the background. */
216 if (daemon (0, 1) == -1) {
222 /* Enter the main loop, reading and performing actions. */
228 /* Turn "/path" into "/sysroot/path".
230 * Caller must check for NULL and call reply_with_perror ("malloc")
231 * if it is. Caller must also free the string.
234 sysroot_path (const char *path)
237 int len = strlen (path) + sysroot_len + 1;
243 snprintf (r, len, "%s%s", sysroot, path);
248 xwrite (int sock, const void *buf, size_t len)
253 r = write (sock, buf, len);
266 xread (int sock, void *buf, size_t len)
271 r = read (sock, buf, len);
277 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
290 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
294 add_string (char ***argv, int *size, int *alloc, const char *str)
299 if (*size >= *alloc) {
301 new_argv = realloc (*argv, *alloc * sizeof (char *));
302 if (new_argv == NULL) {
303 reply_with_perror ("realloc");
304 free_strings (*argv);
311 new_str = strdup (str);
312 if (new_str == NULL) {
313 reply_with_perror ("strdup");
314 free_strings (*argv);
319 (*argv)[*size] = new_str;
326 count_strings (char * const* const argv)
330 for (argc = 0; argv[argc] != NULL; ++argc)
336 compare (const void *vp1, const void *vp2)
338 char * const *p1 = (char * const *) vp1;
339 char * const *p2 = (char * const *) vp2;
340 return strcmp (*p1, *p2);
344 sort_strings (char **argv, int len)
346 qsort (argv, len, sizeof (char *), compare);
350 free_strings (char **argv)
354 for (argc = 0; argv[argc] != NULL; ++argc)
360 free_stringslen (char **argv, int len)
364 for (i = 0; i < len; ++i)
369 /* This is a more sane version of 'system(3)' for running external
370 * commands. It uses fork/execvp, so we don't need to worry about
371 * quoting of parameters, and it allows us to capture any error
372 * messages in a buffer.
375 command (char **stdoutput, char **stderror, const char *name, ...)
382 /* Collect the command line arguments into an array. */
384 argv = malloc (sizeof (char *) * i);
389 argv[0] = (char *) name;
392 va_start (args, name);
394 while ((s = va_arg (args, char *)) != NULL) {
395 p = realloc (argv, sizeof (char *) * (++i));
409 r = commandv (stdoutput, stderror, argv);
411 /* NB: Mustn't free the strings which are on the stack. */
417 /* Same as 'command', but we allow the status code from the
418 * subcommand to be non-zero, and return that status code.
419 * We still return -1 if there was some other error.
422 commandr (char **stdoutput, char **stderror, const char *name, ...)
429 /* Collect the command line arguments into an array. */
431 argv = malloc (sizeof (char *) * i);
436 argv[0] = (char *) name;
439 va_start (args, name);
441 while ((s = va_arg (args, char *)) != NULL) {
442 p = realloc (argv, sizeof (char *) * (++i));
456 r = commandrv (stdoutput, stderror, argv);
458 /* NB: Mustn't free the strings which are on the stack. */
464 /* Same as 'command', but passing an argv. */
466 commandv (char **stdoutput, char **stderror, char * const* const argv)
470 r = commandrv (stdoutput, stderror, argv);
478 commandrv (char **stdoutput, char **stderror, char * const* const argv)
480 int so_size = 0, se_size = 0;
481 int so_fd[2], se_fd[2];
488 if (stdoutput) *stdoutput = NULL;
489 if (stderror) *stderror = NULL;
492 printf ("%s", argv[0]);
493 for (i = 1; argv[i] != NULL; ++i)
494 printf (" %s", argv[i]);
498 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
513 if (pid == 0) { /* Child process. */
522 execvp (argv[0], argv);
527 /* Parent process. */
532 FD_SET (so_fd[0], &rset);
533 FD_SET (se_fd[0], &rset);
538 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
542 if (stdoutput) free (*stdoutput);
543 if (stderror) free (*stderror);
546 waitpid (pid, NULL, 0);
550 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
551 r = read (so_fd[0], buf, sizeof buf);
556 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
558 if (r > 0 && stdoutput) {
560 p = realloc (*stdoutput, so_size);
566 memcpy (*stdoutput + so_size - r, buf, r);
570 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
571 r = read (se_fd[0], buf, sizeof buf);
576 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
578 if (r > 0 && stderror) {
580 p = realloc (*stderror, se_size);
586 memcpy (*stderror + se_size - r, buf, r);
594 /* Make sure the output buffers are \0-terminated. Also remove any
595 * trailing \n characters from the error buffer (not from stdout).
598 void *q = realloc (*stdoutput, so_size+1);
605 (*stdoutput)[so_size] = '\0';
608 void *q = realloc (*stderror, se_size+1);
615 (*stderror)[se_size] = '\0';
617 while (se_size >= 0 && (*stderror)[se_size] == '\n')
618 (*stderror)[se_size--] = '\0';
622 /* Get the exit status of the command. */
623 if (waitpid (pid, &r, 0) != pid) {
629 return WEXITSTATUS (r);
634 /* Split an output string into a NULL-terminated list of lines.
635 * Typically this is used where we have run an external command
636 * which has printed out a list of things, and we want to return
639 * The corner cases here are quite tricky. Note in particular:
643 * "a\nb" -> ["a"; "b"]
644 * "a\nb\n" -> ["a"; "b"]
645 * "a\nb\n\n" -> ["a"; "b"; ""]
647 * The original string is written over and destroyed by this
648 * function (which is usually OK because it's the 'out' string
649 * from command()). You can free the original string, because
650 * add_string() strdups the strings.
653 split_lines (char *str)
656 int size = 0, alloc = 0;
659 if (strcmp (str, "") == 0)
664 /* Empty last line? */
668 pend = strchr (p, '\n');
674 if (add_string (&lines, &size, &alloc, p) == -1) {
682 if (add_string (&lines, &size, &alloc, NULL) == -1)
688 /* Quote 'in' for the shell, and write max len-1 bytes to out. The
689 * result will be NUL-terminated, even if it is truncated.
691 * Returns number of bytes needed, so if result >= len then the buffer
692 * should have been longer.
694 * XXX This doesn't quote \n correctly (but is still safe).
697 shell_quote (char *out, int len, const char *in)
699 #define SAFE(c) (isalnum((c)) || \
700 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
702 int outlen = strlen (in);
704 /* Calculate how much output space this really needs. */
705 for (i = 0; in[i]; ++i)
706 if (!SAFE (in[i])) outlen++;
708 /* Now copy the string, but only up to len-1 bytes. */
709 for (i = 0, j = 0; in[i]; ++i) {
710 int is_safe = SAFE (in[i]);
712 /* Enough space left to write this character? */
713 if (j >= len-1 || (!is_safe && j >= len-2))
716 if (!is_safe) out[j++] = '\\';
725 /* Perform device name translation. Don't call this directly -
726 * use the IS_DEVICE macro.
728 * See guestfs(3) for the algorithm.
730 * We have to open the device and test for ENXIO, because
731 * the device nodes themselves will exist in the appliance.
734 device_name_translation (char *device, const char *func)
738 fd = open (device, O_RDONLY);
744 if (errno != ENXIO && errno != ENOENT) {
746 reply_with_perror ("%s: %s", func, device);
750 /* If the name begins with "/dev/sd" then try the alternatives. */
751 if (strncmp (device, "/dev/sd", 7) != 0)
754 device[5] = 'h'; /* /dev/hd (old IDE driver) */
755 fd = open (device, O_RDONLY);
761 device[5] = 'v'; /* /dev/vd (for virtio devices) */
762 fd = open (device, O_RDONLY);
768 device[5] = 's'; /* Restore original device name. */
772 /* LVM and other commands aren't synchronous, especially when udev is
773 * involved. eg. You can create or remove some device, but the /dev
774 * device node won't appear until some time later. This means that
775 * you get an error if you run one command followed by another.
776 * Use 'udevadm settle' after certain commands, but don't be too
777 * fussed if it fails.
782 command (NULL, NULL, "/sbin/udevadm", "settle", NULL);