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 " -v|--verbose Verbose messages\n"
121 " -x Echo each command before executing it\n"
122 " -V|--version Display version and exit\n"
123 "For more information, see the manpage guestfish(1).\n"));
127 main (int argc, char *argv[])
129 static const char *options = "a:Df:h::im:nrv?Vx";
130 static struct option long_options[] = {
131 { "add", 1, 0, 'a' },
132 { "cmd-help", 2, 0, 'h' },
133 { "file", 1, 0, 'f' },
134 { "help", 0, 0, '?' },
135 { "inspector", 0, 0, 'i' },
136 { "listen", 0, 0, 0 },
137 { "mount", 1, 0, 'm' },
138 { "no-dest-paths", 0, 0, 'D' },
139 { "no-sync", 0, 0, 'n' },
140 { "remote", 2, 0, 0 },
142 { "verbose", 0, 0, 'v' },
143 { "version", 0, 0, 'V' },
146 struct drv *drvs = NULL;
148 struct mp *mps = NULL;
150 char *p, *file = NULL;
156 initialize_readline ();
158 memset (&sa, 0, sizeof sa);
159 sa.sa_handler = SIG_IGN;
160 sa.sa_flags = SA_RESTART;
161 sigaction (SIGPIPE, &sa, NULL);
163 /* guestfs_create is meant to be a lightweight operation, so
164 * it's OK to do it early here.
166 g = guestfs_create ();
168 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
172 guestfs_set_autosync (g, 1);
174 /* If developing, add ./appliance to the path. Note that libtools
175 * interferes with this because uninstalled guestfish is a shell
176 * script that runs the real program with an absolute path. Detect
179 * BUT if LIBGUESTFS_PATH environment variable is already set by
180 * the user, then don't override it.
182 if (getenv ("LIBGUESTFS_PATH") == NULL &&
184 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
185 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
188 c = getopt_long (argc, argv, options, long_options, &option_index);
192 case 0: /* options which are long only */
193 if (strcmp (long_options[option_index].name, "listen") == 0)
194 remote_control_listen = 1;
195 else if (strcmp (long_options[option_index].name, "remote") == 0) {
197 if (sscanf (optarg, "%d", &remote_control) != 1) {
198 fprintf (stderr, _("guestfish: --listen=PID: PID was not a number: %s\n"), optarg);
202 p = getenv ("GUESTFISH_PID");
203 if (!p || sscanf (p, "%d", &remote_control) != 1) {
204 fprintf (stderr, _("guestfish: remote: $GUESTFISH_PID must be set to the PID of the remote process\n"));
209 fprintf (stderr, _("guestfish: unknown long option: %s (%d)\n"),
210 long_options[option_index].name, option_index);
216 if (access (optarg, R_OK) != 0) {
220 drv = malloc (sizeof (struct drv));
225 drv->filename = optarg;
231 complete_dest_paths = 0;
236 fprintf (stderr, _("guestfish: only one -f parameter can be given\n"));
244 display_command (optarg);
245 else if (argv[optind] && argv[optind][0] != '-')
246 display_command (argv[optind++]);
256 mp = malloc (sizeof (struct mp));
261 p = strchr (optarg, ':');
264 mp->mountpoint = p+1;
266 mp->mountpoint = "/";
273 guestfs_set_autosync (g, 0);
282 guestfs_set_verbose (g, verbose);
286 printf ("guestfish %s\n", PACKAGE_VERSION);
298 fprintf (stderr, _("guestfish: unexpected command line option 0x%x\n"),
304 /* Inspector mode invalidates most of the other arguments. */
309 if (drvs || mps || remote_control_listen || remote_control) {
310 fprintf (stderr, _("guestfish: cannot use -i option with -a, -m, --listen or --remote\n"));
313 if (optind >= argc) {
314 fprintf (stderr, _("guestfish -i requires a libvirt domain or path(s) to disk image(s)\n"));
318 strcpy (cmd, "a=`virt-inspector");
319 while (optind < argc) {
320 if (strlen (cmd) + strlen (argv[optind]) + strlen (argv[0]) + 60
322 fprintf (stderr, _("guestfish: virt-inspector command too long for fixed-size buffer\n"));
326 strcat (cmd, argv[optind]);
332 strcat (cmd, " --ro-fish");
334 strcat (cmd, " --fish");
336 sprintf (&cmd[strlen(cmd)], "` && %s $a", argv[0]);
338 if (guestfs_get_verbose (g))
340 if (!guestfs_get_autosync (g))
343 /*printf ("%s\n", cmd);*/
350 exit (WEXITSTATUS (r));
353 /* If we've got drives to add, add them now. */
356 /* If we've got mountpoints, we must launch the guest and mount them. */
358 if (launch (g) == -1) exit (1);
362 /* Remote control? */
363 if (remote_control_listen && remote_control) {
364 fprintf (stderr, _("guestfish: cannot use --listen and --remote options at the same time\n"));
368 if (remote_control_listen) {
370 fprintf (stderr, _("guestfish: extra parameters on the command line with --listen flag\n"));
374 fprintf (stderr, _("guestfish: cannot use --listen and --file options at the same time\n"));
380 /* -f (file) parameter? */
383 if (open (file, O_RDONLY) == -1) {
389 /* Interactive, shell script, or command(s) on the command line? */
390 if (optind >= argc) {
397 cmdline (argv, optind, argc);
405 pod2text (const char *heading, const char *str)
409 fp = popen ("pod2text", "w");
411 /* pod2text failed, maybe not found, so let's just print the
412 * source instead, since that's better than doing nothing.
414 printf ("%s\n\n%s\n", heading, str);
417 fputs ("=head1 ", fp);
424 /* List is built in reverse order, so mount them in reverse order. */
426 mount_mps (struct mp *mp)
431 mount_mps (mp->next);
433 r = guestfs_mount (g, mp->device, mp->mountpoint);
435 r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
442 add_drives (struct drv *drv)
447 add_drives (drv->next);
449 r = guestfs_add_drive (g, drv->filename);
451 r = guestfs_add_drive_ro (g, drv->filename);
469 #define FISH "><fs> "
471 static char *line_read = NULL;
476 #ifdef HAVE_LIBREADLINE
484 line_read = readline (prompt ? FISH : "");
486 if (line_read && *line_read)
487 add_history_line (line_read);
492 #endif /* HAVE_LIBREADLINE */
494 static char buf[8192];
497 if (prompt) printf (FISH);
498 line_read = fgets (buf, sizeof buf, stdin);
501 len = strlen (line_read);
502 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
516 int global_exit_on_error = !prompt;
520 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
521 "editing virtual machine filesystems.\n"
523 "Type: 'help' for help with commands\n"
524 " 'quit' to quit the shell\n"
530 exit_on_error = global_exit_on_error;
532 buf = rl_gets (prompt);
538 /* Skip any initial whitespace before the command. */
540 while (*buf && isspace (*buf))
545 /* If the next character is '#' then this is a comment. */
546 if (*buf == '#') continue;
548 /* If the next character is '!' then pass the whole lot to system(3). */
556 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
557 WEXITSTATUS (r) != 0)
563 /* If the next character is '-' allow the command to fail without
564 * exiting on error (just for this one command though).
572 /* Get the command (cannot be quoted). */
573 len = strcspn (buf, " \t");
575 if (len == 0) continue;
579 if (buf[len] == '\0') {
586 p += strspn (p, " \t");
588 /* Get the parameters. */
589 while (*p && i < sizeof argv / sizeof argv[0]) {
590 /* Parameters which start with quotes or pipes are treated
591 * specially. Bare parameters are delimited by whitespace.
595 len = strcspn (p, "\"");
596 if (p[len] == '\0') {
597 fprintf (stderr, _("guestfish: unterminated double quote\n"));
598 if (exit_on_error) exit (1);
601 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
602 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
603 if (exit_on_error) exit (1);
607 pend = p[len+1] ? &p[len+2] : &p[len+1];
608 } else if (*p == '\'') {
610 len = strcspn (p, "'");
611 if (p[len] == '\0') {
612 fprintf (stderr, _("guestfish: unterminated single quote\n"));
613 if (exit_on_error) exit (1);
616 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
617 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
618 if (exit_on_error) exit (1);
622 pend = p[len+1] ? &p[len+2] : &p[len+1];
623 } else if (*p == '|') {
628 } else if (*p == '[') {
632 while (*pend && c != 0) {
633 if (*pend == '[') c++;
634 else if (*pend == ']') c--;
638 fprintf (stderr, _("guestfish: unterminated \"[...]\" sequence\n"));
639 if (exit_on_error) exit (1);
642 if (*pend && (*pend != ' ' && *pend != '\t')) {
643 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
644 if (exit_on_error) exit (1);
649 } else if (*p != ' ' && *p != '\t') {
650 len = strcspn (p, " \t");
657 fprintf (stderr, _("guestfish: internal error parsing string at '%s'\n"),
666 p += strspn (p, " \t");
669 if (i == sizeof argv / sizeof argv[0]) {
670 fprintf (stderr, _("guestfish: too many arguments\n"));
671 if (exit_on_error) exit (1);
678 if (issue_command (cmd, argv, pipe) == -1) {
679 if (exit_on_error) exit (1);
684 if (prompt) printf ("\n");
688 cmdline (char *argv[], int optind, int argc)
695 if (optind >= argc) return;
697 cmd = argv[optind++];
698 if (strcmp (cmd, ":") == 0) {
699 fprintf (stderr, _("guestfish: empty command on command line\n"));
702 params = &argv[optind];
704 /* Search for end of command list or ":" ... */
705 while (optind < argc && strcmp (argv[optind], ":") != 0)
708 if (optind == argc) {
709 if (issue_command (cmd, params, NULL) == -1) exit (1);
712 if (issue_command (cmd, params, NULL) == -1) exit (1);
713 cmdline (argv, optind+1, argc);
718 issue_command (const char *cmd, char *argv[], const char *pipecmd)
721 int stdout_saved_fd = -1;
727 for (i = 0; argv[i] != NULL; ++i)
728 printf (" %s", argv[i]);
732 /* For | ... commands. Annoyingly we can't use popen(3) here. */
744 if (pid == 0) { /* Child process. */
748 r = system (pipecmd);
753 _exit (WEXITSTATUS (r));
756 stdout_saved_fd = dup (1);
762 for (argc = 0; argv[argc] != NULL; ++argc)
765 /* If --remote was set, then send this command to a remote process. */
767 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
769 /* Otherwise execute it locally. */
770 else if (strcasecmp (cmd, "help") == 0) {
774 display_command (argv[0]);
777 else if (strcasecmp (cmd, "quit") == 0 ||
778 strcasecmp (cmd, "exit") == 0 ||
779 strcasecmp (cmd, "q") == 0) {
783 else if (strcasecmp (cmd, "alloc") == 0 ||
784 strcasecmp (cmd, "allocate") == 0)
785 r = do_alloc (cmd, argc, argv);
786 else if (strcasecmp (cmd, "echo") == 0)
787 r = do_echo (cmd, argc, argv);
788 else if (strcasecmp (cmd, "edit") == 0 ||
789 strcasecmp (cmd, "vi") == 0 ||
790 strcasecmp (cmd, "emacs") == 0)
791 r = do_edit (cmd, argc, argv);
792 else if (strcasecmp (cmd, "lcd") == 0)
793 r = do_lcd (cmd, argc, argv);
794 else if (strcasecmp (cmd, "glob") == 0)
795 r = do_glob (cmd, argc, argv);
796 else if (strcasecmp (cmd, "more") == 0 ||
797 strcasecmp (cmd, "less") == 0)
798 r = do_more (cmd, argc, argv);
799 else if (strcasecmp (cmd, "reopen") == 0)
800 r = do_reopen (cmd, argc, argv);
801 else if (strcasecmp (cmd, "time") == 0)
802 r = do_time (cmd, argc, argv);
804 r = run_action (cmd, argc, argv);
806 /* Always flush stdout after every command, so that messages, results
807 * etc appear immediately.
813 dup2 (stdout_saved_fd, 1);
814 close (stdout_saved_fd);
815 waitpid (pid, NULL, 0);
822 list_builtin_commands (void)
824 /* help and quit should appear at the top */
825 printf ("%-20s %s\n",
826 "help", _("display a list of commands or help on a command"));
827 printf ("%-20s %s\n",
828 "quit", _("quit guestfish"));
830 printf ("%-20s %s\n",
831 "alloc", _("allocate an image"));
832 printf ("%-20s %s\n",
833 "echo", _("display a line of text"));
834 printf ("%-20s %s\n",
835 "edit", _("edit a file in the image"));
836 printf ("%-20s %s\n",
837 "lcd", _("local change directory"));
838 printf ("%-20s %s\n",
839 "glob", _("expand wildcards in command"));
840 printf ("%-20s %s\n",
841 "more", _("view a file in the pager"));
842 printf ("%-20s %s\n",
843 "reopen", _("close and reopen libguestfs handle"));
844 printf ("%-20s %s\n",
845 "time", _("measure time taken to run command"));
847 /* actions are printed after this (see list_commands) */
851 display_builtin_command (const char *cmd)
853 /* help for actions is auto-generated, see display_command */
855 if (strcasecmp (cmd, "alloc") == 0 ||
856 strcasecmp (cmd, "allocate") == 0)
857 printf (_("alloc - allocate an image\n"
858 " alloc <filename> <size>\n"
860 " This creates an empty (zeroed) file of the given size,\n"
861 " and then adds so it can be further examined.\n"
863 " For more advanced image creation, see qemu-img utility.\n"
865 " Size can be specified (where <nn> means a number):\n"
866 " <nn> number of kilobytes\n"
867 " eg: 1440 standard 3.5\" floppy\n"
868 " <nn>K or <nn>KB number of kilobytes\n"
869 " <nn>M or <nn>MB number of megabytes\n"
870 " <nn>G or <nn>GB number of gigabytes\n"
871 " <nn>sects number of 512 byte sectors\n"));
872 else if (strcasecmp (cmd, "echo") == 0)
873 printf (_("echo - display a line of text\n"
874 " echo [<params> ...]\n"
876 " This echos the parameters to the terminal.\n"));
877 else if (strcasecmp (cmd, "edit") == 0 ||
878 strcasecmp (cmd, "vi") == 0 ||
879 strcasecmp (cmd, "emacs") == 0)
880 printf (_("edit - edit a file in the image\n"
883 " This is used to edit a file.\n"
885 " It is the equivalent of (and is implemented by)\n"
886 " running \"cat\", editing locally, and then \"write-file\".\n"
888 " Normally it uses $EDITOR, but if you use the aliases\n"
889 " \"vi\" or \"emacs\" you will get those editors.\n"
891 " NOTE: This will not work reliably for large files\n"
892 " (> 2 MB) or binary files containing \\0 bytes.\n"));
893 else if (strcasecmp (cmd, "lcd") == 0)
894 printf (_("lcd - local change directory\n"
897 " Change guestfish's current directory. This command is\n"
898 " useful if you want to download files to a particular\n"
900 else if (strcasecmp (cmd, "glob") == 0)
901 printf (_("glob - expand wildcards in command\n"
902 " glob <command> [<args> ...]\n"
904 " Glob runs <command> with wildcards expanded in any\n"
905 " command args. Note that the command is run repeatedly\n"
906 " once for each expanded argument.\n"));
907 else if (strcasecmp (cmd, "help") == 0)
908 printf (_("help - display a list of commands or help on a command\n"
911 else if (strcasecmp (cmd, "more") == 0 ||
912 strcasecmp (cmd, "less") == 0)
913 printf (_("more - view a file in the pager\n"
916 " This is used to view a file in the pager.\n"
918 " It is the equivalent of (and is implemented by)\n"
919 " running \"cat\" and using the pager.\n"
921 " Normally it uses $PAGER, but if you use the alias\n"
922 " \"less\" then it always uses \"less\".\n"
924 " NOTE: This will not work reliably for large files\n"
925 " (> 2 MB) or binary files containing \\0 bytes.\n"));
926 else if (strcasecmp (cmd, "quit") == 0 ||
927 strcasecmp (cmd, "exit") == 0 ||
928 strcasecmp (cmd, "q") == 0)
929 printf (_("quit - quit guestfish\n"
931 else if (strcasecmp (cmd, "reopen") == 0)
932 printf (_("reopen - close and reopen the libguestfs handle\n"
935 "Close and reopen the libguestfs handle. It is not necessary to use\n"
936 "this normally, because the handle is closed properly when guestfish\n"
937 "exits. However this is occasionally useful for testing.\n"));
938 else if (strcasecmp (cmd, "time") == 0)
939 printf (_("time - measure time taken to run command\n"
940 " time <command> [<args> ...]\n"
942 " This runs <command> as usual, and prints the elapsed\n"
943 " time afterwards.\n"));
945 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
950 free_strings (char **argv)
954 for (argc = 0; argv[argc] != NULL; ++argc)
960 count_strings (char * const * const argv)
964 for (c = 0; argv[c]; ++c)
970 print_strings (char * const * const argv)
974 for (argc = 0; argv[argc] != NULL; ++argc)
975 printf ("%s\n", argv[argc]);
979 print_table (char * const * const argv)
983 for (i = 0; argv[i] != NULL; i += 2)
984 printf ("%s: %s\n", argv[i], argv[i+1]);
988 is_true (const char *str)
991 strcasecmp (str, "0") != 0 &&
992 strcasecmp (str, "f") != 0 &&
993 strcasecmp (str, "false") != 0 &&
994 strcasecmp (str, "n") != 0 &&
995 strcasecmp (str, "no") != 0;
998 /* XXX We could improve list parsing. */
1000 parse_string_list (const char *str)
1003 const char *p, *pend;
1007 for (i = 0; str[i]; ++i)
1008 if (str[i] == ' ') argc++;
1010 argv = malloc (sizeof (char *) * (argc+1));
1011 if (argv == NULL) { perror ("malloc"); exit (1); }
1016 pend = strchrnul (p, ' ');
1017 argv[i] = strndup (p, pend-p);
1019 p = *pend == ' ' ? pend+1 : pend;
1026 #ifdef HAVE_LIBREADLINE
1027 static char histfile[1024];
1028 static int nr_history_lines = 0;
1032 initialize_readline (void)
1034 #ifdef HAVE_LIBREADLINE
1037 home = getenv ("HOME");
1039 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1041 (void) read_history (histfile);
1044 rl_readline_name = "guestfish";
1045 rl_attempted_completion_function = do_completion;
1050 cleanup_readline (void)
1052 #ifdef HAVE_LIBREADLINE
1055 if (histfile[0] != '\0') {
1056 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1063 (void) append_history (nr_history_lines, histfile);
1069 add_history_line (const char *line)
1071 #ifdef HAVE_LIBREADLINE
1078 xwrite (int fd, const void *buf, size_t len)
1083 r = write (fd, buf, len);