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>
55 static void add_drives (struct drv *drv);
56 static void mount_mps (struct mp *mp);
57 static void interactive (void);
58 static void shell_script (void);
59 static void script (int prompt);
60 static void cmdline (char *argv[], int optind, int argc);
61 static void initialize_readline (void);
62 static void cleanup_readline (void);
63 static void add_history_line (const char *);
65 /* Currently open libguestfs handle. */
71 int echo_commands = 0;
72 int remote_control_listen = 0;
73 int remote_control = 0;
74 int exit_on_error = 1;
77 launch (guestfs_h *_g)
81 if (guestfs_is_config (g)) {
82 if (guestfs_launch (g) == -1)
84 if (guestfs_wait_ready (g) == -1)
94 _("guestfish: guest filesystem shell\n"
95 "guestfish lets you edit virtual machine filesystems\n"
96 "Copyright (C) 2009 Red Hat Inc.\n"
98 " guestfish [--options] cmd [: cmd : cmd ...]\n"
99 " guestfish -i libvirt-domain\n"
100 " guestfish -i disk-image(s)\n"
101 "or for interactive use:\n"
103 "or from a shell script:\n"
109 " -h|--cmd-help List available commands\n"
110 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
111 " -a|--add image Add image\n"
112 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
113 " -f|--file file Read commands from file\n"
114 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
115 " --listen Listen for remote commands\n"
116 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
117 " -n|--no-sync Don't autosync\n"
118 " --remote[=pid] Send commands to remote guestfish\n"
119 " -r|--ro Mount read-only\n"
120 " --selinux Enable SELinux support\n"
121 " -v|--verbose Verbose messages\n"
122 " -x Echo each command before executing it\n"
123 " -V|--version Display version and exit\n"
124 "For more information, see the manpage guestfish(1).\n"));
128 main (int argc, char *argv[])
130 static const char *options = "a:Df:h::im:nrv?Vx";
131 static const struct option long_options[] = {
132 { "add", 1, 0, 'a' },
133 { "cmd-help", 2, 0, 'h' },
134 { "file", 1, 0, 'f' },
135 { "help", 0, 0, '?' },
136 { "inspector", 0, 0, 'i' },
137 { "listen", 0, 0, 0 },
138 { "mount", 1, 0, 'm' },
139 { "no-dest-paths", 0, 0, 'D' },
140 { "no-sync", 0, 0, 'n' },
141 { "remote", 2, 0, 0 },
143 { "selinux", 0, 0, 0 },
144 { "verbose", 0, 0, 'v' },
145 { "version", 0, 0, 'V' },
148 struct drv *drvs = NULL;
150 struct mp *mps = NULL;
152 char *p, *file = NULL;
158 initialize_readline ();
160 memset (&sa, 0, sizeof sa);
161 sa.sa_handler = SIG_IGN;
162 sa.sa_flags = SA_RESTART;
163 sigaction (SIGPIPE, &sa, NULL);
165 /* guestfs_create is meant to be a lightweight operation, so
166 * it's OK to do it early here.
168 g = guestfs_create ();
170 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
174 guestfs_set_autosync (g, 1);
176 /* If developing, add ./appliance to the path. Note that libtools
177 * interferes with this because uninstalled guestfish is a shell
178 * script that runs the real program with an absolute path. Detect
181 * BUT if LIBGUESTFS_PATH environment variable is already set by
182 * the user, then don't override it.
184 if (getenv ("LIBGUESTFS_PATH") == NULL &&
186 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
187 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
190 c = getopt_long (argc, argv, options, long_options, &option_index);
194 case 0: /* options which are long only */
195 if (strcmp (long_options[option_index].name, "listen") == 0)
196 remote_control_listen = 1;
197 else if (strcmp (long_options[option_index].name, "remote") == 0) {
199 if (sscanf (optarg, "%d", &remote_control) != 1) {
200 fprintf (stderr, _("guestfish: --listen=PID: PID was not a number: %s\n"), optarg);
204 p = getenv ("GUESTFISH_PID");
205 if (!p || sscanf (p, "%d", &remote_control) != 1) {
206 fprintf (stderr, _("guestfish: remote: $GUESTFISH_PID must be set to the PID of the remote process\n"));
210 } else if (strcmp (long_options[option_index].name, "selinux") == 0) {
211 guestfs_set_selinux (g, 1);
213 fprintf (stderr, _("guestfish: unknown long option: %s (%d)\n"),
214 long_options[option_index].name, option_index);
220 if (access (optarg, R_OK) != 0) {
224 drv = malloc (sizeof (struct drv));
229 drv->filename = optarg;
235 complete_dest_paths = 0;
240 fprintf (stderr, _("guestfish: only one -f parameter can be given\n"));
248 display_command (optarg);
249 else if (argv[optind] && argv[optind][0] != '-')
250 display_command (argv[optind++]);
260 mp = malloc (sizeof (struct mp));
265 p = strchr (optarg, ':');
268 mp->mountpoint = p+1;
270 mp->mountpoint = "/";
277 guestfs_set_autosync (g, 0);
286 guestfs_set_verbose (g, verbose);
290 printf ("guestfish %s\n", PACKAGE_VERSION);
302 fprintf (stderr, _("guestfish: unexpected command line option 0x%x\n"),
308 /* Inspector mode invalidates most of the other arguments. */
313 if (drvs || mps || remote_control_listen || remote_control ||
314 guestfs_get_selinux (g)) {
315 fprintf (stderr, _("guestfish: cannot use -i option with -a, -m, --listen, --remote or --selinux\n"));
318 if (optind >= argc) {
319 fprintf (stderr, _("guestfish -i requires a libvirt domain or path(s) to disk image(s)\n"));
323 strcpy (cmd, "a=`virt-inspector");
324 while (optind < argc) {
325 if (strlen (cmd) + strlen (argv[optind]) + strlen (argv[0]) + 60
327 fprintf (stderr, _("guestfish: virt-inspector command too long for fixed-size buffer\n"));
331 strcat (cmd, argv[optind]);
337 strcat (cmd, " --ro-fish");
339 strcat (cmd, " --fish");
341 sprintf (&cmd[strlen(cmd)], "` && %s $a", argv[0]);
343 if (guestfs_get_verbose (g))
345 if (!guestfs_get_autosync (g))
350 "guestfish -i: running virt-inspector command:\n%s\n", cmd);
357 exit (WEXITSTATUS (r));
360 /* If we've got drives to add, add them now. */
363 /* If we've got mountpoints, we must launch the guest and mount them. */
365 if (launch (g) == -1) exit (1);
369 /* Remote control? */
370 if (remote_control_listen && remote_control) {
371 fprintf (stderr, _("guestfish: cannot use --listen and --remote options at the same time\n"));
375 if (remote_control_listen) {
377 fprintf (stderr, _("guestfish: extra parameters on the command line with --listen flag\n"));
381 fprintf (stderr, _("guestfish: cannot use --listen and --file options at the same time\n"));
387 /* -f (file) parameter? */
390 if (open (file, O_RDONLY) == -1) {
396 /* Interactive, shell script, or command(s) on the command line? */
397 if (optind >= argc) {
404 cmdline (argv, optind, argc);
412 pod2text (const char *name, const char *shortdesc, const char *str)
416 fp = popen ("pod2text", "w");
418 /* pod2text failed, maybe not found, so let's just print the
419 * source instead, since that's better than doing nothing.
421 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
424 fprintf (fp, "=head1 %s - %s\n\n", name, shortdesc);
429 /* List is built in reverse order, so mount them in reverse order. */
431 mount_mps (struct mp *mp)
436 mount_mps (mp->next);
438 r = guestfs_mount (g, mp->device, mp->mountpoint);
440 r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
447 add_drives (struct drv *drv)
452 add_drives (drv->next);
454 r = guestfs_add_drive (g, drv->filename);
456 r = guestfs_add_drive_ro (g, drv->filename);
474 #define FISH "><fs> "
476 static char *line_read = NULL;
481 #ifdef HAVE_LIBREADLINE
489 line_read = readline (prompt ? FISH : "");
491 if (line_read && *line_read)
492 add_history_line (line_read);
497 #endif /* HAVE_LIBREADLINE */
499 static char buf[8192];
502 if (prompt) printf (FISH);
503 line_read = fgets (buf, sizeof buf, stdin);
506 len = strlen (line_read);
507 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
521 int global_exit_on_error = !prompt;
526 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
527 "editing virtual machine filesystems.\n"
529 "Type: 'help' for help with commands\n"
530 " 'quit' to quit the shell\n"
536 exit_on_error = global_exit_on_error;
538 buf = rl_gets (prompt);
544 /* Skip any initial whitespace before the command. */
546 while (*buf && isspace (*buf))
551 /* If the next character is '#' then this is a comment. */
552 if (*buf == '#') continue;
554 /* If the next character is '!' then pass the whole lot to system(3). */
562 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
563 WEXITSTATUS (r) != 0)
569 /* If the next character is '-' allow the command to fail without
570 * exiting on error (just for this one command though).
578 /* Get the command (cannot be quoted). */
579 len = strcspn (buf, " \t");
581 if (len == 0) continue;
585 if (buf[len] == '\0') {
592 p += strspn (p, " \t");
594 /* Get the parameters. */
595 while (*p && i < sizeof argv / sizeof argv[0]) {
598 /* Parameters which start with quotes or pipes are treated
599 * specially. Bare parameters are delimited by whitespace.
603 len = strcspn (p, "\"");
604 if (p[len] == '\0') {
605 fprintf (stderr, _("guestfish: unterminated double quote\n"));
606 if (exit_on_error) exit (1);
609 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
610 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
611 if (exit_on_error) exit (1);
615 pend = p[len+1] ? &p[len+2] : &p[len+1];
616 } else if (*p == '\'') {
618 len = strcspn (p, "'");
619 if (p[len] == '\0') {
620 fprintf (stderr, _("guestfish: unterminated single quote\n"));
621 if (exit_on_error) exit (1);
624 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
625 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
626 if (exit_on_error) exit (1);
630 pend = p[len+1] ? &p[len+2] : &p[len+1];
631 } else if (*p == '|') {
636 } else if (*p == '[') {
640 while (*pend && c != 0) {
641 if (*pend == '[') c++;
642 else if (*pend == ']') c--;
646 fprintf (stderr, _("guestfish: unterminated \"[...]\" sequence\n"));
647 if (exit_on_error) exit (1);
650 if (*pend && (*pend != ' ' && *pend != '\t')) {
651 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
652 if (exit_on_error) exit (1);
657 } else if (*p != ' ' && *p != '\t') {
658 /* If the first character is a ~ then note that this parameter
659 * is a candidate for ~username expansion. NB this does not
660 * apply to quoted parameters.
662 tilde_candidate = *p == '~';
663 len = strcspn (p, " \t");
670 fprintf (stderr, _("guestfish: internal error parsing string at '%s'\n"),
675 if (!tilde_candidate)
678 argv[i] = try_tilde_expansion (p);
683 p += strspn (p, " \t");
686 if (i == sizeof argv / sizeof argv[0]) {
687 fprintf (stderr, _("guestfish: too many arguments\n"));
688 if (exit_on_error) exit (1);
695 if (issue_command (cmd, argv, pipe) == -1) {
696 if (exit_on_error) exit (1);
701 if (prompt) printf ("\n");
705 cmdline (char *argv[], int optind, int argc)
712 if (optind >= argc) return;
714 cmd = argv[optind++];
715 if (strcmp (cmd, ":") == 0) {
716 fprintf (stderr, _("guestfish: empty command on command line\n"));
719 params = &argv[optind];
721 /* Search for end of command list or ":" ... */
722 while (optind < argc && strcmp (argv[optind], ":") != 0)
725 if (optind == argc) {
726 if (issue_command (cmd, params, NULL) == -1) exit (1);
729 if (issue_command (cmd, params, NULL) == -1) exit (1);
730 cmdline (argv, optind+1, argc);
735 issue_command (const char *cmd, char *argv[], const char *pipecmd)
738 int stdout_saved_fd = -1;
744 for (i = 0; argv[i] != NULL; ++i)
745 printf (" %s", argv[i]);
749 /* For | ... commands. Annoyingly we can't use popen(3) here. */
761 if (pid == 0) { /* Child process. */
765 r = system (pipecmd);
770 _exit (WEXITSTATUS (r));
773 stdout_saved_fd = dup (1);
779 for (argc = 0; argv[argc] != NULL; ++argc)
782 /* If --remote was set, then send this command to a remote process. */
784 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
786 /* Otherwise execute it locally. */
787 else if (strcasecmp (cmd, "help") == 0) {
791 display_command (argv[0]);
794 else if (strcasecmp (cmd, "quit") == 0 ||
795 strcasecmp (cmd, "exit") == 0 ||
796 strcasecmp (cmd, "q") == 0) {
800 else if (strcasecmp (cmd, "alloc") == 0 ||
801 strcasecmp (cmd, "allocate") == 0)
802 r = do_alloc (cmd, argc, argv);
803 else if (strcasecmp (cmd, "echo") == 0)
804 r = do_echo (cmd, argc, argv);
805 else if (strcasecmp (cmd, "edit") == 0 ||
806 strcasecmp (cmd, "vi") == 0 ||
807 strcasecmp (cmd, "emacs") == 0)
808 r = do_edit (cmd, argc, argv);
809 else if (strcasecmp (cmd, "lcd") == 0)
810 r = do_lcd (cmd, argc, argv);
811 else if (strcasecmp (cmd, "glob") == 0)
812 r = do_glob (cmd, argc, argv);
813 else if (strcasecmp (cmd, "more") == 0 ||
814 strcasecmp (cmd, "less") == 0)
815 r = do_more (cmd, argc, argv);
816 else if (strcasecmp (cmd, "reopen") == 0)
817 r = do_reopen (cmd, argc, argv);
818 else if (strcasecmp (cmd, "time") == 0)
819 r = do_time (cmd, argc, argv);
821 r = run_action (cmd, argc, argv);
823 /* Always flush stdout after every command, so that messages, results
824 * etc appear immediately.
830 dup2 (stdout_saved_fd, 1);
831 close (stdout_saved_fd);
832 waitpid (pid, NULL, 0);
839 list_builtin_commands (void)
841 /* help and quit should appear at the top */
842 printf ("%-20s %s\n",
843 "help", _("display a list of commands or help on a command"));
844 printf ("%-20s %s\n",
845 "quit", _("quit guestfish"));
847 printf ("%-20s %s\n",
848 "alloc", _("allocate an image"));
849 printf ("%-20s %s\n",
850 "echo", _("display a line of text"));
851 printf ("%-20s %s\n",
852 "edit", _("edit a file in the image"));
853 printf ("%-20s %s\n",
854 "lcd", _("local change directory"));
855 printf ("%-20s %s\n",
856 "glob", _("expand wildcards in command"));
857 printf ("%-20s %s\n",
858 "more", _("view a file in the pager"));
859 printf ("%-20s %s\n",
860 "reopen", _("close and reopen libguestfs handle"));
861 printf ("%-20s %s\n",
862 "time", _("measure time taken to run command"));
864 /* actions are printed after this (see list_commands) */
868 display_builtin_command (const char *cmd)
870 /* help for actions is auto-generated, see display_command */
872 if (strcasecmp (cmd, "alloc") == 0 ||
873 strcasecmp (cmd, "allocate") == 0)
874 printf (_("alloc - allocate an image\n"
875 " alloc <filename> <size>\n"
877 " This creates an empty (zeroed) file of the given size,\n"
878 " and then adds so it can be further examined.\n"
880 " For more advanced image creation, see qemu-img utility.\n"
882 " Size can be specified (where <nn> means a number):\n"
883 " <nn> number of kilobytes\n"
884 " eg: 1440 standard 3.5\" floppy\n"
885 " <nn>K or <nn>KB number of kilobytes\n"
886 " <nn>M or <nn>MB number of megabytes\n"
887 " <nn>G or <nn>GB number of gigabytes\n"
888 " <nn>sects number of 512 byte sectors\n"));
889 else if (strcasecmp (cmd, "echo") == 0)
890 printf (_("echo - display a line of text\n"
891 " echo [<params> ...]\n"
893 " This echos the parameters to the terminal.\n"));
894 else if (strcasecmp (cmd, "edit") == 0 ||
895 strcasecmp (cmd, "vi") == 0 ||
896 strcasecmp (cmd, "emacs") == 0)
897 printf (_("edit - edit a file in the image\n"
900 " This is used to edit a file.\n"
902 " It is the equivalent of (and is implemented by)\n"
903 " running \"cat\", editing locally, and then \"write-file\".\n"
905 " Normally it uses $EDITOR, but if you use the aliases\n"
906 " \"vi\" or \"emacs\" you will get those editors.\n"
908 " NOTE: This will not work reliably for large files\n"
909 " (> 2 MB) or binary files containing \\0 bytes.\n"));
910 else if (strcasecmp (cmd, "lcd") == 0)
911 printf (_("lcd - local change directory\n"
914 " Change guestfish's current directory. This command is\n"
915 " useful if you want to download files to a particular\n"
917 else if (strcasecmp (cmd, "glob") == 0)
918 printf (_("glob - expand wildcards in command\n"
919 " glob <command> [<args> ...]\n"
921 " Glob runs <command> with wildcards expanded in any\n"
922 " command args. Note that the command is run repeatedly\n"
923 " once for each expanded argument.\n"));
924 else if (strcasecmp (cmd, "help") == 0)
925 printf (_("help - display a list of commands or help on a command\n"
928 else if (strcasecmp (cmd, "more") == 0 ||
929 strcasecmp (cmd, "less") == 0)
930 printf (_("more - view a file in the pager\n"
933 " This is used to view a file in the pager.\n"
935 " It is the equivalent of (and is implemented by)\n"
936 " running \"cat\" and using the pager.\n"
938 " Normally it uses $PAGER, but if you use the alias\n"
939 " \"less\" then it always uses \"less\".\n"
941 " NOTE: This will not work reliably for large files\n"
942 " (> 2 MB) or binary files containing \\0 bytes.\n"));
943 else if (strcasecmp (cmd, "quit") == 0 ||
944 strcasecmp (cmd, "exit") == 0 ||
945 strcasecmp (cmd, "q") == 0)
946 printf (_("quit - quit guestfish\n"
948 else if (strcasecmp (cmd, "reopen") == 0)
949 printf (_("reopen - close and reopen the libguestfs handle\n"
952 "Close and reopen the libguestfs handle. It is not necessary to use\n"
953 "this normally, because the handle is closed properly when guestfish\n"
954 "exits. However this is occasionally useful for testing.\n"));
955 else if (strcasecmp (cmd, "time") == 0)
956 printf (_("time - measure time taken to run command\n"
957 " time <command> [<args> ...]\n"
959 " This runs <command> as usual, and prints the elapsed\n"
960 " time afterwards.\n"));
962 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
967 free_strings (char **argv)
971 for (argc = 0; argv[argc] != NULL; ++argc)
977 count_strings (char *const *argv)
981 for (c = 0; argv[c]; ++c)
987 print_strings (char *const *argv)
991 for (argc = 0; argv[argc] != NULL; ++argc)
992 printf ("%s\n", argv[argc]);
996 print_table (char *const *argv)
1000 for (i = 0; argv[i] != NULL; i += 2)
1001 printf ("%s: %s\n", argv[i], argv[i+1]);
1005 is_true (const char *str)
1008 strcasecmp (str, "0") != 0 &&
1009 strcasecmp (str, "f") != 0 &&
1010 strcasecmp (str, "false") != 0 &&
1011 strcasecmp (str, "n") != 0 &&
1012 strcasecmp (str, "no") != 0;
1015 /* XXX We could improve list parsing. */
1017 parse_string_list (const char *str)
1020 const char *p, *pend;
1024 for (i = 0; str[i]; ++i)
1025 if (str[i] == ' ') argc++;
1027 argv = malloc (sizeof (char *) * (argc+1));
1028 if (argv == NULL) { perror ("malloc"); exit (1); }
1033 pend = strchrnul (p, ' ');
1034 argv[i] = strndup (p, pend-p);
1036 p = *pend == ' ' ? pend+1 : pend;
1043 #ifdef HAVE_LIBREADLINE
1044 static char histfile[1024];
1045 static int nr_history_lines = 0;
1049 initialize_readline (void)
1051 #ifdef HAVE_LIBREADLINE
1054 home = getenv ("HOME");
1056 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1058 (void) read_history (histfile);
1061 rl_readline_name = "guestfish";
1062 rl_attempted_completion_function = do_completion;
1067 cleanup_readline (void)
1069 #ifdef HAVE_LIBREADLINE
1072 if (histfile[0] != '\0') {
1073 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1080 (void) append_history (nr_history_lines, histfile);
1086 add_history_line (const char *line)
1088 #ifdef HAVE_LIBREADLINE
1095 xwrite (int fd, const void *buf, size_t len)
1100 r = write (fd, buf, len);