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>
32 #ifdef HAVE_LIBREADLINE
33 #include <readline/readline.h>
34 #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)
88 static void __attribute__((noreturn))
91 if (status != EXIT_SUCCESS)
92 fprintf (stderr, _("Try `%s --help' for more information.\n"),
96 _("%s: guest filesystem shell\n"
97 "%s lets you edit virtual machine filesystems\n"
98 "Copyright (C) 2009 Red Hat Inc.\n"
100 " %s [--options] cmd [: cmd : cmd ...]\n"
101 " %s -i libvirt-domain\n"
102 " %s -i disk-image(s)\n"
103 "or for interactive use:\n"
105 "or from a shell script:\n"
111 " -h|--cmd-help List available commands\n"
112 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
113 " -a|--add image Add image\n"
114 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
115 " -f|--file file Read commands from file\n"
116 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
117 " --listen Listen for remote commands\n"
118 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
119 " -n|--no-sync Don't autosync\n"
120 " --remote[=pid] Send commands to remote %s\n"
121 " -r|--ro Mount read-only\n"
122 " --selinux Enable SELinux support\n"
123 " -v|--verbose Verbose messages\n"
124 " -x Echo each command before executing it\n"
125 " -V|--version Display version and exit\n"
126 "For more information, see the manpage %s(1).\n"),
127 program_name, program_name, program_name,
128 program_name, program_name, program_name,
129 program_name, program_name, program_name);
135 main (int argc, char *argv[])
137 /* Set global program name that is not polluted with libtool artifacts. */
138 set_program_name (argv[0]);
140 atexit (close_stdout);
142 enum { HELP_OPTION = CHAR_MAX + 1 };
144 static const char *options = "a:Df:h::im:nrv?Vx";
145 static const struct option long_options[] = {
146 { "add", 1, 0, 'a' },
147 { "cmd-help", 2, 0, 'h' },
148 { "file", 1, 0, 'f' },
149 { "help", 0, 0, HELP_OPTION },
150 { "inspector", 0, 0, 'i' },
151 { "listen", 0, 0, 0 },
152 { "mount", 1, 0, 'm' },
153 { "no-dest-paths", 0, 0, 'D' },
154 { "no-sync", 0, 0, 'n' },
155 { "remote", 2, 0, 0 },
157 { "selinux", 0, 0, 0 },
158 { "verbose", 0, 0, 'v' },
159 { "version", 0, 0, 'V' },
162 struct drv *drvs = NULL;
164 struct mp *mps = NULL;
166 char *p, *file = NULL;
172 initialize_readline ();
174 memset (&sa, 0, sizeof sa);
175 sa.sa_handler = SIG_IGN;
176 sa.sa_flags = SA_RESTART;
177 sigaction (SIGPIPE, &sa, NULL);
179 /* guestfs_create is meant to be a lightweight operation, so
180 * it's OK to do it early here.
182 g = guestfs_create ();
184 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
188 guestfs_set_autosync (g, 1);
190 /* If developing, add ./appliance to the path. Note that libtools
191 * interferes with this because uninstalled guestfish is a shell
192 * script that runs the real program with an absolute path. Detect
195 * BUT if LIBGUESTFS_PATH environment variable is already set by
196 * the user, then don't override it.
198 if (getenv ("LIBGUESTFS_PATH") == NULL &&
200 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
201 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
203 /* CAUTION: we are careful to modify argv[0] here, only after
204 * using it just above.
206 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
207 * of the original, in case it's needed in virt-inspector mode, below.
209 char *real_argv0 = argv[0];
210 argv[0] = bad_cast (program_name);
213 c = getopt_long (argc, argv, options, long_options, &option_index);
217 case 0: /* options which are long only */
218 if (strcmp (long_options[option_index].name, "listen") == 0)
219 remote_control_listen = 1;
220 else if (strcmp (long_options[option_index].name, "remote") == 0) {
222 if (sscanf (optarg, "%d", &remote_control) != 1) {
223 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
224 program_name, optarg);
228 p = getenv ("GUESTFISH_PID");
229 if (!p || sscanf (p, "%d", &remote_control) != 1) {
230 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
231 " to the PID of the remote process\n"),
236 } else if (strcmp (long_options[option_index].name, "selinux") == 0) {
237 guestfs_set_selinux (g, 1);
239 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
240 program_name, long_options[option_index].name, option_index);
246 if (access (optarg, R_OK) != 0) {
250 drv = malloc (sizeof (struct drv));
255 drv->filename = optarg;
261 complete_dest_paths = 0;
266 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
275 display_command (optarg);
276 else if (argv[optind] && argv[optind][0] != '-')
277 display_command (argv[optind++]);
287 mp = malloc (sizeof (struct mp));
292 p = strchr (optarg, ':');
295 mp->mountpoint = p+1;
297 mp->mountpoint = bad_cast ("/");
304 guestfs_set_autosync (g, 0);
313 guestfs_set_verbose (g, verbose);
317 printf ("%s %s\n", program_name, PACKAGE_VERSION);
332 /* Inspector mode invalidates most of the other arguments. */
337 if (drvs || mps || remote_control_listen || remote_control ||
338 guestfs_get_selinux (g)) {
339 fprintf (stderr, _("%s: cannot use -i option with -a, -m,"
340 " --listen, --remote or --selinux\n"),
344 if (optind >= argc) {
346 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
351 strcpy (cmd, "a=`virt-inspector");
352 while (optind < argc) {
353 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
356 _("%s: virt-inspector command too long for fixed-size buffer\n"),
361 strcat (cmd, argv[optind]);
367 strcat (cmd, " --ro-fish");
369 strcat (cmd, " --fish");
371 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
373 if (guestfs_get_verbose (g))
375 if (!guestfs_get_autosync (g))
380 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
387 exit (WEXITSTATUS (r));
390 /* If we've got drives to add, add them now. */
393 /* If we've got mountpoints, we must launch the guest and mount them. */
395 if (launch (g) == -1) exit (1);
399 /* Remote control? */
400 if (remote_control_listen && remote_control) {
402 _("%s: cannot use --listen and --remote options at the same time\n"),
407 if (remote_control_listen) {
410 _("%s: extra parameters on the command line with --listen flag\n"),
416 _("%s: cannot use --listen and --file options at the same time\n"),
423 /* -f (file) parameter? */
426 if (open (file, O_RDONLY) == -1) {
432 /* Interactive, shell script, or command(s) on the command line? */
433 if (optind >= argc) {
440 cmdline (argv, optind, argc);
448 pod2text (const char *name, const char *shortdesc, const char *str)
452 fp = popen ("pod2text", "w");
454 /* pod2text failed, maybe not found, so let's just print the
455 * source instead, since that's better than doing nothing.
457 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
460 fprintf (fp, "=head1 %s - %s\n\n", name, shortdesc);
465 /* List is built in reverse order, so mount them in reverse order. */
467 mount_mps (struct mp *mp)
472 mount_mps (mp->next);
474 r = guestfs_mount (g, mp->device, mp->mountpoint);
476 r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
483 add_drives (struct drv *drv)
488 add_drives (drv->next);
490 r = guestfs_add_drive (g, drv->filename);
492 r = guestfs_add_drive_ro (g, drv->filename);
510 #define FISH "><fs> "
512 static char *line_read = NULL;
517 #ifdef HAVE_LIBREADLINE
525 line_read = readline (prompt ? FISH : "");
527 if (line_read && *line_read)
528 add_history_line (line_read);
533 #endif /* HAVE_LIBREADLINE */
535 static char buf[8192];
538 if (prompt) printf (FISH);
539 line_read = fgets (buf, sizeof buf, stdin);
542 len = strlen (line_read);
543 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
557 int global_exit_on_error = !prompt;
562 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
563 "editing virtual machine filesystems.\n"
565 "Type: 'help' for help with commands\n"
566 " 'quit' to quit the shell\n"
572 exit_on_error = global_exit_on_error;
574 buf = rl_gets (prompt);
580 /* Skip any initial whitespace before the command. */
582 while (*buf && c_isspace (*buf))
587 /* If the next character is '#' then this is a comment. */
588 if (*buf == '#') continue;
590 /* If the next character is '!' then pass the whole lot to system(3). */
598 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
599 WEXITSTATUS (r) != 0)
605 /* If the next character is '-' allow the command to fail without
606 * exiting on error (just for this one command though).
614 /* Get the command (cannot be quoted). */
615 len = strcspn (buf, " \t");
617 if (len == 0) continue;
621 if (buf[len] == '\0') {
628 p += strspn (p, " \t");
630 /* Get the parameters. */
631 while (*p && i < sizeof argv / sizeof argv[0]) {
634 /* Parameters which start with quotes or pipes are treated
635 * specially. Bare parameters are delimited by whitespace.
639 len = strcspn (p, "\"");
640 if (p[len] == '\0') {
641 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
642 if (exit_on_error) exit (1);
645 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
647 _("%s: command arguments not separated by whitespace\n"),
649 if (exit_on_error) exit (1);
653 pend = p[len+1] ? &p[len+2] : &p[len+1];
654 } else if (*p == '\'') {
656 len = strcspn (p, "'");
657 if (p[len] == '\0') {
658 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
659 if (exit_on_error) exit (1);
662 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
664 _("%s: command arguments not separated by whitespace\n"),
666 if (exit_on_error) exit (1);
670 pend = p[len+1] ? &p[len+2] : &p[len+1];
671 } else if (*p == '|') {
676 } else if (*p == '[') {
680 while (*pend && c != 0) {
681 if (*pend == '[') c++;
682 else if (*pend == ']') c--;
687 _("%s: unterminated \"[...]\" sequence\n"), program_name);
688 if (exit_on_error) exit (1);
691 if (*pend && (*pend != ' ' && *pend != '\t')) {
693 _("%s: command arguments not separated by whitespace\n"),
695 if (exit_on_error) exit (1);
700 } else if (*p != ' ' && *p != '\t') {
701 /* If the first character is a ~ then note that this parameter
702 * is a candidate for ~username expansion. NB this does not
703 * apply to quoted parameters.
705 tilde_candidate = *p == '~';
706 len = strcspn (p, " \t");
713 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
718 if (!tilde_candidate)
721 argv[i] = try_tilde_expansion (p);
726 p += strspn (p, " \t");
729 if (i == sizeof argv / sizeof argv[0]) {
730 fprintf (stderr, _("%s: too many arguments\n"), program_name);
731 if (exit_on_error) exit (1);
738 if (issue_command (cmd, argv, pipe) == -1) {
739 if (exit_on_error) exit (1);
744 if (prompt) printf ("\n");
748 cmdline (char *argv[], int optind, int argc)
755 if (optind >= argc) return;
757 cmd = argv[optind++];
758 if (strcmp (cmd, ":") == 0) {
759 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
762 params = &argv[optind];
764 /* Search for end of command list or ":" ... */
765 while (optind < argc && strcmp (argv[optind], ":") != 0)
768 if (optind == argc) {
769 if (issue_command (cmd, params, NULL) == -1) exit (1);
772 if (issue_command (cmd, params, NULL) == -1) exit (1);
773 cmdline (argv, optind+1, argc);
778 issue_command (const char *cmd, char *argv[], const char *pipecmd)
781 int stdout_saved_fd = -1;
787 for (i = 0; argv[i] != NULL; ++i)
788 printf (" %s", argv[i]);
792 /* For | ... commands. Annoyingly we can't use popen(3) here. */
796 if (fflush (stdout) == EOF) {
797 perror ("failed to flush standard output");
801 perror ("pipe failed");
810 if (pid == 0) { /* Child process. */
812 if (dup2 (fd[0], 0) < 0) {
813 perror ("dup2 of stdin failed");
817 r = system (pipecmd);
822 _exit (WEXITSTATUS (r));
825 if ((stdout_saved_fd = dup (1)) < 0) {
826 perror ("failed to dup stdout");
830 if (dup2 (fd[1], 1) < 0) {
831 perror ("failed to dup stdout");
832 close (stdout_saved_fd);
838 for (argc = 0; argv[argc] != NULL; ++argc)
841 /* If --remote was set, then send this command to a remote process. */
843 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
845 /* Otherwise execute it locally. */
846 else if (strcasecmp (cmd, "help") == 0) {
850 display_command (argv[0]);
853 else if (strcasecmp (cmd, "quit") == 0 ||
854 strcasecmp (cmd, "exit") == 0 ||
855 strcasecmp (cmd, "q") == 0) {
859 else if (strcasecmp (cmd, "alloc") == 0 ||
860 strcasecmp (cmd, "allocate") == 0)
861 r = do_alloc (cmd, argc, argv);
862 else if (strcasecmp (cmd, "echo") == 0)
863 r = do_echo (cmd, argc, argv);
864 else if (strcasecmp (cmd, "edit") == 0 ||
865 strcasecmp (cmd, "vi") == 0 ||
866 strcasecmp (cmd, "emacs") == 0)
867 r = do_edit (cmd, argc, argv);
868 else if (strcasecmp (cmd, "lcd") == 0)
869 r = do_lcd (cmd, argc, argv);
870 else if (strcasecmp (cmd, "glob") == 0)
871 r = do_glob (cmd, argc, argv);
872 else if (strcasecmp (cmd, "more") == 0 ||
873 strcasecmp (cmd, "less") == 0)
874 r = do_more (cmd, argc, argv);
875 else if (strcasecmp (cmd, "reopen") == 0)
876 r = do_reopen (cmd, argc, argv);
877 else if (strcasecmp (cmd, "sparse") == 0)
878 r = do_sparse (cmd, argc, argv);
879 else if (strcasecmp (cmd, "time") == 0)
880 r = do_time (cmd, argc, argv);
882 r = run_action (cmd, argc, argv);
884 /* Always flush stdout after every command, so that messages, results
885 * etc appear immediately.
887 if (fflush (stdout) == EOF) {
888 perror ("failed to flush standard output");
894 if (dup2 (stdout_saved_fd, 1) < 0) {
895 perror ("failed to dup2 standard output");
898 close (stdout_saved_fd);
899 if (waitpid (pid, NULL, 0) < 0) {
900 perror ("waiting for command to complete");
909 list_builtin_commands (void)
911 /* help and quit should appear at the top */
912 printf ("%-20s %s\n",
913 "help", _("display a list of commands or help on a command"));
914 printf ("%-20s %s\n",
915 "quit", _("quit guestfish"));
917 printf ("%-20s %s\n",
918 "alloc", _("allocate an image"));
919 printf ("%-20s %s\n",
920 "echo", _("display a line of text"));
921 printf ("%-20s %s\n",
922 "edit", _("edit a file in the image"));
923 printf ("%-20s %s\n",
924 "lcd", _("local change directory"));
925 printf ("%-20s %s\n",
926 "glob", _("expand wildcards in command"));
927 printf ("%-20s %s\n",
928 "more", _("view a file in the pager"));
929 printf ("%-20s %s\n",
930 "reopen", _("close and reopen libguestfs handle"));
931 printf ("%-20s %s\n",
932 "sparse", _("allocate a sparse image file"));
933 printf ("%-20s %s\n",
934 "time", _("measure time taken to run command"));
936 /* actions are printed after this (see list_commands) */
940 display_builtin_command (const char *cmd)
942 /* help for actions is auto-generated, see display_command */
944 if (strcasecmp (cmd, "alloc") == 0 ||
945 strcasecmp (cmd, "allocate") == 0)
946 printf (_("alloc - allocate an image\n"
947 " alloc <filename> <size>\n"
949 " This creates an empty (zeroed) file of the given size,\n"
950 " and then adds so it can be further examined.\n"
952 " For more advanced image creation, see qemu-img utility.\n"
954 " Size can be specified (where <nn> means a number):\n"
955 " <nn> number of kilobytes\n"
956 " eg: 1440 standard 3.5\" floppy\n"
957 " <nn>K or <nn>KB number of kilobytes\n"
958 " <nn>M or <nn>MB number of megabytes\n"
959 " <nn>G or <nn>GB number of gigabytes\n"
960 " <nn>T or <nn>TB number of terabytes\n"
961 " <nn>sects number of 512 byte sectors\n"));
962 else if (strcasecmp (cmd, "echo") == 0)
963 printf (_("echo - display a line of text\n"
964 " echo [<params> ...]\n"
966 " This echos the parameters to the terminal.\n"));
967 else if (strcasecmp (cmd, "edit") == 0 ||
968 strcasecmp (cmd, "vi") == 0 ||
969 strcasecmp (cmd, "emacs") == 0)
970 printf (_("edit - edit a file in the image\n"
973 " This is used to edit a file.\n"
975 " It is the equivalent of (and is implemented by)\n"
976 " running \"cat\", editing locally, and then \"write-file\".\n"
978 " Normally it uses $EDITOR, but if you use the aliases\n"
979 " \"vi\" or \"emacs\" you will get those editors.\n"
981 " NOTE: This will not work reliably for large files\n"
982 " (> 2 MB) or binary files containing \\0 bytes.\n"));
983 else if (strcasecmp (cmd, "lcd") == 0)
984 printf (_("lcd - local change directory\n"
987 " Change guestfish's current directory. This command is\n"
988 " useful if you want to download files to a particular\n"
990 else if (strcasecmp (cmd, "glob") == 0)
991 printf (_("glob - expand wildcards in command\n"
992 " glob <command> [<args> ...]\n"
994 " Glob runs <command> with wildcards expanded in any\n"
995 " command args. Note that the command is run repeatedly\n"
996 " once for each expanded argument.\n"));
997 else if (strcasecmp (cmd, "help") == 0)
998 printf (_("help - display a list of commands or help on a command\n"
1001 else if (strcasecmp (cmd, "more") == 0 ||
1002 strcasecmp (cmd, "less") == 0)
1003 printf (_("more - view a file in the pager\n"
1004 " more <filename>\n"
1006 " This is used to view a file in the pager.\n"
1008 " It is the equivalent of (and is implemented by)\n"
1009 " running \"cat\" and using the pager.\n"
1011 " Normally it uses $PAGER, but if you use the alias\n"
1012 " \"less\" then it always uses \"less\".\n"
1014 " NOTE: This will not work reliably for large files\n"
1015 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1016 else if (strcasecmp (cmd, "quit") == 0 ||
1017 strcasecmp (cmd, "exit") == 0 ||
1018 strcasecmp (cmd, "q") == 0)
1019 printf (_("quit - quit guestfish\n"
1021 else if (strcasecmp (cmd, "reopen") == 0)
1022 printf (_("reopen - close and reopen the libguestfs handle\n"
1025 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1026 "this normally, because the handle is closed properly when guestfish\n"
1027 "exits. However this is occasionally useful for testing.\n"));
1028 else if (strcasecmp (cmd, "sparse") == 0)
1029 printf (_("sparse - allocate a sparse image file\n"
1030 " sparse <filename> <size>\n"
1032 " This creates an empty sparse file of the given size,\n"
1033 " and then adds so it can be further examined.\n"
1035 " In all respects it works the same as the 'alloc'\n"
1036 " command, except that the image file is allocated\n"
1037 " sparsely, which means that disk blocks are not assigned\n"
1038 " to the file until they are needed. Sparse disk files\n"
1039 " only use space when written to, but they are slower\n"
1040 " and there is a danger you could run out of real disk\n"
1041 " space during a write operation.\n"
1043 " For more advanced image creation, see qemu-img utility.\n"
1045 " Size can be specified (where <nn> means a number):\n"
1046 " <nn> number of kilobytes\n"
1047 " eg: 1440 standard 3.5\" floppy\n"
1048 " <nn>K or <nn>KB number of kilobytes\n"
1049 " <nn>M or <nn>MB number of megabytes\n"
1050 " <nn>G or <nn>GB number of gigabytes\n"
1051 " <nn>T or <nn>TB number of terabytes\n"
1052 " <nn>sects number of 512 byte sectors\n"));
1053 else if (strcasecmp (cmd, "time") == 0)
1054 printf (_("time - measure time taken to run command\n"
1055 " time <command> [<args> ...]\n"
1057 " This runs <command> as usual, and prints the elapsed\n"
1058 " time afterwards.\n"));
1060 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1065 free_strings (char **argv)
1069 for (argc = 0; argv[argc] != NULL; ++argc)
1075 count_strings (char *const *argv)
1079 for (c = 0; argv[c]; ++c)
1085 print_strings (char *const *argv)
1089 for (argc = 0; argv[argc] != NULL; ++argc)
1090 printf ("%s\n", argv[argc]);
1094 print_table (char *const *argv)
1098 for (i = 0; argv[i] != NULL; i += 2)
1099 printf ("%s: %s\n", argv[i], argv[i+1]);
1103 is_true (const char *str)
1106 strcasecmp (str, "0") != 0 &&
1107 strcasecmp (str, "f") != 0 &&
1108 strcasecmp (str, "false") != 0 &&
1109 strcasecmp (str, "n") != 0 &&
1110 strcasecmp (str, "no") != 0;
1113 /* Free strings from a non-NULL terminated char** */
1115 free_n_strings (char **str, size_t len)
1119 for (i = 0; i < len; i++) {
1126 parse_string_list (const char *str)
1129 size_t argv_len = 0;
1131 /* Current position pointer */
1132 const char *p = str;
1134 /* Token might be simple:
1137 * 'This is a single token'
1138 * or contain embedded single-quoted sections:
1139 * This' is a sing'l'e to'ken
1141 * The latter may seem over-complicated, but it's what a normal shell does.
1142 * Not doing it risks surprising somebody.
1144 * This outer loop is over complete tokens.
1150 /* Skip leading whitespace */
1151 p += strspn (p, " \t");
1155 /* This loop is over token 'fragments'. A token can be in multiple bits if
1156 * it contains single quotes. We also treat both sides of an escaped quote
1157 * as separate fragments because we can't just copy it: we have to remove
1160 while (*p && (!c_isblank (*p) || in_quote)) {
1161 const char *end = p;
1163 /* Check if the fragment starts with a quote */
1165 /* Toggle in_quote */
1166 in_quote = !in_quote;
1168 /* Skip the quote */
1172 /* If we're in a quote, look for an end quote */
1174 end += strcspn (end, "'");
1177 /* Otherwise, look for whitespace or a quote */
1179 end += strcspn (end, " \t'");
1182 /* Grow the token to accommodate the fragment */
1183 size_t tok_end = tok_len;
1185 char *tok_new = realloc (tok, tok_len + 1);
1186 if (NULL == tok_new) {
1188 free_n_strings (argv, argv_len);
1194 /* Check if we stopped on an escaped quote */
1195 if ('\'' == *end && end != p && *(end-1) == '\\') {
1196 /* Add everything before \' to the token */
1197 memcpy (&tok[tok_end], p, end - p - 1);
1200 tok[tok_len-1] = '\'';
1202 /* Already processed the quote */
1207 /* Add the whole fragment */
1208 memcpy (&tok[tok_end], p, end - p);
1214 /* We've reached the end of a token. We shouldn't still be in quotes. */
1216 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1218 free_n_strings (argv, argv_len);
1223 /* Add this token if there is one. There might not be if there was
1224 * whitespace at the end of the input string */
1226 /* Add the NULL terminator */
1227 tok[tok_len] = '\0';
1229 /* Add the argument to the argument list */
1231 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1232 if (NULL == argv_new) {
1234 free_n_strings (argv, argv_len-1);
1240 argv[argv_len-1] = tok;
1244 /* NULL terminate the argument list */
1246 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1247 if (NULL == argv_new) {
1249 free_n_strings (argv, argv_len-1);
1254 argv[argv_len-1] = NULL;
1259 #ifdef HAVE_LIBREADLINE
1260 static char histfile[1024];
1261 static int nr_history_lines = 0;
1265 initialize_readline (void)
1267 #ifdef HAVE_LIBREADLINE
1270 home = getenv ("HOME");
1272 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1274 (void) read_history (histfile);
1277 rl_readline_name = "guestfish";
1278 rl_attempted_completion_function = do_completion;
1283 cleanup_readline (void)
1285 #ifdef HAVE_LIBREADLINE
1288 if (histfile[0] != '\0') {
1289 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1296 (void) append_history (nr_history_lines, histfile);
1302 add_history_line (const char *line)
1304 #ifdef HAVE_LIBREADLINE
1311 xwrite (int fd, const void *v_buf, size_t len)
1314 const char *buf = v_buf;
1317 r = write (fd, buf, len);
1329 /* Resolve the special "win:..." form for Windows-specific paths.
1330 * This always returns a newly allocated string which is freed by the
1331 * caller function in "cmds.c".
1334 resolve_win_path (const char *path)
1339 if (strncasecmp (path, "win:", 4) != 0) {
1340 ret = strdup (path);
1348 /* Drop drive letter, if it's "C:". */
1349 if (strncasecmp (path, "c:", 2) == 0)
1359 ret = strdup (path);
1365 /* Blindly convert any backslashes into forward slashes. Is this good? */
1366 for (i = 0; i < strlen (ret); ++i)
1370 char *t = guestfs_case_sensitive_path (g, ret);