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 /* Resolve the hostname. */
154 memset (&hints, 0, sizeof hints);
155 hints.ai_socktype = SOCK_STREAM;
156 hints.ai_flags = AI_ADDRCONFIG;
157 r = getaddrinfo (host, port, &hints, &res);
159 fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
163 /* Connect to the given TCP socket. */
165 for (rr = res; rr != NULL; rr = rr->ai_next) {
166 sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
168 if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
179 fprintf (stderr, "connection to %s:%s failed\n", host, port);
183 /* Send the magic length message which indicates that
184 * userspace is up inside the guest.
186 len = GUESTFS_LAUNCH_FLAG;
187 xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
188 if (!xdr_uint32_t (&xdr, &len)) {
189 fprintf (stderr, "xdr_uint32_t failed\n");
193 (void) xwrite (sock, buf, xdr_getpos (&xdr));
197 /* Fork into the background. */
199 if (daemon (0, 1) == -1) {
205 /* Enter the main loop, reading and performing actions. */
212 xwrite (int sock, const void *buf, size_t len)
217 r = write (sock, buf, len);
230 xread (int sock, void *buf, size_t len)
235 r = read (sock, buf, len);
241 fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
254 fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
258 add_string (char ***argv, int *size, int *alloc, const char *str)
263 if (*size >= *alloc) {
265 new_argv = realloc (*argv, *alloc * sizeof (char *));
266 if (new_argv == NULL) {
267 reply_with_perror ("realloc");
268 free_strings (*argv);
275 new_str = strdup (str);
276 if (new_str == NULL) {
277 reply_with_perror ("strdup");
278 free_strings (*argv);
283 (*argv)[*size] = new_str;
290 count_strings (char * const* const argv)
294 for (argc = 0; argv[argc] != NULL; ++argc)
300 compare (const void *vp1, const void *vp2)
302 char * const *p1 = (char * const *) vp1;
303 char * const *p2 = (char * const *) vp2;
304 return strcmp (*p1, *p2);
308 sort_strings (char **argv, int len)
310 qsort (argv, len, sizeof (char *), compare);
314 free_strings (char **argv)
318 for (argc = 0; argv[argc] != NULL; ++argc)
324 free_stringslen (char **argv, int len)
328 for (i = 0; i < len; ++i)
333 /* This is a more sane version of 'system(3)' for running external
334 * commands. It uses fork/execvp, so we don't need to worry about
335 * quoting of parameters, and it allows us to capture any error
336 * messages in a buffer.
339 command (char **stdoutput, char **stderror, const char *name, ...)
346 /* Collect the command line arguments into an array. */
348 argv = malloc (sizeof (char *) * i);
353 argv[0] = (char *) name;
356 va_start (args, name);
358 while ((s = va_arg (args, char *)) != NULL) {
359 p = realloc (argv, sizeof (char *) * (++i));
373 r = commandv (stdoutput, stderror, argv);
375 /* NB: Mustn't free the strings which are on the stack. */
381 /* Same as 'command', but we allow the status code from the
382 * subcommand to be non-zero, and return that status code.
383 * We still return -1 if there was some other error.
386 commandr (char **stdoutput, char **stderror, const char *name, ...)
393 /* Collect the command line arguments into an array. */
395 argv = malloc (sizeof (char *) * i);
400 argv[0] = (char *) name;
403 va_start (args, name);
405 while ((s = va_arg (args, char *)) != NULL) {
406 p = realloc (argv, sizeof (char *) * (++i));
420 r = commandrv (stdoutput, stderror, argv);
422 /* NB: Mustn't free the strings which are on the stack. */
428 /* Same as 'command', but passing an argv. */
430 commandv (char **stdoutput, char **stderror, char * const* const argv)
434 r = commandrv (stdoutput, stderror, argv);
442 commandrv (char **stdoutput, char **stderror, char * const* const argv)
444 int so_size = 0, se_size = 0;
445 int so_fd[2], se_fd[2];
451 if (stdoutput) *stdoutput = NULL;
452 if (stderror) *stderror = NULL;
455 printf ("%s", argv[0]);
456 for (i = 1; argv[i] != NULL; ++i)
457 printf (" %s", argv[i]);
461 if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
476 if (pid == 0) { /* Child process. */
485 execvp (argv[0], argv);
490 /* Parent process. */
495 FD_SET (so_fd[0], &rset);
496 FD_SET (se_fd[0], &rset);
501 r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
505 if (stdoutput) free (*stdoutput);
506 if (stderror) free (*stderror);
509 waitpid (pid, NULL, 0);
513 if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
514 r = read (so_fd[0], buf, sizeof buf);
519 if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
521 if (r > 0 && stdoutput) {
523 p = realloc (*stdoutput, so_size);
529 memcpy (*stdoutput + so_size - r, buf, r);
533 if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
534 r = read (se_fd[0], buf, sizeof buf);
539 if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
541 if (r > 0 && stderror) {
543 p = realloc (*stderror, se_size);
549 memcpy (*stderror + se_size - r, buf, r);
557 /* Make sure the output buffers are \0-terminated. Also remove any
558 * trailing \n characters from the error buffer (not from stdout).
561 *stdoutput = realloc (*stdoutput, so_size+1);
562 if (*stdoutput == NULL) {
566 (*stdoutput)[so_size] = '\0';
569 *stderror = realloc (*stderror, se_size+1);
570 if (*stderror == NULL) {
574 (*stderror)[se_size] = '\0';
576 while (se_size >= 0 && (*stderror)[se_size] == '\n')
577 (*stderror)[se_size--] = '\0';
581 /* Get the exit status of the command. */
582 waitpid (pid, &r, 0);
585 return WEXITSTATUS (r);
590 /* Split an output string into a NULL-terminated list of lines.
591 * Typically this is used where we have run an external command
592 * which has printed out a list of things, and we want to return
595 * The corner cases here are quite tricky. Note in particular:
599 * "a\nb" -> ["a"; "b"]
600 * "a\nb\n" -> ["a"; "b"]
601 * "a\nb\n\n" -> ["a"; "b"; ""]
603 * The original string is written over and destroyed by this
604 * function (which is usually OK because it's the 'out' string
605 * from command()). You can free the original string, because
606 * add_string() strdups the strings.
609 split_lines (char *str)
612 int size = 0, alloc = 0;
615 if (strcmp (str, "") == 0)
620 /* Empty last line? */
624 pend = strchr (p, '\n');
630 if (add_string (&lines, &size, &alloc, p) == -1) {
638 if (add_string (&lines, &size, &alloc, NULL) == -1)
644 /* Quote 'in' for the shell, and write max len-1 bytes to out. The
645 * result will be NUL-terminated, even if it is truncated.
647 * Returns number of bytes needed, so if result >= len then the buffer
648 * should have been longer.
650 * XXX This doesn't quote \n correctly (but is still safe).
653 shell_quote (char *out, int len, const char *in)
655 #define SAFE(c) (isalnum((c)) || \
656 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
658 int outlen = strlen (in);
660 /* Calculate how much output space this really needs. */
661 for (i = 0; in[i]; ++i)
662 if (!SAFE (in[i])) outlen++;
664 /* Now copy the string, but only up to len-1 bytes. */
665 for (i = 0, j = 0; in[i]; ++i) {
666 int is_safe = SAFE (in[i]);
668 /* Enough space left to write this character? */
669 if (j >= len-1 || (!is_safe && j >= len-2))
672 if (!is_safe) out[j++] = '\\';