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.
29 #include <sys/types.h>
33 #ifdef HAVE_LIBREADLINE
34 #include <readline/readline.h>
35 #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 #ifdef HAVE_LIBREADLINE
65 static void add_history_line (const char *);
68 /* Currently open libguestfs handle. */
74 int remote_control_listen = 0;
75 int remote_control = 0;
76 int exit_on_error = 1;
80 launch (guestfs_h *_g)
84 if (guestfs_is_config (g)) {
85 if (guestfs_launch (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 atexit (close_stdout);
145 setlocale (LC_ALL, "");
146 bindtextdomain (PACKAGE, LOCALEBASEDIR);
147 textdomain (PACKAGE);
149 enum { HELP_OPTION = CHAR_MAX + 1 };
151 static const char *options = "a:Df:h::im:nrv?Vx";
152 static const struct option long_options[] = {
153 { "add", 1, 0, 'a' },
154 { "cmd-help", 2, 0, 'h' },
155 { "file", 1, 0, 'f' },
156 { "help", 0, 0, HELP_OPTION },
157 { "inspector", 0, 0, 'i' },
158 { "listen", 0, 0, 0 },
159 { "mount", 1, 0, 'm' },
160 { "no-dest-paths", 0, 0, 'D' },
161 { "no-sync", 0, 0, 'n' },
162 { "remote", 2, 0, 0 },
164 { "selinux", 0, 0, 0 },
165 { "verbose", 0, 0, 'v' },
166 { "version", 0, 0, 'V' },
169 struct drv *drvs = NULL;
171 struct mp *mps = NULL;
173 char *p, *file = NULL;
179 initialize_readline ();
181 memset (&sa, 0, sizeof sa);
182 sa.sa_handler = SIG_IGN;
183 sa.sa_flags = SA_RESTART;
184 sigaction (SIGPIPE, &sa, NULL);
186 /* guestfs_create is meant to be a lightweight operation, so
187 * it's OK to do it early here.
189 g = guestfs_create ();
191 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
195 guestfs_set_autosync (g, 1);
197 /* If developing, add ./appliance to the path. Note that libtools
198 * interferes with this because uninstalled guestfish is a shell
199 * script that runs the real program with an absolute path. Detect
202 * BUT if LIBGUESTFS_PATH environment variable is already set by
203 * the user, then don't override it.
205 if (getenv ("LIBGUESTFS_PATH") == NULL &&
207 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
208 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
210 /* CAUTION: we are careful to modify argv[0] here, only after
211 * using it just above.
213 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
214 * of the original, in case it's needed in virt-inspector mode, below.
216 char *real_argv0 = argv[0];
217 argv[0] = bad_cast (program_name);
220 c = getopt_long (argc, argv, options, long_options, &option_index);
224 case 0: /* options which are long only */
225 if (STREQ (long_options[option_index].name, "listen"))
226 remote_control_listen = 1;
227 else if (STREQ (long_options[option_index].name, "remote")) {
229 if (sscanf (optarg, "%d", &remote_control) != 1) {
230 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
231 program_name, optarg);
235 p = getenv ("GUESTFISH_PID");
236 if (!p || sscanf (p, "%d", &remote_control) != 1) {
237 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
238 " to the PID of the remote process\n"),
243 } else if (STREQ (long_options[option_index].name, "selinux")) {
244 guestfs_set_selinux (g, 1);
246 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
247 program_name, long_options[option_index].name, option_index);
253 if (access (optarg, R_OK) != 0) {
257 drv = malloc (sizeof (struct drv));
262 drv->filename = optarg;
268 complete_dest_paths = 0;
273 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
282 display_command (optarg);
283 else if (argv[optind] && argv[optind][0] != '-')
284 display_command (argv[optind++]);
294 mp = malloc (sizeof (struct mp));
299 p = strchr (optarg, ':');
302 mp->mountpoint = p+1;
304 mp->mountpoint = bad_cast ("/");
311 guestfs_set_autosync (g, 0);
320 guestfs_set_verbose (g, verbose);
324 printf ("%s %s\n", program_name, PACKAGE_VERSION);
328 guestfs_set_trace (g, 1);
332 usage (EXIT_SUCCESS);
335 usage (EXIT_FAILURE);
339 /* Inspector mode invalidates most of the other arguments. */
344 if (drvs || mps || remote_control_listen || remote_control ||
345 guestfs_get_selinux (g)) {
346 fprintf (stderr, _("%s: cannot use -i option with -a, -m,"
347 " --listen, --remote or --selinux\n"),
351 if (optind >= argc) {
353 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
358 strcpy (cmd, "a=`virt-inspector");
359 while (optind < argc) {
360 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
363 _("%s: virt-inspector command too long for fixed-size buffer\n"),
368 strcat (cmd, argv[optind]);
374 strcat (cmd, " --ro-fish");
376 strcat (cmd, " --fish");
378 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
380 if (guestfs_get_verbose (g))
382 if (!guestfs_get_autosync (g))
384 if (guestfs_get_trace (g))
389 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
396 exit (WEXITSTATUS (r));
399 /* If we've got drives to add, add them now. */
402 /* If we've got mountpoints, we must launch the guest and mount them. */
404 if (launch (g) == -1) exit (EXIT_FAILURE);
408 /* Remote control? */
409 if (remote_control_listen && remote_control) {
411 _("%s: cannot use --listen and --remote options at the same time\n"),
416 if (remote_control_listen) {
419 _("%s: extra parameters on the command line with --listen flag\n"),
425 _("%s: cannot use --listen and --file options at the same time\n"),
432 /* -f (file) parameter? */
435 if (open (file, O_RDONLY) == -1) {
441 /* Interactive, shell script, or command(s) on the command line? */
442 if (optind >= argc) {
449 cmdline (argv, optind, argc);
457 pod2text (const char *name, const char *shortdesc, const char *str)
461 fp = popen ("pod2text", "w");
463 /* pod2text failed, maybe not found, so let's just print the
464 * source instead, since that's better than doing nothing.
466 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
469 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
474 /* List is built in reverse order, so mount them in reverse order. */
476 mount_mps (struct mp *mp)
481 mount_mps (mp->next);
483 /* Don't use guestfs_mount here because that will default to mount
484 * options -o sync,noatime. For more information, see guestfs(3)
485 * section "LIBGUESTFS GOTCHAS".
487 const char *options = read_only ? "ro" : "";
488 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
495 add_drives (struct drv *drv)
500 add_drives (drv->next);
502 r = guestfs_add_drive (g, drv->filename);
504 r = guestfs_add_drive_ro (g, drv->filename);
522 #define FISH "><fs> "
524 static char *line_read = NULL;
529 #ifdef HAVE_LIBREADLINE
537 line_read = readline (prompt ? FISH : "");
539 if (line_read && *line_read)
540 add_history_line (line_read);
545 #endif /* HAVE_LIBREADLINE */
547 static char buf[8192];
550 if (prompt) printf (FISH);
551 line_read = fgets (buf, sizeof buf, stdin);
554 len = strlen (line_read);
555 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
569 int global_exit_on_error = !prompt;
574 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
575 "editing virtual machine filesystems.\n"
577 "Type: 'help' for help with commands\n"
578 " 'quit' to quit the shell\n"
584 exit_on_error = global_exit_on_error;
586 buf = rl_gets (prompt);
592 /* Skip any initial whitespace before the command. */
594 while (*buf && c_isspace (*buf))
599 /* If the next character is '#' then this is a comment. */
600 if (*buf == '#') continue;
602 /* If the next character is '!' then pass the whole lot to system(3). */
610 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
611 WEXITSTATUS (r) != 0)
617 /* If the next character is '-' allow the command to fail without
618 * exiting on error (just for this one command though).
626 /* Get the command (cannot be quoted). */
627 len = strcspn (buf, " \t");
629 if (len == 0) continue;
633 if (buf[len] == '\0') {
640 p += strspn (p, " \t");
642 /* Get the parameters. */
643 while (*p && i < sizeof argv / sizeof argv[0]) {
646 /* Parameters which start with quotes or pipes are treated
647 * specially. Bare parameters are delimited by whitespace.
651 len = strcspn (p, "\"");
652 if (p[len] == '\0') {
653 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
654 if (exit_on_error) exit (EXIT_FAILURE);
657 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
659 _("%s: command arguments not separated by whitespace\n"),
661 if (exit_on_error) exit (EXIT_FAILURE);
665 pend = p[len+1] ? &p[len+2] : &p[len+1];
666 } else if (*p == '\'') {
668 len = strcspn (p, "'");
669 if (p[len] == '\0') {
670 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
671 if (exit_on_error) exit (EXIT_FAILURE);
674 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
676 _("%s: command arguments not separated by whitespace\n"),
678 if (exit_on_error) exit (EXIT_FAILURE);
682 pend = p[len+1] ? &p[len+2] : &p[len+1];
683 } else if (*p == '|') {
688 } else if (*p == '[') {
692 while (*pend && c != 0) {
693 if (*pend == '[') c++;
694 else if (*pend == ']') c--;
699 _("%s: unterminated \"[...]\" sequence\n"), program_name);
700 if (exit_on_error) exit (EXIT_FAILURE);
703 if (*pend && (*pend != ' ' && *pend != '\t')) {
705 _("%s: command arguments not separated by whitespace\n"),
707 if (exit_on_error) exit (EXIT_FAILURE);
712 } else if (*p != ' ' && *p != '\t') {
713 /* If the first character is a ~ then note that this parameter
714 * is a candidate for ~username expansion. NB this does not
715 * apply to quoted parameters.
717 tilde_candidate = *p == '~';
718 len = strcspn (p, " \t");
725 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
730 if (!tilde_candidate)
733 argv[i] = try_tilde_expansion (p);
738 p += strspn (p, " \t");
741 if (i == sizeof argv / sizeof argv[0]) {
742 fprintf (stderr, _("%s: too many arguments\n"), program_name);
743 if (exit_on_error) exit (EXIT_FAILURE);
750 if (issue_command (cmd, argv, pipe) == -1) {
751 if (exit_on_error) exit (EXIT_FAILURE);
756 if (prompt) printf ("\n");
760 cmdline (char *argv[], int optind, int argc)
767 if (optind >= argc) return;
769 cmd = argv[optind++];
770 if (STREQ (cmd, ":")) {
771 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
775 /* Allow -cmd on the command line to mean (temporarily) override
776 * the normal exit on error (RHBZ#578407).
783 params = &argv[optind];
785 /* Search for end of command list or ":" ... */
786 while (optind < argc && STRNEQ (argv[optind], ":"))
789 if (optind == argc) {
790 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
794 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
796 cmdline (argv, optind+1, argc);
801 issue_command (const char *cmd, char *argv[], const char *pipecmd)
804 int stdout_saved_fd = -1;
808 /* This counts the commands issued, starting at 1. */
811 /* For | ... commands. Annoyingly we can't use popen(3) here. */
815 if (fflush (stdout) == EOF) {
816 perror ("failed to flush standard output");
820 perror ("pipe failed");
829 if (pid == 0) { /* Child process. */
831 if (dup2 (fd[0], 0) < 0) {
832 perror ("dup2 of stdin failed");
836 r = system (pipecmd);
841 _exit (WEXITSTATUS (r));
844 if ((stdout_saved_fd = dup (1)) < 0) {
845 perror ("failed to dup stdout");
849 if (dup2 (fd[1], 1) < 0) {
850 perror ("failed to dup stdout");
851 close (stdout_saved_fd);
857 for (argc = 0; argv[argc] != NULL; ++argc)
860 /* If --remote was set, then send this command to a remote process. */
862 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
864 /* Otherwise execute it locally. */
865 else if (STRCASEEQ (cmd, "help")) {
869 display_command (argv[0]);
872 else if (STRCASEEQ (cmd, "quit") ||
873 STRCASEEQ (cmd, "exit") ||
874 STRCASEEQ (cmd, "q")) {
878 else if (STRCASEEQ (cmd, "alloc") ||
879 STRCASEEQ (cmd, "allocate"))
880 r = do_alloc (cmd, argc, argv);
881 else if (STRCASEEQ (cmd, "echo"))
882 r = do_echo (cmd, argc, argv);
883 else if (STRCASEEQ (cmd, "edit") ||
884 STRCASEEQ (cmd, "vi") ||
885 STRCASEEQ (cmd, "emacs"))
886 r = do_edit (cmd, argc, argv);
887 else if (STRCASEEQ (cmd, "lcd"))
888 r = do_lcd (cmd, argc, argv);
889 else if (STRCASEEQ (cmd, "glob"))
890 r = do_glob (cmd, argc, argv);
891 else if (STRCASEEQ (cmd, "more") ||
892 STRCASEEQ (cmd, "less"))
893 r = do_more (cmd, argc, argv);
894 else if (STRCASEEQ (cmd, "reopen"))
895 r = do_reopen (cmd, argc, argv);
896 else if (STRCASEEQ (cmd, "sparse"))
897 r = do_sparse (cmd, argc, argv);
898 else if (STRCASEEQ (cmd, "time"))
899 r = do_time (cmd, argc, argv);
901 r = run_action (cmd, argc, argv);
903 /* Always flush stdout after every command, so that messages, results
904 * etc appear immediately.
906 if (fflush (stdout) == EOF) {
907 perror ("failed to flush standard output");
913 if (dup2 (stdout_saved_fd, 1) < 0) {
914 perror ("failed to dup2 standard output");
917 close (stdout_saved_fd);
918 if (waitpid (pid, NULL, 0) < 0) {
919 perror ("waiting for command to complete");
928 list_builtin_commands (void)
930 /* help and quit should appear at the top */
931 printf ("%-20s %s\n",
932 "help", _("display a list of commands or help on a command"));
933 printf ("%-20s %s\n",
934 "quit", _("quit guestfish"));
936 printf ("%-20s %s\n",
937 "alloc", _("allocate an image"));
938 printf ("%-20s %s\n",
939 "echo", _("display a line of text"));
940 printf ("%-20s %s\n",
941 "edit", _("edit a file in the image"));
942 printf ("%-20s %s\n",
943 "lcd", _("local change directory"));
944 printf ("%-20s %s\n",
945 "glob", _("expand wildcards in command"));
946 printf ("%-20s %s\n",
947 "more", _("view a file in the pager"));
948 printf ("%-20s %s\n",
949 "reopen", _("close and reopen libguestfs handle"));
950 printf ("%-20s %s\n",
951 "sparse", _("allocate a sparse image file"));
952 printf ("%-20s %s\n",
953 "time", _("measure time taken to run command"));
955 /* actions are printed after this (see list_commands) */
959 display_builtin_command (const char *cmd)
961 /* help for actions is auto-generated, see display_command */
963 if (STRCASEEQ (cmd, "alloc") ||
964 STRCASEEQ (cmd, "allocate"))
965 printf (_("alloc - allocate an image\n"
966 " alloc <filename> <size>\n"
968 " This creates an empty (zeroed) file of the given size,\n"
969 " and then adds so it can be further examined.\n"
971 " For more advanced image creation, see qemu-img utility.\n"
973 " Size can be specified (where <nn> means a number):\n"
974 " <nn> number of kilobytes\n"
975 " eg: 1440 standard 3.5\" floppy\n"
976 " <nn>K or <nn>KB number of kilobytes\n"
977 " <nn>M or <nn>MB number of megabytes\n"
978 " <nn>G or <nn>GB number of gigabytes\n"
979 " <nn>T or <nn>TB number of terabytes\n"
980 " <nn>P or <nn>PB number of petabytes\n"
981 " <nn>E or <nn>EB number of exabytes\n"
982 " <nn>sects number of 512 byte sectors\n"));
983 else if (STRCASEEQ (cmd, "echo"))
984 printf (_("echo - display a line of text\n"
985 " echo [<params> ...]\n"
987 " This echos the parameters to the terminal.\n"));
988 else if (STRCASEEQ (cmd, "edit") ||
989 STRCASEEQ (cmd, "vi") ||
990 STRCASEEQ (cmd, "emacs"))
991 printf (_("edit - edit a file in the image\n"
994 " This is used to edit a file.\n"
996 " It is the equivalent of (and is implemented by)\n"
997 " running \"cat\", editing locally, and then \"write-file\".\n"
999 " Normally it uses $EDITOR, but if you use the aliases\n"
1000 " \"vi\" or \"emacs\" you will get those editors.\n"
1002 " NOTE: This will not work reliably for large files\n"
1003 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1004 else if (STRCASEEQ (cmd, "lcd"))
1005 printf (_("lcd - local change directory\n"
1006 " lcd <directory>\n"
1008 " Change guestfish's current directory. This command is\n"
1009 " useful if you want to download files to a particular\n"
1011 else if (STRCASEEQ (cmd, "glob"))
1012 printf (_("glob - expand wildcards in command\n"
1013 " glob <command> [<args> ...]\n"
1015 " Glob runs <command> with wildcards expanded in any\n"
1016 " command args. Note that the command is run repeatedly\n"
1017 " once for each expanded argument.\n"));
1018 else if (STRCASEEQ (cmd, "help"))
1019 printf (_("help - display a list of commands or help on a command\n"
1022 else if (STRCASEEQ (cmd, "more") ||
1023 STRCASEEQ (cmd, "less"))
1024 printf (_("more - view a file in the pager\n"
1025 " more <filename>\n"
1027 " This is used to view a file in the pager.\n"
1029 " It is the equivalent of (and is implemented by)\n"
1030 " running \"cat\" and using the pager.\n"
1032 " Normally it uses $PAGER, but if you use the alias\n"
1033 " \"less\" then it always uses \"less\".\n"
1035 " NOTE: This will not work reliably for large files\n"
1036 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1037 else if (STRCASEEQ (cmd, "quit") ||
1038 STRCASEEQ (cmd, "exit") ||
1039 STRCASEEQ (cmd, "q"))
1040 printf (_("quit - quit guestfish\n"
1042 else if (STRCASEEQ (cmd, "reopen"))
1043 printf (_("reopen - close and reopen the libguestfs handle\n"
1046 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1047 "this normally, because the handle is closed properly when guestfish\n"
1048 "exits. However this is occasionally useful for testing.\n"));
1049 else if (STRCASEEQ (cmd, "sparse"))
1050 printf (_("sparse - allocate a sparse image file\n"
1051 " sparse <filename> <size>\n"
1053 " This creates an empty sparse file of the given size,\n"
1054 " and then adds so it can be further examined.\n"
1056 " In all respects it works the same as the 'alloc'\n"
1057 " command, except that the image file is allocated\n"
1058 " sparsely, which means that disk blocks are not assigned\n"
1059 " to the file until they are needed. Sparse disk files\n"
1060 " only use space when written to, but they are slower\n"
1061 " and there is a danger you could run out of real disk\n"
1062 " space during a write operation.\n"
1064 " For more advanced image creation, see qemu-img utility.\n"
1066 " Size can be specified (where <nn> means a number):\n"
1067 " <nn> number of kilobytes\n"
1068 " eg: 1440 standard 3.5\" floppy\n"
1069 " <nn>K or <nn>KB number of kilobytes\n"
1070 " <nn>M or <nn>MB number of megabytes\n"
1071 " <nn>G or <nn>GB number of gigabytes\n"
1072 " <nn>T or <nn>TB number of terabytes\n"
1073 " <nn>P or <nn>PB number of petabytes\n"
1074 " <nn>E or <nn>EB number of exabytes\n"
1075 " <nn>sects number of 512 byte sectors\n"));
1076 else if (STRCASEEQ (cmd, "time"))
1077 printf (_("time - measure time taken to run command\n"
1078 " time <command> [<args> ...]\n"
1080 " This runs <command> as usual, and prints the elapsed\n"
1081 " time afterwards.\n"));
1083 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1087 /* This is printed when the user types in an unknown command for the
1088 * first command issued. A common case is the user doing:
1089 * guestfish disk.img
1090 * expecting guestfish to open 'disk.img' (in fact, this tried to
1091 * run a command 'disk.img').
1094 extended_help_message (void)
1097 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1098 "For a list of commands: guestfish -h\n"
1099 "For complete documentation: man guestfish\n"));
1103 free_strings (char **argv)
1107 for (argc = 0; argv[argc] != NULL; ++argc)
1113 count_strings (char *const *argv)
1117 for (c = 0; argv[c]; ++c)
1123 print_strings (char *const *argv)
1127 for (argc = 0; argv[argc] != NULL; ++argc)
1128 printf ("%s\n", argv[argc]);
1132 print_table (char *const *argv)
1136 for (i = 0; argv[i] != NULL; i += 2)
1137 printf ("%s: %s\n", argv[i], argv[i+1]);
1141 is_true (const char *str)
1144 STRCASENEQ (str, "0") &&
1145 STRCASENEQ (str, "f") &&
1146 STRCASENEQ (str, "false") &&
1147 STRCASENEQ (str, "n") &&
1148 STRCASENEQ (str, "no");
1151 /* Free strings from a non-NULL terminated char** */
1153 free_n_strings (char **str, size_t len)
1157 for (i = 0; i < len; i++) {
1164 parse_string_list (const char *str)
1167 size_t argv_len = 0;
1169 /* Current position pointer */
1170 const char *p = str;
1172 /* Token might be simple:
1175 * 'This is a single token'
1176 * or contain embedded single-quoted sections:
1177 * This' is a sing'l'e to'ken
1179 * The latter may seem over-complicated, but it's what a normal shell does.
1180 * Not doing it risks surprising somebody.
1182 * This outer loop is over complete tokens.
1188 /* Skip leading whitespace */
1189 p += strspn (p, " \t");
1193 /* This loop is over token 'fragments'. A token can be in multiple bits if
1194 * it contains single quotes. We also treat both sides of an escaped quote
1195 * as separate fragments because we can't just copy it: we have to remove
1198 while (*p && (!c_isblank (*p) || in_quote)) {
1199 const char *end = p;
1201 /* Check if the fragment starts with a quote */
1203 /* Toggle in_quote */
1204 in_quote = !in_quote;
1206 /* Skip the quote */
1210 /* If we're in a quote, look for an end quote */
1212 end += strcspn (end, "'");
1215 /* Otherwise, look for whitespace or a quote */
1217 end += strcspn (end, " \t'");
1220 /* Grow the token to accommodate the fragment */
1221 size_t tok_end = tok_len;
1223 char *tok_new = realloc (tok, tok_len + 1);
1224 if (NULL == tok_new) {
1226 free_n_strings (argv, argv_len);
1228 exit (EXIT_FAILURE);
1232 /* Check if we stopped on an escaped quote */
1233 if ('\'' == *end && end != p && *(end-1) == '\\') {
1234 /* Add everything before \' to the token */
1235 memcpy (&tok[tok_end], p, end - p - 1);
1238 tok[tok_len-1] = '\'';
1240 /* Already processed the quote */
1245 /* Add the whole fragment */
1246 memcpy (&tok[tok_end], p, end - p);
1252 /* We've reached the end of a token. We shouldn't still be in quotes. */
1254 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1256 free_n_strings (argv, argv_len);
1261 /* Add this token if there is one. There might not be if there was
1262 * whitespace at the end of the input string */
1264 /* Add the NULL terminator */
1265 tok[tok_len] = '\0';
1267 /* Add the argument to the argument list */
1269 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1270 if (NULL == argv_new) {
1272 free_n_strings (argv, argv_len-1);
1274 exit (EXIT_FAILURE);
1278 argv[argv_len-1] = tok;
1282 /* NULL terminate the argument list */
1284 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1285 if (NULL == argv_new) {
1287 free_n_strings (argv, argv_len-1);
1288 exit (EXIT_FAILURE);
1292 argv[argv_len-1] = NULL;
1297 #ifdef HAVE_LIBREADLINE
1298 static char histfile[1024];
1299 static int nr_history_lines = 0;
1303 initialize_readline (void)
1305 #ifdef HAVE_LIBREADLINE
1308 home = getenv ("HOME");
1310 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1312 (void) read_history (histfile);
1315 rl_readline_name = "guestfish";
1316 rl_attempted_completion_function = do_completion;
1318 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1319 * call the readline(), which happens later. Therefore, these
1320 * provide default values which can be overridden by the user if
1323 (void) rl_variable_bind ("completion-ignore-case", "on");
1328 cleanup_readline (void)
1330 #ifdef HAVE_LIBREADLINE
1333 if (histfile[0] != '\0') {
1334 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1341 #ifdef HAVE_APPEND_HISTORY
1342 (void) append_history (nr_history_lines, histfile);
1344 (void) write_history (histfile);
1350 #ifdef HAVE_LIBREADLINE
1352 add_history_line (const char *line)
1360 xwrite (int fd, const void *v_buf, size_t len)
1363 const char *buf = v_buf;
1366 r = write (fd, buf, len);
1378 /* Resolve the special "win:..." form for Windows-specific paths.
1379 * This always returns a newly allocated string which is freed by the
1380 * caller function in "cmds.c".
1383 resolve_win_path (const char *path)
1388 if (STRCASENEQLEN (path, "win:", 4)) {
1389 ret = strdup (path);
1397 /* Drop drive letter, if it's "C:". */
1398 if (STRCASEEQLEN (path, "c:", 2))
1408 ret = strdup (path);
1414 /* Blindly convert any backslashes into forward slashes. Is this good? */
1415 for (i = 0; i < strlen (ret); ++i)
1419 char *t = guestfs_case_sensitive_path (g, ret);