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 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;
79 launch (guestfs_h *_g)
83 if (guestfs_is_config (g)) {
84 if (guestfs_launch (g) == -1)
90 static void __attribute__((noreturn))
93 if (status != EXIT_SUCCESS)
94 fprintf (stderr, _("Try `%s --help' for more information.\n"),
98 _("%s: guest filesystem shell\n"
99 "%s lets you edit virtual machine filesystems\n"
100 "Copyright (C) 2009 Red Hat Inc.\n"
102 " %s [--options] cmd [: cmd : cmd ...]\n"
103 " %s -i libvirt-domain\n"
104 " %s -i disk-image(s)\n"
105 "or for interactive use:\n"
107 "or from a shell script:\n"
113 " -h|--cmd-help List available commands\n"
114 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
115 " -a|--add image Add image\n"
116 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
117 " -f|--file file Read commands from file\n"
118 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
119 " --listen Listen for remote commands\n"
120 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
121 " -n|--no-sync Don't autosync\n"
122 " --remote[=pid] Send commands to remote %s\n"
123 " -r|--ro Mount read-only\n"
124 " --selinux Enable SELinux support\n"
125 " -v|--verbose Verbose messages\n"
126 " -x Echo each command before executing it\n"
127 " -V|--version Display version and exit\n"
128 "For more information, see the manpage %s(1).\n"),
129 program_name, program_name, program_name,
130 program_name, program_name, program_name,
131 program_name, program_name, program_name);
137 main (int argc, char *argv[])
139 /* Set global program name that is not polluted with libtool artifacts. */
140 set_program_name (argv[0]);
142 atexit (close_stdout);
144 setlocale (LC_ALL, "");
145 bindtextdomain (PACKAGE, LOCALEBASEDIR);
146 textdomain (PACKAGE);
148 enum { HELP_OPTION = CHAR_MAX + 1 };
150 static const char *options = "a:Df:h::im:nrv?Vx";
151 static const struct option long_options[] = {
152 { "add", 1, 0, 'a' },
153 { "cmd-help", 2, 0, 'h' },
154 { "file", 1, 0, 'f' },
155 { "help", 0, 0, HELP_OPTION },
156 { "inspector", 0, 0, 'i' },
157 { "listen", 0, 0, 0 },
158 { "mount", 1, 0, 'm' },
159 { "no-dest-paths", 0, 0, 'D' },
160 { "no-sync", 0, 0, 'n' },
161 { "remote", 2, 0, 0 },
163 { "selinux", 0, 0, 0 },
164 { "verbose", 0, 0, 'v' },
165 { "version", 0, 0, 'V' },
168 struct drv *drvs = NULL;
170 struct mp *mps = NULL;
172 char *p, *file = NULL;
178 initialize_readline ();
180 memset (&sa, 0, sizeof sa);
181 sa.sa_handler = SIG_IGN;
182 sa.sa_flags = SA_RESTART;
183 sigaction (SIGPIPE, &sa, NULL);
185 /* guestfs_create is meant to be a lightweight operation, so
186 * it's OK to do it early here.
188 g = guestfs_create ();
190 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
194 guestfs_set_autosync (g, 1);
196 /* If developing, add ./appliance to the path. Note that libtools
197 * interferes with this because uninstalled guestfish is a shell
198 * script that runs the real program with an absolute path. Detect
201 * BUT if LIBGUESTFS_PATH environment variable is already set by
202 * the user, then don't override it.
204 if (getenv ("LIBGUESTFS_PATH") == NULL &&
206 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
207 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
209 /* CAUTION: we are careful to modify argv[0] here, only after
210 * using it just above.
212 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
213 * of the original, in case it's needed in virt-inspector mode, below.
215 char *real_argv0 = argv[0];
216 argv[0] = bad_cast (program_name);
219 c = getopt_long (argc, argv, options, long_options, &option_index);
223 case 0: /* options which are long only */
224 if (STREQ (long_options[option_index].name, "listen"))
225 remote_control_listen = 1;
226 else if (STREQ (long_options[option_index].name, "remote")) {
228 if (sscanf (optarg, "%d", &remote_control) != 1) {
229 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
230 program_name, optarg);
234 p = getenv ("GUESTFISH_PID");
235 if (!p || sscanf (p, "%d", &remote_control) != 1) {
236 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
237 " to the PID of the remote process\n"),
242 } else if (STREQ (long_options[option_index].name, "selinux")) {
243 guestfs_set_selinux (g, 1);
245 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
246 program_name, long_options[option_index].name, option_index);
252 if (access (optarg, R_OK) != 0) {
256 drv = malloc (sizeof (struct drv));
261 drv->filename = optarg;
267 complete_dest_paths = 0;
272 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
281 display_command (optarg);
282 else if (argv[optind] && argv[optind][0] != '-')
283 display_command (argv[optind++]);
293 mp = malloc (sizeof (struct mp));
298 p = strchr (optarg, ':');
301 mp->mountpoint = p+1;
303 mp->mountpoint = bad_cast ("/");
310 guestfs_set_autosync (g, 0);
319 guestfs_set_verbose (g, verbose);
323 printf ("%s %s\n", program_name, PACKAGE_VERSION);
331 usage (EXIT_SUCCESS);
334 usage (EXIT_FAILURE);
338 /* Inspector mode invalidates most of the other arguments. */
343 if (drvs || mps || remote_control_listen || remote_control ||
344 guestfs_get_selinux (g)) {
345 fprintf (stderr, _("%s: cannot use -i option with -a, -m,"
346 " --listen, --remote or --selinux\n"),
350 if (optind >= argc) {
352 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
357 strcpy (cmd, "a=`virt-inspector");
358 while (optind < argc) {
359 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
362 _("%s: virt-inspector command too long for fixed-size buffer\n"),
367 strcat (cmd, argv[optind]);
373 strcat (cmd, " --ro-fish");
375 strcat (cmd, " --fish");
377 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
379 if (guestfs_get_verbose (g))
381 if (!guestfs_get_autosync (g))
386 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
393 exit (WEXITSTATUS (r));
396 /* If we've got drives to add, add them now. */
399 /* If we've got mountpoints, we must launch the guest and mount them. */
401 if (launch (g) == -1) exit (EXIT_FAILURE);
405 /* Remote control? */
406 if (remote_control_listen && remote_control) {
408 _("%s: cannot use --listen and --remote options at the same time\n"),
413 if (remote_control_listen) {
416 _("%s: extra parameters on the command line with --listen flag\n"),
422 _("%s: cannot use --listen and --file options at the same time\n"),
429 /* -f (file) parameter? */
432 if (open (file, O_RDONLY) == -1) {
438 /* Interactive, shell script, or command(s) on the command line? */
439 if (optind >= argc) {
446 cmdline (argv, optind, argc);
454 pod2text (const char *name, const char *shortdesc, const char *str)
458 fp = popen ("pod2text", "w");
460 /* pod2text failed, maybe not found, so let's just print the
461 * source instead, since that's better than doing nothing.
463 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
466 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
471 /* List is built in reverse order, so mount them in reverse order. */
473 mount_mps (struct mp *mp)
478 mount_mps (mp->next);
480 /* Don't use guestfs_mount here because that will default to mount
481 * options -o sync,noatime. For more information, see guestfs(3)
482 * section "LIBGUESTFS GOTCHAS".
484 const char *options = read_only ? "ro" : "";
485 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
492 add_drives (struct drv *drv)
497 add_drives (drv->next);
499 r = guestfs_add_drive (g, drv->filename);
501 r = guestfs_add_drive_ro (g, drv->filename);
519 #define FISH "><fs> "
521 static char *line_read = NULL;
526 #ifdef HAVE_LIBREADLINE
534 line_read = readline (prompt ? FISH : "");
536 if (line_read && *line_read)
537 add_history_line (line_read);
542 #endif /* HAVE_LIBREADLINE */
544 static char buf[8192];
547 if (prompt) printf (FISH);
548 line_read = fgets (buf, sizeof buf, stdin);
551 len = strlen (line_read);
552 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
566 int global_exit_on_error = !prompt;
571 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
572 "editing virtual machine filesystems.\n"
574 "Type: 'help' for help with commands\n"
575 " 'quit' to quit the shell\n"
581 exit_on_error = global_exit_on_error;
583 buf = rl_gets (prompt);
589 /* Skip any initial whitespace before the command. */
591 while (*buf && c_isspace (*buf))
596 /* If the next character is '#' then this is a comment. */
597 if (*buf == '#') continue;
599 /* If the next character is '!' then pass the whole lot to system(3). */
607 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
608 WEXITSTATUS (r) != 0)
614 /* If the next character is '-' allow the command to fail without
615 * exiting on error (just for this one command though).
623 /* Get the command (cannot be quoted). */
624 len = strcspn (buf, " \t");
626 if (len == 0) continue;
630 if (buf[len] == '\0') {
637 p += strspn (p, " \t");
639 /* Get the parameters. */
640 while (*p && i < sizeof argv / sizeof argv[0]) {
643 /* Parameters which start with quotes or pipes are treated
644 * specially. Bare parameters are delimited by whitespace.
648 len = strcspn (p, "\"");
649 if (p[len] == '\0') {
650 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
651 if (exit_on_error) exit (EXIT_FAILURE);
654 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
656 _("%s: command arguments not separated by whitespace\n"),
658 if (exit_on_error) exit (EXIT_FAILURE);
662 pend = p[len+1] ? &p[len+2] : &p[len+1];
663 } else if (*p == '\'') {
665 len = strcspn (p, "'");
666 if (p[len] == '\0') {
667 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
668 if (exit_on_error) exit (EXIT_FAILURE);
671 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
673 _("%s: command arguments not separated by whitespace\n"),
675 if (exit_on_error) exit (EXIT_FAILURE);
679 pend = p[len+1] ? &p[len+2] : &p[len+1];
680 } else if (*p == '|') {
685 } else if (*p == '[') {
689 while (*pend && c != 0) {
690 if (*pend == '[') c++;
691 else if (*pend == ']') c--;
696 _("%s: unterminated \"[...]\" sequence\n"), program_name);
697 if (exit_on_error) exit (EXIT_FAILURE);
700 if (*pend && (*pend != ' ' && *pend != '\t')) {
702 _("%s: command arguments not separated by whitespace\n"),
704 if (exit_on_error) exit (EXIT_FAILURE);
709 } else if (*p != ' ' && *p != '\t') {
710 /* If the first character is a ~ then note that this parameter
711 * is a candidate for ~username expansion. NB this does not
712 * apply to quoted parameters.
714 tilde_candidate = *p == '~';
715 len = strcspn (p, " \t");
722 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
727 if (!tilde_candidate)
730 argv[i] = try_tilde_expansion (p);
735 p += strspn (p, " \t");
738 if (i == sizeof argv / sizeof argv[0]) {
739 fprintf (stderr, _("%s: too many arguments\n"), program_name);
740 if (exit_on_error) exit (EXIT_FAILURE);
747 if (issue_command (cmd, argv, pipe) == -1) {
748 if (exit_on_error) exit (EXIT_FAILURE);
753 if (prompt) printf ("\n");
757 cmdline (char *argv[], int optind, int argc)
764 if (optind >= argc) return;
766 cmd = argv[optind++];
767 if (STREQ (cmd, ":")) {
768 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
771 params = &argv[optind];
773 /* Search for end of command list or ":" ... */
774 while (optind < argc && STRNEQ (argv[optind], ":"))
777 if (optind == argc) {
778 if (issue_command (cmd, params, NULL) == -1) exit (EXIT_FAILURE);
781 if (issue_command (cmd, params, NULL) == -1) exit (EXIT_FAILURE);
782 cmdline (argv, optind+1, argc);
787 issue_command (const char *cmd, char *argv[], const char *pipecmd)
790 int stdout_saved_fd = -1;
794 /* This counts the commands issued, starting at 1. */
799 for (i = 0; argv[i] != NULL; ++i)
800 printf (" %s", argv[i]);
804 /* For | ... commands. Annoyingly we can't use popen(3) here. */
808 if (fflush (stdout) == EOF) {
809 perror ("failed to flush standard output");
813 perror ("pipe failed");
822 if (pid == 0) { /* Child process. */
824 if (dup2 (fd[0], 0) < 0) {
825 perror ("dup2 of stdin failed");
829 r = system (pipecmd);
834 _exit (WEXITSTATUS (r));
837 if ((stdout_saved_fd = dup (1)) < 0) {
838 perror ("failed to dup stdout");
842 if (dup2 (fd[1], 1) < 0) {
843 perror ("failed to dup stdout");
844 close (stdout_saved_fd);
850 for (argc = 0; argv[argc] != NULL; ++argc)
853 /* If --remote was set, then send this command to a remote process. */
855 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
857 /* Otherwise execute it locally. */
858 else if (STRCASEEQ (cmd, "help")) {
862 display_command (argv[0]);
865 else if (STRCASEEQ (cmd, "quit") ||
866 STRCASEEQ (cmd, "exit") ||
867 STRCASEEQ (cmd, "q")) {
871 else if (STRCASEEQ (cmd, "alloc") ||
872 STRCASEEQ (cmd, "allocate"))
873 r = do_alloc (cmd, argc, argv);
874 else if (STRCASEEQ (cmd, "echo"))
875 r = do_echo (cmd, argc, argv);
876 else if (STRCASEEQ (cmd, "edit") ||
877 STRCASEEQ (cmd, "vi") ||
878 STRCASEEQ (cmd, "emacs"))
879 r = do_edit (cmd, argc, argv);
880 else if (STRCASEEQ (cmd, "lcd"))
881 r = do_lcd (cmd, argc, argv);
882 else if (STRCASEEQ (cmd, "glob"))
883 r = do_glob (cmd, argc, argv);
884 else if (STRCASEEQ (cmd, "more") ||
885 STRCASEEQ (cmd, "less"))
886 r = do_more (cmd, argc, argv);
887 else if (STRCASEEQ (cmd, "reopen"))
888 r = do_reopen (cmd, argc, argv);
889 else if (STRCASEEQ (cmd, "sparse"))
890 r = do_sparse (cmd, argc, argv);
891 else if (STRCASEEQ (cmd, "time"))
892 r = do_time (cmd, argc, argv);
894 r = run_action (cmd, argc, argv);
896 /* Always flush stdout after every command, so that messages, results
897 * etc appear immediately.
899 if (fflush (stdout) == EOF) {
900 perror ("failed to flush standard output");
906 if (dup2 (stdout_saved_fd, 1) < 0) {
907 perror ("failed to dup2 standard output");
910 close (stdout_saved_fd);
911 if (waitpid (pid, NULL, 0) < 0) {
912 perror ("waiting for command to complete");
921 list_builtin_commands (void)
923 /* help and quit should appear at the top */
924 printf ("%-20s %s\n",
925 "help", _("display a list of commands or help on a command"));
926 printf ("%-20s %s\n",
927 "quit", _("quit guestfish"));
929 printf ("%-20s %s\n",
930 "alloc", _("allocate an image"));
931 printf ("%-20s %s\n",
932 "echo", _("display a line of text"));
933 printf ("%-20s %s\n",
934 "edit", _("edit a file in the image"));
935 printf ("%-20s %s\n",
936 "lcd", _("local change directory"));
937 printf ("%-20s %s\n",
938 "glob", _("expand wildcards in command"));
939 printf ("%-20s %s\n",
940 "more", _("view a file in the pager"));
941 printf ("%-20s %s\n",
942 "reopen", _("close and reopen libguestfs handle"));
943 printf ("%-20s %s\n",
944 "sparse", _("allocate a sparse image file"));
945 printf ("%-20s %s\n",
946 "time", _("measure time taken to run command"));
948 /* actions are printed after this (see list_commands) */
952 display_builtin_command (const char *cmd)
954 /* help for actions is auto-generated, see display_command */
956 if (STRCASEEQ (cmd, "alloc") ||
957 STRCASEEQ (cmd, "allocate"))
958 printf (_("alloc - allocate an image\n"
959 " alloc <filename> <size>\n"
961 " This creates an empty (zeroed) file of the given size,\n"
962 " and then adds so it can be further examined.\n"
964 " For more advanced image creation, see qemu-img utility.\n"
966 " Size can be specified (where <nn> means a number):\n"
967 " <nn> number of kilobytes\n"
968 " eg: 1440 standard 3.5\" floppy\n"
969 " <nn>K or <nn>KB number of kilobytes\n"
970 " <nn>M or <nn>MB number of megabytes\n"
971 " <nn>G or <nn>GB number of gigabytes\n"
972 " <nn>T or <nn>TB number of terabytes\n"
973 " <nn>P or <nn>PB number of petabytes\n"
974 " <nn>E or <nn>EB number of exabytes\n"
975 " <nn>sects number of 512 byte sectors\n"));
976 else if (STRCASEEQ (cmd, "echo"))
977 printf (_("echo - display a line of text\n"
978 " echo [<params> ...]\n"
980 " This echos the parameters to the terminal.\n"));
981 else if (STRCASEEQ (cmd, "edit") ||
982 STRCASEEQ (cmd, "vi") ||
983 STRCASEEQ (cmd, "emacs"))
984 printf (_("edit - edit a file in the image\n"
987 " This is used to edit a file.\n"
989 " It is the equivalent of (and is implemented by)\n"
990 " running \"cat\", editing locally, and then \"write-file\".\n"
992 " Normally it uses $EDITOR, but if you use the aliases\n"
993 " \"vi\" or \"emacs\" you will get those editors.\n"
995 " NOTE: This will not work reliably for large files\n"
996 " (> 2 MB) or binary files containing \\0 bytes.\n"));
997 else if (STRCASEEQ (cmd, "lcd"))
998 printf (_("lcd - local change directory\n"
1001 " Change guestfish's current directory. This command is\n"
1002 " useful if you want to download files to a particular\n"
1004 else if (STRCASEEQ (cmd, "glob"))
1005 printf (_("glob - expand wildcards in command\n"
1006 " glob <command> [<args> ...]\n"
1008 " Glob runs <command> with wildcards expanded in any\n"
1009 " command args. Note that the command is run repeatedly\n"
1010 " once for each expanded argument.\n"));
1011 else if (STRCASEEQ (cmd, "help"))
1012 printf (_("help - display a list of commands or help on a command\n"
1015 else if (STRCASEEQ (cmd, "more") ||
1016 STRCASEEQ (cmd, "less"))
1017 printf (_("more - view a file in the pager\n"
1018 " more <filename>\n"
1020 " This is used to view a file in the pager.\n"
1022 " It is the equivalent of (and is implemented by)\n"
1023 " running \"cat\" and using the pager.\n"
1025 " Normally it uses $PAGER, but if you use the alias\n"
1026 " \"less\" then it always uses \"less\".\n"
1028 " NOTE: This will not work reliably for large files\n"
1029 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1030 else if (STRCASEEQ (cmd, "quit") ||
1031 STRCASEEQ (cmd, "exit") ||
1032 STRCASEEQ (cmd, "q"))
1033 printf (_("quit - quit guestfish\n"
1035 else if (STRCASEEQ (cmd, "reopen"))
1036 printf (_("reopen - close and reopen the libguestfs handle\n"
1039 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1040 "this normally, because the handle is closed properly when guestfish\n"
1041 "exits. However this is occasionally useful for testing.\n"));
1042 else if (STRCASEEQ (cmd, "sparse"))
1043 printf (_("sparse - allocate a sparse image file\n"
1044 " sparse <filename> <size>\n"
1046 " This creates an empty sparse file of the given size,\n"
1047 " and then adds so it can be further examined.\n"
1049 " In all respects it works the same as the 'alloc'\n"
1050 " command, except that the image file is allocated\n"
1051 " sparsely, which means that disk blocks are not assigned\n"
1052 " to the file until they are needed. Sparse disk files\n"
1053 " only use space when written to, but they are slower\n"
1054 " and there is a danger you could run out of real disk\n"
1055 " space during a write operation.\n"
1057 " For more advanced image creation, see qemu-img utility.\n"
1059 " Size can be specified (where <nn> means a number):\n"
1060 " <nn> number of kilobytes\n"
1061 " eg: 1440 standard 3.5\" floppy\n"
1062 " <nn>K or <nn>KB number of kilobytes\n"
1063 " <nn>M or <nn>MB number of megabytes\n"
1064 " <nn>G or <nn>GB number of gigabytes\n"
1065 " <nn>T or <nn>TB number of terabytes\n"
1066 " <nn>P or <nn>PB number of petabytes\n"
1067 " <nn>E or <nn>EB number of exabytes\n"
1068 " <nn>sects number of 512 byte sectors\n"));
1069 else if (STRCASEEQ (cmd, "time"))
1070 printf (_("time - measure time taken to run command\n"
1071 " time <command> [<args> ...]\n"
1073 " This runs <command> as usual, and prints the elapsed\n"
1074 " time afterwards.\n"));
1076 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1080 /* This is printed when the user types in an unknown command for the
1081 * first command issued. A common case is the user doing:
1082 * guestfish disk.img
1083 * expecting guestfish to open 'disk.img' (in fact, this tried to
1084 * run a command 'disk.img').
1087 extended_help_message (void)
1090 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1091 "For a list of commands: guestfish -h\n"
1092 "For complete documentation: man guestfish\n"));
1096 free_strings (char **argv)
1100 for (argc = 0; argv[argc] != NULL; ++argc)
1106 count_strings (char *const *argv)
1110 for (c = 0; argv[c]; ++c)
1116 print_strings (char *const *argv)
1120 for (argc = 0; argv[argc] != NULL; ++argc)
1121 printf ("%s\n", argv[argc]);
1125 print_table (char *const *argv)
1129 for (i = 0; argv[i] != NULL; i += 2)
1130 printf ("%s: %s\n", argv[i], argv[i+1]);
1134 is_true (const char *str)
1137 STRCASENEQ (str, "0") &&
1138 STRCASENEQ (str, "f") &&
1139 STRCASENEQ (str, "false") &&
1140 STRCASENEQ (str, "n") &&
1141 STRCASENEQ (str, "no");
1144 /* Free strings from a non-NULL terminated char** */
1146 free_n_strings (char **str, size_t len)
1150 for (i = 0; i < len; i++) {
1157 parse_string_list (const char *str)
1160 size_t argv_len = 0;
1162 /* Current position pointer */
1163 const char *p = str;
1165 /* Token might be simple:
1168 * 'This is a single token'
1169 * or contain embedded single-quoted sections:
1170 * This' is a sing'l'e to'ken
1172 * The latter may seem over-complicated, but it's what a normal shell does.
1173 * Not doing it risks surprising somebody.
1175 * This outer loop is over complete tokens.
1181 /* Skip leading whitespace */
1182 p += strspn (p, " \t");
1186 /* This loop is over token 'fragments'. A token can be in multiple bits if
1187 * it contains single quotes. We also treat both sides of an escaped quote
1188 * as separate fragments because we can't just copy it: we have to remove
1191 while (*p && (!c_isblank (*p) || in_quote)) {
1192 const char *end = p;
1194 /* Check if the fragment starts with a quote */
1196 /* Toggle in_quote */
1197 in_quote = !in_quote;
1199 /* Skip the quote */
1203 /* If we're in a quote, look for an end quote */
1205 end += strcspn (end, "'");
1208 /* Otherwise, look for whitespace or a quote */
1210 end += strcspn (end, " \t'");
1213 /* Grow the token to accommodate the fragment */
1214 size_t tok_end = tok_len;
1216 char *tok_new = realloc (tok, tok_len + 1);
1217 if (NULL == tok_new) {
1219 free_n_strings (argv, argv_len);
1221 exit (EXIT_FAILURE);
1225 /* Check if we stopped on an escaped quote */
1226 if ('\'' == *end && end != p && *(end-1) == '\\') {
1227 /* Add everything before \' to the token */
1228 memcpy (&tok[tok_end], p, end - p - 1);
1231 tok[tok_len-1] = '\'';
1233 /* Already processed the quote */
1238 /* Add the whole fragment */
1239 memcpy (&tok[tok_end], p, end - p);
1245 /* We've reached the end of a token. We shouldn't still be in quotes. */
1247 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1249 free_n_strings (argv, argv_len);
1254 /* Add this token if there is one. There might not be if there was
1255 * whitespace at the end of the input string */
1257 /* Add the NULL terminator */
1258 tok[tok_len] = '\0';
1260 /* Add the argument to the argument list */
1262 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1263 if (NULL == argv_new) {
1265 free_n_strings (argv, argv_len-1);
1267 exit (EXIT_FAILURE);
1271 argv[argv_len-1] = tok;
1275 /* NULL terminate the argument list */
1277 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1278 if (NULL == argv_new) {
1280 free_n_strings (argv, argv_len-1);
1281 exit (EXIT_FAILURE);
1285 argv[argv_len-1] = NULL;
1290 #ifdef HAVE_LIBREADLINE
1291 static char histfile[1024];
1292 static int nr_history_lines = 0;
1296 initialize_readline (void)
1298 #ifdef HAVE_LIBREADLINE
1301 home = getenv ("HOME");
1303 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1305 (void) read_history (histfile);
1308 rl_readline_name = "guestfish";
1309 rl_attempted_completion_function = do_completion;
1314 cleanup_readline (void)
1316 #ifdef HAVE_LIBREADLINE
1319 if (histfile[0] != '\0') {
1320 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1327 #ifdef HAVE_APPEND_HISTORY
1328 (void) append_history (nr_history_lines, histfile);
1330 (void) write_history (histfile);
1337 add_history_line (const char *line)
1339 #ifdef HAVE_LIBREADLINE
1346 xwrite (int fd, const void *v_buf, size_t len)
1349 const char *buf = v_buf;
1352 r = write (fd, buf, len);
1364 /* Resolve the special "win:..." form for Windows-specific paths.
1365 * This always returns a newly allocated string which is freed by the
1366 * caller function in "cmds.c".
1369 resolve_win_path (const char *path)
1374 if (STRCASENEQLEN (path, "win:", 4)) {
1375 ret = strdup (path);
1383 /* Drop drive letter, if it's "C:". */
1384 if (STRCASEEQLEN (path, "c:", 2))
1394 ret = strdup (path);
1400 /* Blindly convert any backslashes into forward slashes. Is this good? */
1401 for (i = 0; i < strlen (ret); ++i)
1405 char *t = guestfs_case_sensitive_path (g, ret);