1 /* guestfish - the filesystem interactive shell
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 _GNU_SOURCE // for strchrnul
32 #include <sys/types.h>
35 #ifdef HAVE_LIBREADLINE
36 #include <readline/readline.h>
37 #include <readline/history.h>
56 static void add_drives (struct drv *drv);
57 static void mount_mps (struct mp *mp);
58 static void interactive (void);
59 static void shell_script (void);
60 static void script (int prompt);
61 static void cmdline (char *argv[], int optind, int argc);
62 static void initialize_readline (void);
63 static void cleanup_readline (void);
64 static void add_history_line (const char *);
66 /* Currently open libguestfs handle. */
72 int echo_commands = 0;
73 int remote_control_listen = 0;
74 int remote_control = 0;
75 int exit_on_error = 1;
78 launch (guestfs_h *_g)
82 if (guestfs_is_config (g)) {
83 if (guestfs_launch (g) == -1)
85 if (guestfs_wait_ready (g) == -1)
91 static void __attribute__((noreturn))
94 if (status != EXIT_SUCCESS)
95 fprintf (stderr, _("Try `%s --help' for more information.\n"),
99 _("%s: guest filesystem shell\n"
100 "%s lets you edit virtual machine filesystems\n"
101 "Copyright (C) 2009 Red Hat Inc.\n"
103 " %s [--options] cmd [: cmd : cmd ...]\n"
104 " %s -i libvirt-domain\n"
105 " %s -i disk-image(s)\n"
106 "or for interactive use:\n"
108 "or from a shell script:\n"
114 " -h|--cmd-help List available commands\n"
115 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
116 " -a|--add image Add image\n"
117 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
118 " -f|--file file Read commands from file\n"
119 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
120 " --listen Listen for remote commands\n"
121 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
122 " -n|--no-sync Don't autosync\n"
123 " --remote[=pid] Send commands to remote %s\n"
124 " -r|--ro Mount read-only\n"
125 " --selinux Enable SELinux support\n"
126 " -v|--verbose Verbose messages\n"
127 " -x Echo each command before executing it\n"
128 " -V|--version Display version and exit\n"
129 "For more information, see the manpage %s(1).\n"),
130 program_name, program_name, program_name,
131 program_name, program_name, program_name,
132 program_name, program_name, program_name);
138 main (int argc, char *argv[])
140 /* Set global program name that is not polluted with libtool artifacts. */
141 set_program_name (argv[0]);
143 enum { HELP_OPTION = CHAR_MAX + 1 };
145 static const char *options = "a:Df:h::im:nrv?Vx";
146 static const struct option long_options[] = {
147 { "add", 1, 0, 'a' },
148 { "cmd-help", 2, 0, 'h' },
149 { "file", 1, 0, 'f' },
150 { "help", 0, 0, HELP_OPTION },
151 { "inspector", 0, 0, 'i' },
152 { "listen", 0, 0, 0 },
153 { "mount", 1, 0, 'm' },
154 { "no-dest-paths", 0, 0, 'D' },
155 { "no-sync", 0, 0, 'n' },
156 { "remote", 2, 0, 0 },
158 { "selinux", 0, 0, 0 },
159 { "verbose", 0, 0, 'v' },
160 { "version", 0, 0, 'V' },
163 struct drv *drvs = NULL;
165 struct mp *mps = NULL;
167 char *p, *file = NULL;
173 initialize_readline ();
175 memset (&sa, 0, sizeof sa);
176 sa.sa_handler = SIG_IGN;
177 sa.sa_flags = SA_RESTART;
178 sigaction (SIGPIPE, &sa, NULL);
180 /* guestfs_create is meant to be a lightweight operation, so
181 * it's OK to do it early here.
183 g = guestfs_create ();
185 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
189 guestfs_set_autosync (g, 1);
191 /* If developing, add ./appliance to the path. Note that libtools
192 * interferes with this because uninstalled guestfish is a shell
193 * script that runs the real program with an absolute path. Detect
196 * BUT if LIBGUESTFS_PATH environment variable is already set by
197 * the user, then don't override it.
199 if (getenv ("LIBGUESTFS_PATH") == NULL &&
201 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
202 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
204 /* CAUTION: we are careful to modify argv[0] here, only after
205 * using it just above.
207 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
208 * of the original, in case it's needed in virt-inspector mode, below.
210 char *real_argv0 = argv[0];
211 argv[0] = bad_cast (program_name);
214 c = getopt_long (argc, argv, options, long_options, &option_index);
218 case 0: /* options which are long only */
219 if (strcmp (long_options[option_index].name, "listen") == 0)
220 remote_control_listen = 1;
221 else if (strcmp (long_options[option_index].name, "remote") == 0) {
223 if (sscanf (optarg, "%d", &remote_control) != 1) {
224 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
225 program_name, optarg);
229 p = getenv ("GUESTFISH_PID");
230 if (!p || sscanf (p, "%d", &remote_control) != 1) {
231 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
232 " to the PID of the remote process\n"),
237 } else if (strcmp (long_options[option_index].name, "selinux") == 0) {
238 guestfs_set_selinux (g, 1);
240 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
241 program_name, long_options[option_index].name, option_index);
247 if (access (optarg, R_OK) != 0) {
251 drv = malloc (sizeof (struct drv));
256 drv->filename = optarg;
262 complete_dest_paths = 0;
267 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
276 display_command (optarg);
277 else if (argv[optind] && argv[optind][0] != '-')
278 display_command (argv[optind++]);
288 mp = malloc (sizeof (struct mp));
293 p = strchr (optarg, ':');
296 mp->mountpoint = p+1;
298 mp->mountpoint = bad_cast ("/");
305 guestfs_set_autosync (g, 0);
314 guestfs_set_verbose (g, verbose);
318 printf ("%s %s\n", program_name, PACKAGE_VERSION);
333 /* Inspector mode invalidates most of the other arguments. */
338 if (drvs || mps || remote_control_listen || remote_control ||
339 guestfs_get_selinux (g)) {
340 fprintf (stderr, _("%s: cannot use -i option with -a, -m,"
341 " --listen, --remote or --selinux\n"),
345 if (optind >= argc) {
347 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
352 strcpy (cmd, "a=`virt-inspector");
353 while (optind < argc) {
354 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
357 _("%s: virt-inspector command too long for fixed-size buffer\n"),
362 strcat (cmd, argv[optind]);
368 strcat (cmd, " --ro-fish");
370 strcat (cmd, " --fish");
372 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
374 if (guestfs_get_verbose (g))
376 if (!guestfs_get_autosync (g))
381 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
388 exit (WEXITSTATUS (r));
391 /* If we've got drives to add, add them now. */
394 /* If we've got mountpoints, we must launch the guest and mount them. */
396 if (launch (g) == -1) exit (1);
400 /* Remote control? */
401 if (remote_control_listen && remote_control) {
403 _("%s: cannot use --listen and --remote options at the same time\n"),
408 if (remote_control_listen) {
411 _("%s: extra parameters on the command line with --listen flag\n"),
417 _("%s: cannot use --listen and --file options at the same time\n"),
424 /* -f (file) parameter? */
427 if (open (file, O_RDONLY) == -1) {
433 /* Interactive, shell script, or command(s) on the command line? */
434 if (optind >= argc) {
441 cmdline (argv, optind, argc);
449 pod2text (const char *name, const char *shortdesc, const char *str)
453 fp = popen ("pod2text", "w");
455 /* pod2text failed, maybe not found, so let's just print the
456 * source instead, since that's better than doing nothing.
458 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
461 fprintf (fp, "=head1 %s - %s\n\n", name, shortdesc);
466 /* List is built in reverse order, so mount them in reverse order. */
468 mount_mps (struct mp *mp)
473 mount_mps (mp->next);
475 r = guestfs_mount (g, mp->device, mp->mountpoint);
477 r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
484 add_drives (struct drv *drv)
489 add_drives (drv->next);
491 r = guestfs_add_drive (g, drv->filename);
493 r = guestfs_add_drive_ro (g, drv->filename);
511 #define FISH "><fs> "
513 static char *line_read = NULL;
518 #ifdef HAVE_LIBREADLINE
526 line_read = readline (prompt ? FISH : "");
528 if (line_read && *line_read)
529 add_history_line (line_read);
534 #endif /* HAVE_LIBREADLINE */
536 static char buf[8192];
539 if (prompt) printf (FISH);
540 line_read = fgets (buf, sizeof buf, stdin);
543 len = strlen (line_read);
544 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
558 int global_exit_on_error = !prompt;
563 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
564 "editing virtual machine filesystems.\n"
566 "Type: 'help' for help with commands\n"
567 " 'quit' to quit the shell\n"
573 exit_on_error = global_exit_on_error;
575 buf = rl_gets (prompt);
581 /* Skip any initial whitespace before the command. */
583 while (*buf && isspace (*buf))
588 /* If the next character is '#' then this is a comment. */
589 if (*buf == '#') continue;
591 /* If the next character is '!' then pass the whole lot to system(3). */
599 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
600 WEXITSTATUS (r) != 0)
606 /* If the next character is '-' allow the command to fail without
607 * exiting on error (just for this one command though).
615 /* Get the command (cannot be quoted). */
616 len = strcspn (buf, " \t");
618 if (len == 0) continue;
622 if (buf[len] == '\0') {
629 p += strspn (p, " \t");
631 /* Get the parameters. */
632 while (*p && i < sizeof argv / sizeof argv[0]) {
635 /* Parameters which start with quotes or pipes are treated
636 * specially. Bare parameters are delimited by whitespace.
640 len = strcspn (p, "\"");
641 if (p[len] == '\0') {
642 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
643 if (exit_on_error) exit (1);
646 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
648 _("%s: command arguments not separated by whitespace\n"),
650 if (exit_on_error) exit (1);
654 pend = p[len+1] ? &p[len+2] : &p[len+1];
655 } else if (*p == '\'') {
657 len = strcspn (p, "'");
658 if (p[len] == '\0') {
659 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
660 if (exit_on_error) exit (1);
663 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
665 _("%s: command arguments not separated by whitespace\n"),
667 if (exit_on_error) exit (1);
671 pend = p[len+1] ? &p[len+2] : &p[len+1];
672 } else if (*p == '|') {
677 } else if (*p == '[') {
681 while (*pend && c != 0) {
682 if (*pend == '[') c++;
683 else if (*pend == ']') c--;
688 _("%s: unterminated \"[...]\" sequence\n"), program_name);
689 if (exit_on_error) exit (1);
692 if (*pend && (*pend != ' ' && *pend != '\t')) {
694 _("%s: command arguments not separated by whitespace\n"),
696 if (exit_on_error) exit (1);
701 } else if (*p != ' ' && *p != '\t') {
702 /* If the first character is a ~ then note that this parameter
703 * is a candidate for ~username expansion. NB this does not
704 * apply to quoted parameters.
706 tilde_candidate = *p == '~';
707 len = strcspn (p, " \t");
714 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
719 if (!tilde_candidate)
722 argv[i] = try_tilde_expansion (p);
727 p += strspn (p, " \t");
730 if (i == sizeof argv / sizeof argv[0]) {
731 fprintf (stderr, _("%s: too many arguments\n"), program_name);
732 if (exit_on_error) exit (1);
739 if (issue_command (cmd, argv, pipe) == -1) {
740 if (exit_on_error) exit (1);
745 if (prompt) printf ("\n");
749 cmdline (char *argv[], int optind, int argc)
756 if (optind >= argc) return;
758 cmd = argv[optind++];
759 if (strcmp (cmd, ":") == 0) {
760 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
763 params = &argv[optind];
765 /* Search for end of command list or ":" ... */
766 while (optind < argc && strcmp (argv[optind], ":") != 0)
769 if (optind == argc) {
770 if (issue_command (cmd, params, NULL) == -1) exit (1);
773 if (issue_command (cmd, params, NULL) == -1) exit (1);
774 cmdline (argv, optind+1, argc);
779 issue_command (const char *cmd, char *argv[], const char *pipecmd)
782 int stdout_saved_fd = -1;
788 for (i = 0; argv[i] != NULL; ++i)
789 printf (" %s", argv[i]);
793 /* For | ... commands. Annoyingly we can't use popen(3) here. */
797 if (fflush (stdout) == EOF) {
798 perror ("failed to flush standard output");
802 perror ("pipe failed");
811 if (pid == 0) { /* Child process. */
813 if (dup2 (fd[0], 0) < 0) {
814 perror ("dup2 of stdin failed");
818 r = system (pipecmd);
823 _exit (WEXITSTATUS (r));
826 if ((stdout_saved_fd = dup (1)) < 0) {
827 perror ("failed to dup stdout");
831 if (dup2 (fd[1], 1) < 0) {
832 perror ("failed to dup stdout");
833 close (stdout_saved_fd);
839 for (argc = 0; argv[argc] != NULL; ++argc)
842 /* If --remote was set, then send this command to a remote process. */
844 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
846 /* Otherwise execute it locally. */
847 else if (strcasecmp (cmd, "help") == 0) {
851 display_command (argv[0]);
854 else if (strcasecmp (cmd, "quit") == 0 ||
855 strcasecmp (cmd, "exit") == 0 ||
856 strcasecmp (cmd, "q") == 0) {
860 else if (strcasecmp (cmd, "alloc") == 0 ||
861 strcasecmp (cmd, "allocate") == 0)
862 r = do_alloc (cmd, argc, argv);
863 else if (strcasecmp (cmd, "echo") == 0)
864 r = do_echo (cmd, argc, argv);
865 else if (strcasecmp (cmd, "edit") == 0 ||
866 strcasecmp (cmd, "vi") == 0 ||
867 strcasecmp (cmd, "emacs") == 0)
868 r = do_edit (cmd, argc, argv);
869 else if (strcasecmp (cmd, "lcd") == 0)
870 r = do_lcd (cmd, argc, argv);
871 else if (strcasecmp (cmd, "glob") == 0)
872 r = do_glob (cmd, argc, argv);
873 else if (strcasecmp (cmd, "more") == 0 ||
874 strcasecmp (cmd, "less") == 0)
875 r = do_more (cmd, argc, argv);
876 else if (strcasecmp (cmd, "reopen") == 0)
877 r = do_reopen (cmd, argc, argv);
878 else if (strcasecmp (cmd, "time") == 0)
879 r = do_time (cmd, argc, argv);
881 r = run_action (cmd, argc, argv);
883 /* Always flush stdout after every command, so that messages, results
884 * etc appear immediately.
886 if (fflush (stdout) == EOF) {
887 perror ("failed to flush standard output");
893 if (dup2 (stdout_saved_fd, 1) < 0) {
894 perror ("failed to dup2 standard output");
897 close (stdout_saved_fd);
898 if (waitpid (pid, NULL, 0) < 0) {
899 perror ("waiting for command to complete");
908 list_builtin_commands (void)
910 /* help and quit should appear at the top */
911 printf ("%-20s %s\n",
912 "help", _("display a list of commands or help on a command"));
913 printf ("%-20s %s\n",
914 "quit", _("quit guestfish"));
916 printf ("%-20s %s\n",
917 "alloc", _("allocate an image"));
918 printf ("%-20s %s\n",
919 "echo", _("display a line of text"));
920 printf ("%-20s %s\n",
921 "edit", _("edit a file in the image"));
922 printf ("%-20s %s\n",
923 "lcd", _("local change directory"));
924 printf ("%-20s %s\n",
925 "glob", _("expand wildcards in command"));
926 printf ("%-20s %s\n",
927 "more", _("view a file in the pager"));
928 printf ("%-20s %s\n",
929 "reopen", _("close and reopen libguestfs handle"));
930 printf ("%-20s %s\n",
931 "time", _("measure time taken to run command"));
933 /* actions are printed after this (see list_commands) */
937 display_builtin_command (const char *cmd)
939 /* help for actions is auto-generated, see display_command */
941 if (strcasecmp (cmd, "alloc") == 0 ||
942 strcasecmp (cmd, "allocate") == 0)
943 printf (_("alloc - allocate an image\n"
944 " alloc <filename> <size>\n"
946 " This creates an empty (zeroed) file of the given size,\n"
947 " and then adds so it can be further examined.\n"
949 " For more advanced image creation, see qemu-img utility.\n"
951 " Size can be specified (where <nn> means a number):\n"
952 " <nn> number of kilobytes\n"
953 " eg: 1440 standard 3.5\" floppy\n"
954 " <nn>K or <nn>KB number of kilobytes\n"
955 " <nn>M or <nn>MB number of megabytes\n"
956 " <nn>G or <nn>GB number of gigabytes\n"
957 " <nn>sects number of 512 byte sectors\n"));
958 else if (strcasecmp (cmd, "echo") == 0)
959 printf (_("echo - display a line of text\n"
960 " echo [<params> ...]\n"
962 " This echos the parameters to the terminal.\n"));
963 else if (strcasecmp (cmd, "edit") == 0 ||
964 strcasecmp (cmd, "vi") == 0 ||
965 strcasecmp (cmd, "emacs") == 0)
966 printf (_("edit - edit a file in the image\n"
969 " This is used to edit a file.\n"
971 " It is the equivalent of (and is implemented by)\n"
972 " running \"cat\", editing locally, and then \"write-file\".\n"
974 " Normally it uses $EDITOR, but if you use the aliases\n"
975 " \"vi\" or \"emacs\" you will get those editors.\n"
977 " NOTE: This will not work reliably for large files\n"
978 " (> 2 MB) or binary files containing \\0 bytes.\n"));
979 else if (strcasecmp (cmd, "lcd") == 0)
980 printf (_("lcd - local change directory\n"
983 " Change guestfish's current directory. This command is\n"
984 " useful if you want to download files to a particular\n"
986 else if (strcasecmp (cmd, "glob") == 0)
987 printf (_("glob - expand wildcards in command\n"
988 " glob <command> [<args> ...]\n"
990 " Glob runs <command> with wildcards expanded in any\n"
991 " command args. Note that the command is run repeatedly\n"
992 " once for each expanded argument.\n"));
993 else if (strcasecmp (cmd, "help") == 0)
994 printf (_("help - display a list of commands or help on a command\n"
997 else if (strcasecmp (cmd, "more") == 0 ||
998 strcasecmp (cmd, "less") == 0)
999 printf (_("more - view a file in the pager\n"
1000 " more <filename>\n"
1002 " This is used to view a file in the pager.\n"
1004 " It is the equivalent of (and is implemented by)\n"
1005 " running \"cat\" and using the pager.\n"
1007 " Normally it uses $PAGER, but if you use the alias\n"
1008 " \"less\" then it always uses \"less\".\n"
1010 " NOTE: This will not work reliably for large files\n"
1011 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1012 else if (strcasecmp (cmd, "quit") == 0 ||
1013 strcasecmp (cmd, "exit") == 0 ||
1014 strcasecmp (cmd, "q") == 0)
1015 printf (_("quit - quit guestfish\n"
1017 else if (strcasecmp (cmd, "reopen") == 0)
1018 printf (_("reopen - close and reopen the libguestfs handle\n"
1021 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1022 "this normally, because the handle is closed properly when guestfish\n"
1023 "exits. However this is occasionally useful for testing.\n"));
1024 else if (strcasecmp (cmd, "time") == 0)
1025 printf (_("time - measure time taken to run command\n"
1026 " time <command> [<args> ...]\n"
1028 " This runs <command> as usual, and prints the elapsed\n"
1029 " time afterwards.\n"));
1031 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1036 free_strings (char **argv)
1040 for (argc = 0; argv[argc] != NULL; ++argc)
1046 count_strings (char *const *argv)
1050 for (c = 0; argv[c]; ++c)
1056 print_strings (char *const *argv)
1060 for (argc = 0; argv[argc] != NULL; ++argc)
1061 printf ("%s\n", argv[argc]);
1065 print_table (char *const *argv)
1069 for (i = 0; argv[i] != NULL; i += 2)
1070 printf ("%s: %s\n", argv[i], argv[i+1]);
1074 is_true (const char *str)
1077 strcasecmp (str, "0") != 0 &&
1078 strcasecmp (str, "f") != 0 &&
1079 strcasecmp (str, "false") != 0 &&
1080 strcasecmp (str, "n") != 0 &&
1081 strcasecmp (str, "no") != 0;
1084 /* XXX We could improve list parsing. */
1086 parse_string_list (const char *str)
1089 const char *p, *pend;
1093 for (i = 0; str[i]; ++i)
1094 if (str[i] == ' ') argc++;
1096 argv = malloc (sizeof (char *) * (argc+1));
1097 if (argv == NULL) { perror ("malloc"); exit (1); }
1102 pend = strchrnul (p, ' ');
1103 argv[i] = strndup (p, pend-p);
1105 p = *pend == ' ' ? pend+1 : pend;
1112 #ifdef HAVE_LIBREADLINE
1113 static char histfile[1024];
1114 static int nr_history_lines = 0;
1118 initialize_readline (void)
1120 #ifdef HAVE_LIBREADLINE
1123 home = getenv ("HOME");
1125 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1127 (void) read_history (histfile);
1130 rl_readline_name = "guestfish";
1131 rl_attempted_completion_function = do_completion;
1136 cleanup_readline (void)
1138 #ifdef HAVE_LIBREADLINE
1141 if (histfile[0] != '\0') {
1142 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1149 (void) append_history (nr_history_lines, histfile);
1155 add_history_line (const char *line)
1157 #ifdef HAVE_LIBREADLINE
1164 xwrite (int fd, const void *v_buf, size_t len)
1167 const char *buf = v_buf;
1170 r = write (fd, buf, len);