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;
74 launch (guestfs_h *_g)
78 if (guestfs_is_config (g)) {
79 if (guestfs_launch (g) == -1)
81 if (guestfs_wait_ready (g) == -1)
91 _("guestfish: guest filesystem shell\n"
92 "guestfish lets you edit virtual machine filesystems\n"
93 "Copyright (C) 2009 Red Hat Inc.\n"
95 " guestfish [--options] cmd [: cmd : cmd ...]\n"
96 " guestfish -i libvirt-domain\n"
97 " guestfish -i disk-image(s)\n"
98 "or for interactive use:\n"
100 "or from a shell script:\n"
106 " -h|--cmd-help List available commands\n"
107 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
108 " -a|--add image Add image\n"
109 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
110 " -f|--file file Read commands from file\n"
111 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
112 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
113 " -n|--no-sync Don't autosync\n"
114 " -r|--ro Mount read-only\n"
115 " -v|--verbose Verbose messages\n"
116 " -x Echo each command before executing it\n"
117 " -V|--version Display version and exit\n"
118 "For more information, see the manpage guestfish(1).\n"));
122 main (int argc, char *argv[])
124 static const char *options = "a:Df:h::im:nrv?Vx";
125 static struct option long_options[] = {
126 { "add", 1, 0, 'a' },
127 { "cmd-help", 2, 0, 'h' },
128 { "file", 1, 0, 'f' },
129 { "help", 0, 0, '?' },
130 { "inspector", 0, 0, 'i' },
131 { "mount", 1, 0, 'm' },
132 { "no-dest-paths", 0, 0, 'D' },
133 { "no-sync", 0, 0, 'n' },
135 { "verbose", 0, 0, 'v' },
136 { "version", 0, 0, 'V' },
139 struct drv *drvs = NULL;
141 struct mp *mps = NULL;
143 char *p, *file = NULL;
144 int c, inspector = 0;
147 initialize_readline ();
149 memset (&sa, 0, sizeof sa);
150 sa.sa_handler = SIG_IGN;
151 sa.sa_flags = SA_RESTART;
152 sigaction (SIGPIPE, &sa, NULL);
154 /* guestfs_create is meant to be a lightweight operation, so
155 * it's OK to do it early here.
157 g = guestfs_create ();
159 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
163 guestfs_set_autosync (g, 1);
165 /* If developing, add ./appliance to the path. Note that libtools
166 * interferes with this because uninstalled guestfish is a shell
167 * script that runs the real program with an absolute path. Detect
170 * BUT if LIBGUESTFS_PATH environment variable is already set by
171 * the user, then don't override it.
173 if (getenv ("LIBGUESTFS_PATH") == NULL &&
175 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
176 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
179 c = getopt_long (argc, argv, options, long_options, NULL);
184 if (access (optarg, R_OK) != 0) {
188 drv = malloc (sizeof (struct drv));
193 drv->filename = optarg;
199 complete_dest_paths = 0;
204 fprintf (stderr, _("guestfish: only one -f parameter can be given\n"));
212 display_command (optarg);
213 else if (argv[optind] && argv[optind][0] != '-')
214 display_command (argv[optind++]);
224 mp = malloc (sizeof (struct mp));
229 p = strchr (optarg, ':');
232 mp->mountpoint = p+1;
234 mp->mountpoint = "/";
241 guestfs_set_autosync (g, 0);
250 guestfs_set_verbose (g, verbose);
254 printf ("guestfish %s\n", PACKAGE_VERSION);
266 fprintf (stderr, _("guestfish: unexpected command line option 0x%x\n"),
272 /* Inspector mode invalidates most of the other arguments. */
278 fprintf (stderr, _("guestfish: cannot use -i option with -a or -m\n"));
281 if (optind >= argc) {
282 fprintf (stderr, _("guestfish -i requires a libvirt domain or path(s) to disk image(s)\n"));
286 strcpy (cmd, "a=`virt-inspector");
287 while (optind < argc) {
288 if (strlen (cmd) + strlen (argv[optind]) + strlen (argv[0]) + 60
290 fprintf (stderr, _("guestfish: virt-inspector command too long for fixed-size buffer\n"));
294 strcat (cmd, argv[optind]);
300 strcat (cmd, " --ro-fish");
302 strcat (cmd, " --fish");
304 sprintf (&cmd[strlen(cmd)], "` && %s $a", argv[0]);
306 if (guestfs_get_verbose (g))
308 if (!guestfs_get_autosync (g))
311 /*printf ("%s\n", cmd);*/
318 exit (WEXITSTATUS (r));
321 /* If we've got drives to add, add them now. */
324 /* If we've got mountpoints, we must launch the guest and mount them. */
326 if (launch (g) == -1) exit (1);
330 /* -f (file) parameter? */
333 if (open (file, O_RDONLY) == -1) {
339 /* Interactive, shell script, or command(s) on the command line? */
340 if (optind >= argc) {
347 cmdline (argv, optind, argc);
355 pod2text (const char *heading, const char *str)
359 fp = popen ("pod2text", "w");
361 /* pod2text failed, maybe not found, so let's just print the
362 * source instead, since that's better than doing nothing.
364 printf ("%s\n\n%s\n", heading, str);
367 fputs ("=head1 ", fp);
374 /* List is built in reverse order, so mount them in reverse order. */
376 mount_mps (struct mp *mp)
381 mount_mps (mp->next);
383 r = guestfs_mount (g, mp->device, mp->mountpoint);
385 r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
392 add_drives (struct drv *drv)
397 add_drives (drv->next);
399 r = guestfs_add_drive (g, drv->filename);
401 r = guestfs_add_drive_ro (g, drv->filename);
419 #define FISH "><fs> "
421 static char *line_read = NULL;
426 #ifdef HAVE_LIBREADLINE
434 line_read = readline (prompt ? FISH : "");
436 if (line_read && *line_read)
437 add_history_line (line_read);
442 #endif /* HAVE_LIBREADLINE */
444 static char buf[8192];
447 if (prompt) printf (FISH);
448 line_read = fgets (buf, sizeof buf, stdin);
451 len = strlen (line_read);
452 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
466 int global_exit_on_error = !prompt;
471 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
472 "editing virtual machine filesystems.\n"
474 "Type: 'help' for help with commands\n"
475 " 'quit' to quit the shell\n"
481 exit_on_error = global_exit_on_error;
483 buf = rl_gets (prompt);
489 /* Skip any initial whitespace before the command. */
491 while (*buf && isspace (*buf))
496 /* If the next character is '#' then this is a comment. */
497 if (*buf == '#') continue;
499 /* If the next character is '!' then pass the whole lot to system(3). */
507 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
508 WEXITSTATUS (r) != 0)
514 /* If the next character is '-' allow the command to fail without
515 * exiting on error (just for this one command though).
523 /* Get the command (cannot be quoted). */
524 len = strcspn (buf, " \t");
526 if (len == 0) continue;
530 if (buf[len] == '\0') {
537 p += strspn (p, " \t");
539 /* Get the parameters. */
540 while (*p && i < sizeof argv / sizeof argv[0]) {
541 /* Parameters which start with quotes or pipes are treated
542 * specially. Bare parameters are delimited by whitespace.
546 len = strcspn (p, "\"");
547 if (p[len] == '\0') {
548 fprintf (stderr, _("guestfish: unterminated double quote\n"));
549 if (exit_on_error) exit (1);
552 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
553 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
554 if (exit_on_error) exit (1);
558 pend = p[len+1] ? &p[len+2] : &p[len+1];
559 } else if (*p == '\'') {
561 len = strcspn (p, "'");
562 if (p[len] == '\0') {
563 fprintf (stderr, _("guestfish: unterminated single quote\n"));
564 if (exit_on_error) exit (1);
567 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
568 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
569 if (exit_on_error) exit (1);
573 pend = p[len+1] ? &p[len+2] : &p[len+1];
574 } else if (*p == '|') {
579 } else if (*p == '[') {
583 while (*pend && c != 0) {
584 if (*pend == '[') c++;
585 else if (*pend == ']') c--;
589 fprintf (stderr, _("guestfish: unterminated \"[...]\" sequence\n"));
590 if (exit_on_error) exit (1);
593 if (*pend && (*pend != ' ' && *pend != '\t')) {
594 fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
595 if (exit_on_error) exit (1);
600 } else if (*p != ' ' && *p != '\t') {
601 len = strcspn (p, " \t");
608 fprintf (stderr, _("guestfish: internal error parsing string at '%s'\n"),
617 p += strspn (p, " \t");
620 if (i == sizeof argv / sizeof argv[0]) {
621 fprintf (stderr, _("guestfish: too many arguments\n"));
622 if (exit_on_error) exit (1);
629 if (issue_command (cmd, argv, pipe) == -1) {
630 if (exit_on_error) exit (1);
635 if (prompt) printf ("\n");
639 cmdline (char *argv[], int optind, int argc)
644 if (optind >= argc) return;
646 cmd = argv[optind++];
647 if (strcmp (cmd, ":") == 0) {
648 fprintf (stderr, _("guestfish: empty command on command line\n"));
651 params = &argv[optind];
653 /* Search for end of command list or ":" ... */
654 while (optind < argc && strcmp (argv[optind], ":") != 0)
657 if (optind == argc) {
658 if (issue_command (cmd, params, NULL) == -1) exit (1);
661 if (issue_command (cmd, params, NULL) == -1) exit (1);
662 cmdline (argv, optind+1, argc);
667 issue_command (const char *cmd, char *argv[], const char *pipecmd)
670 int stdout_saved_fd = -1;
676 for (i = 0; argv[i] != NULL; ++i)
677 printf (" %s", argv[i]);
681 /* For | ... commands. Annoyingly we can't use popen(3) here. */
693 if (pid == 0) { /* Child process. */
697 r = system (pipecmd);
702 _exit (WEXITSTATUS (r));
705 stdout_saved_fd = dup (1);
711 for (argc = 0; argv[argc] != NULL; ++argc)
714 if (strcasecmp (cmd, "help") == 0) {
718 display_command (argv[0]);
721 else if (strcasecmp (cmd, "quit") == 0 ||
722 strcasecmp (cmd, "exit") == 0 ||
723 strcasecmp (cmd, "q") == 0) {
727 else if (strcasecmp (cmd, "alloc") == 0 ||
728 strcasecmp (cmd, "allocate") == 0)
729 r = do_alloc (cmd, argc, argv);
730 else if (strcasecmp (cmd, "echo") == 0)
731 r = do_echo (cmd, argc, argv);
732 else if (strcasecmp (cmd, "edit") == 0 ||
733 strcasecmp (cmd, "vi") == 0 ||
734 strcasecmp (cmd, "emacs") == 0)
735 r = do_edit (cmd, argc, argv);
736 else if (strcasecmp (cmd, "lcd") == 0)
737 r = do_lcd (cmd, argc, argv);
738 else if (strcasecmp (cmd, "glob") == 0)
739 r = do_glob (cmd, argc, argv);
740 else if (strcasecmp (cmd, "more") == 0 ||
741 strcasecmp (cmd, "less") == 0)
742 r = do_more (cmd, argc, argv);
743 else if (strcasecmp (cmd, "reopen") == 0)
744 r = do_reopen (cmd, argc, argv);
745 else if (strcasecmp (cmd, "time") == 0)
746 r = do_time (cmd, argc, argv);
748 r = run_action (cmd, argc, argv);
750 /* Always flush stdout after every command, so that messages, results
751 * etc appear immediately.
757 dup2 (stdout_saved_fd, 1);
758 close (stdout_saved_fd);
759 waitpid (pid, NULL, 0);
766 list_builtin_commands (void)
768 /* help and quit should appear at the top */
769 printf ("%-20s %s\n",
770 "help", _("display a list of commands or help on a command"));
771 printf ("%-20s %s\n",
772 "quit", _("quit guestfish"));
774 printf ("%-20s %s\n",
775 "alloc", _("allocate an image"));
776 printf ("%-20s %s\n",
777 "echo", _("display a line of text"));
778 printf ("%-20s %s\n",
779 "edit", _("edit a file in the image"));
780 printf ("%-20s %s\n",
781 "lcd", _("local change directory"));
782 printf ("%-20s %s\n",
783 "glob", _("expand wildcards in command"));
784 printf ("%-20s %s\n",
785 "more", _("view a file in the pager"));
786 printf ("%-20s %s\n",
787 "reopen", _("close and reopen libguestfs handle"));
788 printf ("%-20s %s\n",
789 "time", _("measure time taken to run command"));
791 /* actions are printed after this (see list_commands) */
795 display_builtin_command (const char *cmd)
797 /* help for actions is auto-generated, see display_command */
799 if (strcasecmp (cmd, "alloc") == 0 ||
800 strcasecmp (cmd, "allocate") == 0)
801 printf (_("alloc - allocate an image\n"
802 " alloc <filename> <size>\n"
804 " This creates an empty (zeroed) file of the given size,\n"
805 " and then adds so it can be further examined.\n"
807 " For more advanced image creation, see qemu-img utility.\n"
809 " Size can be specified (where <nn> means a number):\n"
810 " <nn> number of kilobytes\n"
811 " eg: 1440 standard 3.5\" floppy\n"
812 " <nn>K or <nn>KB number of kilobytes\n"
813 " <nn>M or <nn>MB number of megabytes\n"
814 " <nn>G or <nn>GB number of gigabytes\n"
815 " <nn>sects number of 512 byte sectors\n"));
816 else if (strcasecmp (cmd, "echo") == 0)
817 printf (_("echo - display a line of text\n"
818 " echo [<params> ...]\n"
820 " This echos the parameters to the terminal.\n"));
821 else if (strcasecmp (cmd, "edit") == 0 ||
822 strcasecmp (cmd, "vi") == 0 ||
823 strcasecmp (cmd, "emacs") == 0)
824 printf (_("edit - edit a file in the image\n"
827 " This is used to edit a file.\n"
829 " It is the equivalent of (and is implemented by)\n"
830 " running \"cat\", editing locally, and then \"write-file\".\n"
832 " Normally it uses $EDITOR, but if you use the aliases\n"
833 " \"vi\" or \"emacs\" you will get those editors.\n"
835 " NOTE: This will not work reliably for large files\n"
836 " (> 2 MB) or binary files containing \\0 bytes.\n"));
837 else if (strcasecmp (cmd, "lcd") == 0)
838 printf (_("lcd - local change directory\n"
841 " Change guestfish's current directory. This command is\n"
842 " useful if you want to download files to a particular\n"
844 else if (strcasecmp (cmd, "glob") == 0)
845 printf (_("glob - expand wildcards in command\n"
846 " glob <command> [<args> ...]\n"
848 " Glob runs <command> with wildcards expanded in any\n"
849 " command args. Note that the command is run repeatedly\n"
850 " once for each expanded argument.\n"));
851 else if (strcasecmp (cmd, "help") == 0)
852 printf (_("help - display a list of commands or help on a command\n"
855 else if (strcasecmp (cmd, "more") == 0 ||
856 strcasecmp (cmd, "less") == 0)
857 printf (_("more - view a file in the pager\n"
860 " This is used to view a file in the pager.\n"
862 " It is the equivalent of (and is implemented by)\n"
863 " running \"cat\" and using the pager.\n"
865 " Normally it uses $PAGER, but if you use the alias\n"
866 " \"less\" then it always uses \"less\".\n"
868 " NOTE: This will not work reliably for large files\n"
869 " (> 2 MB) or binary files containing \\0 bytes.\n"));
870 else if (strcasecmp (cmd, "quit") == 0 ||
871 strcasecmp (cmd, "exit") == 0 ||
872 strcasecmp (cmd, "q") == 0)
873 printf (_("quit - quit guestfish\n"
875 else if (strcasecmp (cmd, "reopen") == 0)
876 printf (_("reopen - close and reopen the libguestfs handle\n"
879 "Close and reopen the libguestfs handle. It is not necessary to use\n"
880 "this normally, because the handle is closed properly when guestfish\n"
881 "exits. However this is occasionally useful for testing.\n"));
882 else if (strcasecmp (cmd, "time") == 0)
883 printf (_("time - measure time taken to run command\n"
884 " time <command> [<args> ...]\n"
886 " This runs <command> as usual, and prints the elapsed\n"
887 " time afterwards.\n"));
889 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
894 free_strings (char **argv)
898 for (argc = 0; argv[argc] != NULL; ++argc)
904 count_strings (char * const * const argv)
908 for (c = 0; argv[c]; ++c)
914 print_strings (char * const * const argv)
918 for (argc = 0; argv[argc] != NULL; ++argc)
919 printf ("%s\n", argv[argc]);
923 print_table (char * const * const argv)
927 for (i = 0; argv[i] != NULL; i += 2)
928 printf ("%s: %s\n", argv[i], argv[i+1]);
932 is_true (const char *str)
935 strcasecmp (str, "0") != 0 &&
936 strcasecmp (str, "f") != 0 &&
937 strcasecmp (str, "false") != 0 &&
938 strcasecmp (str, "n") != 0 &&
939 strcasecmp (str, "no") != 0;
942 /* XXX We could improve list parsing. */
944 parse_string_list (const char *str)
947 const char *p, *pend;
951 for (i = 0; str[i]; ++i)
952 if (str[i] == ' ') argc++;
954 argv = malloc (sizeof (char *) * (argc+1));
955 if (argv == NULL) { perror ("malloc"); exit (1); }
960 pend = strchrnul (p, ' ');
961 argv[i] = strndup (p, pend-p);
963 p = *pend == ' ' ? pend+1 : pend;
970 #ifdef HAVE_LIBREADLINE
971 static char histfile[1024];
972 static int nr_history_lines = 0;
976 initialize_readline (void)
978 #ifdef HAVE_LIBREADLINE
981 home = getenv ("HOME");
983 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
985 (void) read_history (histfile);
988 rl_readline_name = "guestfish";
989 rl_attempted_completion_function = do_completion;
994 cleanup_readline (void)
996 #ifdef HAVE_LIBREADLINE
999 if (histfile[0] != '\0') {
1000 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1007 (void) append_history (nr_history_lines, histfile);
1013 add_history_line (const char *line)
1015 #ifdef HAVE_LIBREADLINE
1022 xwrite (int fd, const void *buf, size_t len)
1027 r = write (fd, buf, len);