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 remote_control_listen = 0;
73 int remote_control = 0;
74 int exit_on_error = 1;
78 launch (guestfs_h *_g)
82 if (guestfs_is_config (g)) {
83 if (guestfs_launch (g) == -1)
89 static void __attribute__((noreturn))
92 if (status != EXIT_SUCCESS)
93 fprintf (stderr, _("Try `%s --help' for more information.\n"),
97 _("%s: guest filesystem shell\n"
98 "%s lets you edit virtual machine filesystems\n"
99 "Copyright (C) 2009 Red Hat Inc.\n"
101 " %s [--options] cmd [: cmd : cmd ...]\n"
102 " %s -i libvirt-domain\n"
103 " %s -i disk-image(s)\n"
104 "or for interactive use:\n"
106 "or from a shell script:\n"
112 " -h|--cmd-help List available commands\n"
113 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
114 " -a|--add image Add image\n"
115 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
116 " -f|--file file Read commands from file\n"
117 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
118 " --listen Listen for remote commands\n"
119 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
120 " -n|--no-sync Don't autosync\n"
121 " --remote[=pid] Send commands to remote %s\n"
122 " -r|--ro Mount read-only\n"
123 " --selinux Enable SELinux support\n"
124 " -v|--verbose Verbose messages\n"
125 " -x Echo each command before executing it\n"
126 " -V|--version Display version and exit\n"
127 "For more information, see the manpage %s(1).\n"),
128 program_name, program_name, program_name,
129 program_name, program_name, program_name,
130 program_name, program_name, program_name);
136 main (int argc, char *argv[])
138 /* Set global program name that is not polluted with libtool artifacts. */
139 set_program_name (argv[0]);
141 atexit (close_stdout);
143 setlocale (LC_ALL, "");
144 bindtextdomain (PACKAGE, LOCALEBASEDIR);
145 textdomain (PACKAGE);
147 enum { HELP_OPTION = CHAR_MAX + 1 };
149 static const char *options = "a:Df:h::im:nrv?Vx";
150 static const struct option long_options[] = {
151 { "add", 1, 0, 'a' },
152 { "cmd-help", 2, 0, 'h' },
153 { "file", 1, 0, 'f' },
154 { "help", 0, 0, HELP_OPTION },
155 { "inspector", 0, 0, 'i' },
156 { "listen", 0, 0, 0 },
157 { "mount", 1, 0, 'm' },
158 { "no-dest-paths", 0, 0, 'D' },
159 { "no-sync", 0, 0, 'n' },
160 { "remote", 2, 0, 0 },
162 { "selinux", 0, 0, 0 },
163 { "verbose", 0, 0, 'v' },
164 { "version", 0, 0, 'V' },
167 struct drv *drvs = NULL;
169 struct mp *mps = NULL;
171 char *p, *file = NULL;
177 initialize_readline ();
179 memset (&sa, 0, sizeof sa);
180 sa.sa_handler = SIG_IGN;
181 sa.sa_flags = SA_RESTART;
182 sigaction (SIGPIPE, &sa, NULL);
184 /* guestfs_create is meant to be a lightweight operation, so
185 * it's OK to do it early here.
187 g = guestfs_create ();
189 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
193 guestfs_set_autosync (g, 1);
195 /* If developing, add ./appliance to the path. Note that libtools
196 * interferes with this because uninstalled guestfish is a shell
197 * script that runs the real program with an absolute path. Detect
200 * BUT if LIBGUESTFS_PATH environment variable is already set by
201 * the user, then don't override it.
203 if (getenv ("LIBGUESTFS_PATH") == NULL &&
205 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
206 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
208 /* CAUTION: we are careful to modify argv[0] here, only after
209 * using it just above.
211 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
212 * of the original, in case it's needed in virt-inspector mode, below.
214 char *real_argv0 = argv[0];
215 argv[0] = bad_cast (program_name);
218 c = getopt_long (argc, argv, options, long_options, &option_index);
222 case 0: /* options which are long only */
223 if (STREQ (long_options[option_index].name, "listen"))
224 remote_control_listen = 1;
225 else if (STREQ (long_options[option_index].name, "remote")) {
227 if (sscanf (optarg, "%d", &remote_control) != 1) {
228 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
229 program_name, optarg);
233 p = getenv ("GUESTFISH_PID");
234 if (!p || sscanf (p, "%d", &remote_control) != 1) {
235 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
236 " to the PID of the remote process\n"),
241 } else if (STREQ (long_options[option_index].name, "selinux")) {
242 guestfs_set_selinux (g, 1);
244 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
245 program_name, long_options[option_index].name, option_index);
251 if (access (optarg, R_OK) != 0) {
255 drv = malloc (sizeof (struct drv));
260 drv->filename = optarg;
266 complete_dest_paths = 0;
271 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
280 display_command (optarg);
281 else if (argv[optind] && argv[optind][0] != '-')
282 display_command (argv[optind++]);
292 mp = malloc (sizeof (struct mp));
297 p = strchr (optarg, ':');
300 mp->mountpoint = p+1;
302 mp->mountpoint = bad_cast ("/");
309 guestfs_set_autosync (g, 0);
318 guestfs_set_verbose (g, verbose);
322 printf ("%s %s\n", program_name, PACKAGE_VERSION);
326 guestfs_set_trace (g, 1);
330 usage (EXIT_SUCCESS);
333 usage (EXIT_FAILURE);
337 /* Inspector mode invalidates most of the other arguments. */
342 if (drvs || mps || remote_control_listen || remote_control ||
343 guestfs_get_selinux (g)) {
344 fprintf (stderr, _("%s: cannot use -i option with -a, -m,"
345 " --listen, --remote or --selinux\n"),
349 if (optind >= argc) {
351 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
356 strcpy (cmd, "a=`virt-inspector");
357 while (optind < argc) {
358 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
361 _("%s: virt-inspector command too long for fixed-size buffer\n"),
366 strcat (cmd, argv[optind]);
372 strcat (cmd, " --ro-fish");
374 strcat (cmd, " --fish");
376 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
378 if (guestfs_get_verbose (g))
380 if (!guestfs_get_autosync (g))
382 if (guestfs_get_trace (g))
387 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
394 exit (WEXITSTATUS (r));
397 /* If we've got drives to add, add them now. */
400 /* If we've got mountpoints, we must launch the guest and mount them. */
402 if (launch (g) == -1) exit (EXIT_FAILURE);
406 /* Remote control? */
407 if (remote_control_listen && remote_control) {
409 _("%s: cannot use --listen and --remote options at the same time\n"),
414 if (remote_control_listen) {
417 _("%s: extra parameters on the command line with --listen flag\n"),
423 _("%s: cannot use --listen and --file options at the same time\n"),
430 /* -f (file) parameter? */
433 if (open (file, O_RDONLY) == -1) {
439 /* Interactive, shell script, or command(s) on the command line? */
440 if (optind >= argc) {
447 cmdline (argv, optind, argc);
455 pod2text (const char *name, const char *shortdesc, const char *str)
459 fp = popen ("pod2text", "w");
461 /* pod2text failed, maybe not found, so let's just print the
462 * source instead, since that's better than doing nothing.
464 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
467 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
472 /* List is built in reverse order, so mount them in reverse order. */
474 mount_mps (struct mp *mp)
479 mount_mps (mp->next);
481 /* Don't use guestfs_mount here because that will default to mount
482 * options -o sync,noatime. For more information, see guestfs(3)
483 * section "LIBGUESTFS GOTCHAS".
485 const char *options = read_only ? "ro" : "";
486 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
493 add_drives (struct drv *drv)
498 add_drives (drv->next);
500 r = guestfs_add_drive (g, drv->filename);
502 r = guestfs_add_drive_ro (g, drv->filename);
520 #define FISH "><fs> "
522 static char *line_read = NULL;
527 #ifdef HAVE_LIBREADLINE
535 line_read = readline (prompt ? FISH : "");
537 if (line_read && *line_read)
538 add_history_line (line_read);
543 #endif /* HAVE_LIBREADLINE */
545 static char buf[8192];
548 if (prompt) printf (FISH);
549 line_read = fgets (buf, sizeof buf, stdin);
552 len = strlen (line_read);
553 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
567 int global_exit_on_error = !prompt;
572 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
573 "editing virtual machine filesystems.\n"
575 "Type: 'help' for help with commands\n"
576 " 'quit' to quit the shell\n"
582 exit_on_error = global_exit_on_error;
584 buf = rl_gets (prompt);
590 /* Skip any initial whitespace before the command. */
592 while (*buf && c_isspace (*buf))
597 /* If the next character is '#' then this is a comment. */
598 if (*buf == '#') continue;
600 /* If the next character is '!' then pass the whole lot to system(3). */
608 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
609 WEXITSTATUS (r) != 0)
615 /* If the next character is '-' allow the command to fail without
616 * exiting on error (just for this one command though).
624 /* Get the command (cannot be quoted). */
625 len = strcspn (buf, " \t");
627 if (len == 0) continue;
631 if (buf[len] == '\0') {
638 p += strspn (p, " \t");
640 /* Get the parameters. */
641 while (*p && i < sizeof argv / sizeof argv[0]) {
644 /* Parameters which start with quotes or pipes are treated
645 * specially. Bare parameters are delimited by whitespace.
649 len = strcspn (p, "\"");
650 if (p[len] == '\0') {
651 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
652 if (exit_on_error) exit (EXIT_FAILURE);
655 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
657 _("%s: command arguments not separated by whitespace\n"),
659 if (exit_on_error) exit (EXIT_FAILURE);
663 pend = p[len+1] ? &p[len+2] : &p[len+1];
664 } else if (*p == '\'') {
666 len = strcspn (p, "'");
667 if (p[len] == '\0') {
668 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
669 if (exit_on_error) exit (EXIT_FAILURE);
672 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
674 _("%s: command arguments not separated by whitespace\n"),
676 if (exit_on_error) exit (EXIT_FAILURE);
680 pend = p[len+1] ? &p[len+2] : &p[len+1];
681 } else if (*p == '|') {
686 } else if (*p == '[') {
690 while (*pend && c != 0) {
691 if (*pend == '[') c++;
692 else if (*pend == ']') c--;
697 _("%s: unterminated \"[...]\" sequence\n"), program_name);
698 if (exit_on_error) exit (EXIT_FAILURE);
701 if (*pend && (*pend != ' ' && *pend != '\t')) {
703 _("%s: command arguments not separated by whitespace\n"),
705 if (exit_on_error) exit (EXIT_FAILURE);
710 } else if (*p != ' ' && *p != '\t') {
711 /* If the first character is a ~ then note that this parameter
712 * is a candidate for ~username expansion. NB this does not
713 * apply to quoted parameters.
715 tilde_candidate = *p == '~';
716 len = strcspn (p, " \t");
723 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
728 if (!tilde_candidate)
731 argv[i] = try_tilde_expansion (p);
736 p += strspn (p, " \t");
739 if (i == sizeof argv / sizeof argv[0]) {
740 fprintf (stderr, _("%s: too many arguments\n"), program_name);
741 if (exit_on_error) exit (EXIT_FAILURE);
748 if (issue_command (cmd, argv, pipe) == -1) {
749 if (exit_on_error) exit (EXIT_FAILURE);
754 if (prompt) printf ("\n");
758 cmdline (char *argv[], int optind, int argc)
765 if (optind >= argc) return;
767 cmd = argv[optind++];
768 if (STREQ (cmd, ":")) {
769 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
773 /* Allow -cmd on the command line to mean (temporarily) override
774 * the normal exit on error (RHBZ#578407).
781 params = &argv[optind];
783 /* Search for end of command list or ":" ... */
784 while (optind < argc && STRNEQ (argv[optind], ":"))
787 if (optind == argc) {
788 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
792 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
794 cmdline (argv, optind+1, argc);
799 issue_command (const char *cmd, char *argv[], const char *pipecmd)
802 int stdout_saved_fd = -1;
806 /* This counts the commands issued, starting at 1. */
809 /* For | ... commands. Annoyingly we can't use popen(3) here. */
813 if (fflush (stdout) == EOF) {
814 perror ("failed to flush standard output");
818 perror ("pipe failed");
827 if (pid == 0) { /* Child process. */
829 if (dup2 (fd[0], 0) < 0) {
830 perror ("dup2 of stdin failed");
834 r = system (pipecmd);
839 _exit (WEXITSTATUS (r));
842 if ((stdout_saved_fd = dup (1)) < 0) {
843 perror ("failed to dup stdout");
847 if (dup2 (fd[1], 1) < 0) {
848 perror ("failed to dup stdout");
849 close (stdout_saved_fd);
855 for (argc = 0; argv[argc] != NULL; ++argc)
858 /* If --remote was set, then send this command to a remote process. */
860 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
862 /* Otherwise execute it locally. */
863 else if (STRCASEEQ (cmd, "help")) {
867 display_command (argv[0]);
870 else if (STRCASEEQ (cmd, "quit") ||
871 STRCASEEQ (cmd, "exit") ||
872 STRCASEEQ (cmd, "q")) {
876 else if (STRCASEEQ (cmd, "alloc") ||
877 STRCASEEQ (cmd, "allocate"))
878 r = do_alloc (cmd, argc, argv);
879 else if (STRCASEEQ (cmd, "echo"))
880 r = do_echo (cmd, argc, argv);
881 else if (STRCASEEQ (cmd, "edit") ||
882 STRCASEEQ (cmd, "vi") ||
883 STRCASEEQ (cmd, "emacs"))
884 r = do_edit (cmd, argc, argv);
885 else if (STRCASEEQ (cmd, "lcd"))
886 r = do_lcd (cmd, argc, argv);
887 else if (STRCASEEQ (cmd, "glob"))
888 r = do_glob (cmd, argc, argv);
889 else if (STRCASEEQ (cmd, "more") ||
890 STRCASEEQ (cmd, "less"))
891 r = do_more (cmd, argc, argv);
892 else if (STRCASEEQ (cmd, "reopen"))
893 r = do_reopen (cmd, argc, argv);
894 else if (STRCASEEQ (cmd, "sparse"))
895 r = do_sparse (cmd, argc, argv);
896 else if (STRCASEEQ (cmd, "time"))
897 r = do_time (cmd, argc, argv);
899 r = run_action (cmd, argc, argv);
901 /* Always flush stdout after every command, so that messages, results
902 * etc appear immediately.
904 if (fflush (stdout) == EOF) {
905 perror ("failed to flush standard output");
911 if (dup2 (stdout_saved_fd, 1) < 0) {
912 perror ("failed to dup2 standard output");
915 close (stdout_saved_fd);
916 if (waitpid (pid, NULL, 0) < 0) {
917 perror ("waiting for command to complete");
926 list_builtin_commands (void)
928 /* help and quit should appear at the top */
929 printf ("%-20s %s\n",
930 "help", _("display a list of commands or help on a command"));
931 printf ("%-20s %s\n",
932 "quit", _("quit guestfish"));
934 printf ("%-20s %s\n",
935 "alloc", _("allocate an image"));
936 printf ("%-20s %s\n",
937 "echo", _("display a line of text"));
938 printf ("%-20s %s\n",
939 "edit", _("edit a file in the image"));
940 printf ("%-20s %s\n",
941 "lcd", _("local change directory"));
942 printf ("%-20s %s\n",
943 "glob", _("expand wildcards in command"));
944 printf ("%-20s %s\n",
945 "more", _("view a file in the pager"));
946 printf ("%-20s %s\n",
947 "reopen", _("close and reopen libguestfs handle"));
948 printf ("%-20s %s\n",
949 "sparse", _("allocate a sparse image file"));
950 printf ("%-20s %s\n",
951 "time", _("measure time taken to run command"));
953 /* actions are printed after this (see list_commands) */
957 display_builtin_command (const char *cmd)
959 /* help for actions is auto-generated, see display_command */
961 if (STRCASEEQ (cmd, "alloc") ||
962 STRCASEEQ (cmd, "allocate"))
963 printf (_("alloc - allocate an image\n"
964 " alloc <filename> <size>\n"
966 " This creates an empty (zeroed) file of the given size,\n"
967 " and then adds so it can be further examined.\n"
969 " For more advanced image creation, see qemu-img utility.\n"
971 " Size can be specified (where <nn> means a number):\n"
972 " <nn> number of kilobytes\n"
973 " eg: 1440 standard 3.5\" floppy\n"
974 " <nn>K or <nn>KB number of kilobytes\n"
975 " <nn>M or <nn>MB number of megabytes\n"
976 " <nn>G or <nn>GB number of gigabytes\n"
977 " <nn>T or <nn>TB number of terabytes\n"
978 " <nn>P or <nn>PB number of petabytes\n"
979 " <nn>E or <nn>EB number of exabytes\n"
980 " <nn>sects number of 512 byte sectors\n"));
981 else if (STRCASEEQ (cmd, "echo"))
982 printf (_("echo - display a line of text\n"
983 " echo [<params> ...]\n"
985 " This echos the parameters to the terminal.\n"));
986 else if (STRCASEEQ (cmd, "edit") ||
987 STRCASEEQ (cmd, "vi") ||
988 STRCASEEQ (cmd, "emacs"))
989 printf (_("edit - edit a file in the image\n"
992 " This is used to edit a file.\n"
994 " It is the equivalent of (and is implemented by)\n"
995 " running \"cat\", editing locally, and then \"write-file\".\n"
997 " Normally it uses $EDITOR, but if you use the aliases\n"
998 " \"vi\" or \"emacs\" you will get those editors.\n"
1000 " NOTE: This will not work reliably for large files\n"
1001 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1002 else if (STRCASEEQ (cmd, "lcd"))
1003 printf (_("lcd - local change directory\n"
1004 " lcd <directory>\n"
1006 " Change guestfish's current directory. This command is\n"
1007 " useful if you want to download files to a particular\n"
1009 else if (STRCASEEQ (cmd, "glob"))
1010 printf (_("glob - expand wildcards in command\n"
1011 " glob <command> [<args> ...]\n"
1013 " Glob runs <command> with wildcards expanded in any\n"
1014 " command args. Note that the command is run repeatedly\n"
1015 " once for each expanded argument.\n"));
1016 else if (STRCASEEQ (cmd, "help"))
1017 printf (_("help - display a list of commands or help on a command\n"
1020 else if (STRCASEEQ (cmd, "more") ||
1021 STRCASEEQ (cmd, "less"))
1022 printf (_("more - view a file in the pager\n"
1023 " more <filename>\n"
1025 " This is used to view a file in the pager.\n"
1027 " It is the equivalent of (and is implemented by)\n"
1028 " running \"cat\" and using the pager.\n"
1030 " Normally it uses $PAGER, but if you use the alias\n"
1031 " \"less\" then it always uses \"less\".\n"
1033 " NOTE: This will not work reliably for large files\n"
1034 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1035 else if (STRCASEEQ (cmd, "quit") ||
1036 STRCASEEQ (cmd, "exit") ||
1037 STRCASEEQ (cmd, "q"))
1038 printf (_("quit - quit guestfish\n"
1040 else if (STRCASEEQ (cmd, "reopen"))
1041 printf (_("reopen - close and reopen the libguestfs handle\n"
1044 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1045 "this normally, because the handle is closed properly when guestfish\n"
1046 "exits. However this is occasionally useful for testing.\n"));
1047 else if (STRCASEEQ (cmd, "sparse"))
1048 printf (_("sparse - allocate a sparse image file\n"
1049 " sparse <filename> <size>\n"
1051 " This creates an empty sparse file of the given size,\n"
1052 " and then adds so it can be further examined.\n"
1054 " In all respects it works the same as the 'alloc'\n"
1055 " command, except that the image file is allocated\n"
1056 " sparsely, which means that disk blocks are not assigned\n"
1057 " to the file until they are needed. Sparse disk files\n"
1058 " only use space when written to, but they are slower\n"
1059 " and there is a danger you could run out of real disk\n"
1060 " space during a write operation.\n"
1062 " For more advanced image creation, see qemu-img utility.\n"
1064 " Size can be specified (where <nn> means a number):\n"
1065 " <nn> number of kilobytes\n"
1066 " eg: 1440 standard 3.5\" floppy\n"
1067 " <nn>K or <nn>KB number of kilobytes\n"
1068 " <nn>M or <nn>MB number of megabytes\n"
1069 " <nn>G or <nn>GB number of gigabytes\n"
1070 " <nn>T or <nn>TB number of terabytes\n"
1071 " <nn>P or <nn>PB number of petabytes\n"
1072 " <nn>E or <nn>EB number of exabytes\n"
1073 " <nn>sects number of 512 byte sectors\n"));
1074 else if (STRCASEEQ (cmd, "time"))
1075 printf (_("time - measure time taken to run command\n"
1076 " time <command> [<args> ...]\n"
1078 " This runs <command> as usual, and prints the elapsed\n"
1079 " time afterwards.\n"));
1081 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1085 /* This is printed when the user types in an unknown command for the
1086 * first command issued. A common case is the user doing:
1087 * guestfish disk.img
1088 * expecting guestfish to open 'disk.img' (in fact, this tried to
1089 * run a command 'disk.img').
1092 extended_help_message (void)
1095 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1096 "For a list of commands: guestfish -h\n"
1097 "For complete documentation: man guestfish\n"));
1101 free_strings (char **argv)
1105 for (argc = 0; argv[argc] != NULL; ++argc)
1111 count_strings (char *const *argv)
1115 for (c = 0; argv[c]; ++c)
1121 print_strings (char *const *argv)
1125 for (argc = 0; argv[argc] != NULL; ++argc)
1126 printf ("%s\n", argv[argc]);
1130 print_table (char *const *argv)
1134 for (i = 0; argv[i] != NULL; i += 2)
1135 printf ("%s: %s\n", argv[i], argv[i+1]);
1139 is_true (const char *str)
1142 STRCASENEQ (str, "0") &&
1143 STRCASENEQ (str, "f") &&
1144 STRCASENEQ (str, "false") &&
1145 STRCASENEQ (str, "n") &&
1146 STRCASENEQ (str, "no");
1149 /* Free strings from a non-NULL terminated char** */
1151 free_n_strings (char **str, size_t len)
1155 for (i = 0; i < len; i++) {
1162 parse_string_list (const char *str)
1165 size_t argv_len = 0;
1167 /* Current position pointer */
1168 const char *p = str;
1170 /* Token might be simple:
1173 * 'This is a single token'
1174 * or contain embedded single-quoted sections:
1175 * This' is a sing'l'e to'ken
1177 * The latter may seem over-complicated, but it's what a normal shell does.
1178 * Not doing it risks surprising somebody.
1180 * This outer loop is over complete tokens.
1186 /* Skip leading whitespace */
1187 p += strspn (p, " \t");
1191 /* This loop is over token 'fragments'. A token can be in multiple bits if
1192 * it contains single quotes. We also treat both sides of an escaped quote
1193 * as separate fragments because we can't just copy it: we have to remove
1196 while (*p && (!c_isblank (*p) || in_quote)) {
1197 const char *end = p;
1199 /* Check if the fragment starts with a quote */
1201 /* Toggle in_quote */
1202 in_quote = !in_quote;
1204 /* Skip the quote */
1208 /* If we're in a quote, look for an end quote */
1210 end += strcspn (end, "'");
1213 /* Otherwise, look for whitespace or a quote */
1215 end += strcspn (end, " \t'");
1218 /* Grow the token to accommodate the fragment */
1219 size_t tok_end = tok_len;
1221 char *tok_new = realloc (tok, tok_len + 1);
1222 if (NULL == tok_new) {
1224 free_n_strings (argv, argv_len);
1226 exit (EXIT_FAILURE);
1230 /* Check if we stopped on an escaped quote */
1231 if ('\'' == *end && end != p && *(end-1) == '\\') {
1232 /* Add everything before \' to the token */
1233 memcpy (&tok[tok_end], p, end - p - 1);
1236 tok[tok_len-1] = '\'';
1238 /* Already processed the quote */
1243 /* Add the whole fragment */
1244 memcpy (&tok[tok_end], p, end - p);
1250 /* We've reached the end of a token. We shouldn't still be in quotes. */
1252 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1254 free_n_strings (argv, argv_len);
1259 /* Add this token if there is one. There might not be if there was
1260 * whitespace at the end of the input string */
1262 /* Add the NULL terminator */
1263 tok[tok_len] = '\0';
1265 /* Add the argument to the argument list */
1267 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1268 if (NULL == argv_new) {
1270 free_n_strings (argv, argv_len-1);
1272 exit (EXIT_FAILURE);
1276 argv[argv_len-1] = tok;
1280 /* NULL terminate the argument list */
1282 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1283 if (NULL == argv_new) {
1285 free_n_strings (argv, argv_len-1);
1286 exit (EXIT_FAILURE);
1290 argv[argv_len-1] = NULL;
1295 #ifdef HAVE_LIBREADLINE
1296 static char histfile[1024];
1297 static int nr_history_lines = 0;
1301 initialize_readline (void)
1303 #ifdef HAVE_LIBREADLINE
1306 home = getenv ("HOME");
1308 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1310 (void) read_history (histfile);
1313 rl_readline_name = "guestfish";
1314 rl_attempted_completion_function = do_completion;
1319 cleanup_readline (void)
1321 #ifdef HAVE_LIBREADLINE
1324 if (histfile[0] != '\0') {
1325 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1332 #ifdef HAVE_APPEND_HISTORY
1333 (void) append_history (nr_history_lines, histfile);
1335 (void) write_history (histfile);
1342 add_history_line (const char *line)
1344 #ifdef HAVE_LIBREADLINE
1351 xwrite (int fd, const void *v_buf, size_t len)
1354 const char *buf = v_buf;
1357 r = write (fd, buf, len);
1369 /* Resolve the special "win:..." form for Windows-specific paths.
1370 * This always returns a newly allocated string which is freed by the
1371 * caller function in "cmds.c".
1374 resolve_win_path (const char *path)
1379 if (STRCASENEQLEN (path, "win:", 4)) {
1380 ret = strdup (path);
1388 /* Drop drive letter, if it's "C:". */
1389 if (STRCASEEQLEN (path, "c:", 2))
1399 ret = strdup (path);
1405 /* Blindly convert any backslashes into forward slashes. Is this good? */
1406 for (i = 0; i < strlen (ret); ++i)
1410 char *t = guestfs_case_sensitive_path (g, ret);