1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2011 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>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
48 /* Return from parse_command_line. See description below. */
49 struct parsed_command {
56 static void user_cancel (int);
57 static void set_up_terminal (void);
58 static void prepare_drives (struct drv *drv);
59 static int launch (void);
60 static void interactive (void);
61 static void shell_script (void);
62 static void script (int prompt);
63 static void cmdline (char *argv[], int optind, int argc);
64 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
65 static int parse_quoted_string (char *p);
66 static int execute_and_inline (const char *cmd, int exit_on_error);
67 static void initialize_readline (void);
68 static void cleanup_readline (void);
69 #ifdef HAVE_LIBREADLINE
70 static void add_history_line (const char *);
73 static int override_progress_bars = -1;
75 /* Currently open libguestfs handle. */
82 int remote_control_listen = 0;
83 int remote_control_csh = 0;
84 int remote_control = 0;
86 int keys_from_stdin = 0;
88 const char *libvirt_uri = NULL;
91 int have_terminfo = 0;
92 int progress_bars = 0;
93 int is_interactive = 0;
95 static void __attribute__((noreturn))
98 if (status != EXIT_SUCCESS)
99 fprintf (stderr, _("Try `%s --help' for more information.\n"),
103 _("%s: guest filesystem shell\n"
104 "%s lets you edit virtual machine filesystems\n"
105 "Copyright (C) 2009-2011 Red Hat Inc.\n"
107 " %s [--options] cmd [: cmd : cmd ...]\n"
109 " -h|--cmd-help List available commands\n"
110 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
111 " -a|--add image Add image\n"
112 " -c|--connect uri Specify libvirt URI for -d option\n"
113 " --csh Make --listen csh-compatible\n"
114 " -d|--domain guest Add disks from libvirt guest\n"
115 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
116 " --echo-keys Don't turn off echo for passphrases\n"
117 " -f|--file file Read commands from file\n"
118 " --format[=raw|..] Force disk format for -a option\n"
119 " -i|--inspector Automatically mount filesystems\n"
120 " --keys-from-stdin Read passphrases from stdin\n"
121 " --listen Listen for remote commands\n"
122 " --live Connect to a live virtual machine\n"
123 " -m|--mount dev[:mnt[:opts]] Mount dev on mnt (if omitted, /)\n"
124 " -n|--no-sync Don't autosync\n"
125 " -N|--new type Create prepared disk (test1.img, ...)\n"
126 " --progress-bars Enable progress bars even when not interactive\n"
127 " --no-progress-bars Disable progress bars\n"
128 " --remote[=pid] Send commands to remote %s\n"
129 " -r|--ro Mount read-only\n"
130 " --selinux Enable SELinux support\n"
131 " -v|--verbose Verbose messages\n"
132 " -V|--version Display version and exit\n"
133 " -w|--rw Mount read-write\n"
134 " -x Echo each command before executing it\n"
136 "To examine a disk image, ISO, hard disk, filesystem etc:\n"
137 " %s [--ro|--rw] -i -a /path/to/disk.img\n"
139 " %s [--ro|--rw] -i -d name-of-libvirt-domain\n"
141 "--ro recommended to avoid any writes to the disk image. If -i option fails\n"
142 "run again without -i and use 'run' + 'list-filesystems' + 'mount' cmds.\n"
144 "For more information, see the manpage %s(1).\n"),
145 program_name, program_name, program_name,
146 program_name, program_name, program_name,
153 main (int argc, char *argv[])
155 /* Set global program name that is not polluted with libtool artifacts. */
156 set_program_name (argv[0]);
158 atexit (close_stdout);
160 setlocale (LC_ALL, "");
161 bindtextdomain (PACKAGE, LOCALEBASEDIR);
162 textdomain (PACKAGE);
168 enum { HELP_OPTION = CHAR_MAX + 1 };
170 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
171 static const struct option long_options[] = {
172 { "add", 1, 0, 'a' },
173 { "cmd-help", 2, 0, 'h' },
174 { "connect", 1, 0, 'c' },
176 { "domain", 1, 0, 'd' },
177 { "echo-keys", 0, 0, 0 },
178 { "file", 1, 0, 'f' },
179 { "format", 2, 0, 0 },
180 { "help", 0, 0, HELP_OPTION },
181 { "inspector", 0, 0, 'i' },
182 { "keys-from-stdin", 0, 0, 0 },
183 { "listen", 0, 0, 0 },
185 { "mount", 1, 0, 'm' },
186 { "new", 1, 0, 'N' },
187 { "no-dest-paths", 0, 0, 'D' },
188 { "no-sync", 0, 0, 'n' },
189 { "progress-bars", 0, 0, 0 },
190 { "no-progress-bars", 0, 0, 0 },
191 { "remote", 2, 0, 0 },
194 { "selinux", 0, 0, 0 },
195 { "verbose", 0, 0, 'v' },
196 { "version", 0, 0, 'V' },
199 struct drv *drvs = NULL;
201 struct mp *mps = NULL;
203 char *p, *file = NULL;
204 const char *format = NULL;
208 int next_prepared_drive = 1;
210 initialize_readline ();
212 memset (&sa, 0, sizeof sa);
213 sa.sa_handler = SIG_IGN;
214 sa.sa_flags = SA_RESTART;
215 sigaction (SIGPIPE, &sa, NULL);
217 /* guestfs_create is meant to be a lightweight operation, so
218 * it's OK to do it early here.
220 g = guestfs_create ();
222 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
226 /* CAUTION: we are careful to modify argv[0] here, only after
227 * using it just above.
229 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
230 * of the original, in case it's needed below.
232 //char *real_argv0 = argv[0];
233 argv[0] = bad_cast (program_name);
236 c = getopt_long (argc, argv, options, long_options, &option_index);
240 case 0: /* options which are long only */
241 if (STREQ (long_options[option_index].name, "listen"))
242 remote_control_listen = 1;
243 else if (STREQ (long_options[option_index].name, "remote")) {
245 if (sscanf (optarg, "%d", &remote_control) != 1) {
246 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
247 program_name, optarg);
251 p = getenv ("GUESTFISH_PID");
252 if (!p || sscanf (p, "%d", &remote_control) != 1) {
253 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
254 " to the PID of the remote process\n"),
259 } else if (STREQ (long_options[option_index].name, "selinux")) {
260 guestfs_set_selinux (g, 1);
261 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
263 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
264 override_progress_bars = 1;
265 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
266 override_progress_bars = 0;
267 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
269 } else if (STREQ (long_options[option_index].name, "format")) {
270 if (!optarg || STREQ (optarg, ""))
274 } else if (STREQ (long_options[option_index].name, "csh")) {
275 remote_control_csh = 1;
276 } else if (STREQ (long_options[option_index].name, "live")) {
279 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
280 program_name, long_options[option_index].name, option_index);
298 complete_dest_paths = 0;
303 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
314 r = display_command (optarg);
315 else if (argv[optind] && argv[optind][0] != '-')
316 r = display_command (argv[optind++]);
320 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
336 if (STRCASEEQ (optarg, "list") ||
337 STRCASEEQ (optarg, "help") ||
338 STRCASEEQ (optarg, "h") ||
339 STRCASEEQ (optarg, "?")) {
340 list_prepared_drives ();
343 drv = malloc (sizeof (struct drv));
351 if (asprintf (&drv->N.filename, "test%d.img",
352 next_prepared_drive++) == -1) {
356 drv->N.data = create_prepared_file (optarg, drv->N.filename);
357 drv->N.data_free = free_prep_data;
383 usage (EXIT_SUCCESS);
386 usage (EXIT_FAILURE);
390 /* Decide here if this will be an interactive session. We have to
391 * do this as soon as possible after processing the command line
394 is_interactive = !file && isatty (0);
396 /* Register a ^C handler. We have to do this before launch could
397 * possibly be called below.
399 if (is_interactive) {
400 memset (&sa, 0, sizeof sa);
401 sa.sa_handler = user_cancel;
402 sa.sa_flags = SA_RESTART;
403 sigaction (SIGINT, &sa, NULL);
405 guestfs_set_pgroup (g, 1);
408 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
409 * previously, if we have -i without any drives but with something
410 * on the command line, it must be old-style syntax.
412 if (inspector && drvs == NULL && optind < argc) {
413 while (optind < argc) {
414 if (strchr (argv[optind], '/') ||
415 access (argv[optind], F_OK) == 0) { /* simulate -a option */
416 drv = malloc (sizeof (struct drv));
422 drv->a.filename = argv[optind];
423 drv->a.format = NULL;
426 } else { /* simulate -d option */
427 drv = malloc (sizeof (struct drv));
433 drv->d.guest = argv[optind];
442 /* If we've got drives to add, add them now. */
443 add_drives (drvs, 'a');
445 /* If we've got mountpoints or prepared drives or -i option, we must
446 * launch the guest and mount them.
448 if (next_prepared_drive > 1 || mps != NULL || inspector) {
449 /* RHBZ#612178: If --listen flag is given, then we will fork into
450 * the background in rc_listen(). However you can't do this while
451 * holding a libguestfs handle open because the recovery process
452 * will think the main program has died and kill qemu. Therefore
453 * don't use the recovery process for this case. (A better
454 * solution would be to call launch () etc after the fork, but
455 * that greatly complicates the code here).
457 if (remote_control_listen)
458 guestfs_set_recovery_proc (g, 0);
460 if (launch () == -1) exit (EXIT_FAILURE);
465 prepare_drives (drvs);
469 /* Free up data structures, no longer needed after this point. */
473 /* Remote control? */
474 if (remote_control_listen && remote_control) {
476 _("%s: cannot use --listen and --remote options at the same time\n"),
481 if (remote_control_listen) {
484 _("%s: extra parameters on the command line with --listen flag\n"),
490 _("%s: cannot use --listen and --file options at the same time\n"),
497 /* -f (file) parameter? */
500 if (open (file, O_RDONLY) == -1) {
506 /* Decide if we display progress bars. */
508 override_progress_bars >= 0
509 ? override_progress_bars
510 : (optind >= argc && is_interactive);
513 guestfs_set_event_callback (g, progress_callback,
514 GUESTFS_EVENT_PROGRESS, 0, NULL);
516 /* Interactive, shell script, or command(s) on the command line? */
517 if (optind >= argc) {
524 cmdline (argv, optind, argc);
532 user_cancel (int sig)
535 guestfs_user_cancel (g);
538 /* The <term.h> header file which defines this has "issues". */
539 extern int tgetent (char *, const char *);
542 set_up_terminal (void)
544 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
545 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
547 char *term = getenv ("TERM");
549 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
553 int r = tgetent (NULL, term);
555 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
559 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
568 prepare_drives (struct drv *drv)
571 prepare_drives (drv->next);
572 if (drv->type == drv_N)
573 prepare_drive (drv->N.filename, drv->N.data, drv->device);
580 if (guestfs_is_config (g)) {
581 if (guestfs_launch (g) == -1)
599 #define FISH "><fs> "
601 static char *line_read = NULL;
606 #ifdef HAVE_LIBREADLINE
614 line_read = readline (prompt ? FISH : "");
616 if (line_read && *line_read)
617 add_history_line (line_read);
622 #endif /* HAVE_LIBREADLINE */
624 static char buf[8192];
627 if (prompt) printf (FISH);
628 line_read = fgets (buf, sizeof buf, stdin);
631 len = strlen (line_read);
632 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
642 int global_exit_on_error = !prompt;
644 struct parsed_command pcmd;
648 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
649 "editing virtual machine filesystems.\n"
651 "Type: 'help' for help on commands\n"
652 " 'man' to read the manual\n"
653 " 'quit' to quit the shell\n"
657 print_inspect_prompt ();
663 exit_on_error = global_exit_on_error;
665 buf = rl_gets (prompt);
671 pcmd = parse_command_line (buf, &exit_on_error);
672 if (pcmd.status == -1 && exit_on_error)
674 if (pcmd.status == 1) {
675 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
676 if (exit_on_error) exit (EXIT_FAILURE);
680 if (prompt) printf ("\n");
683 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
684 * This destructively updates 'buf'.
686 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
687 * setting and to return the local setting (eg. if the command begins
690 * Returns in parsed_command.status:
691 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
692 * 0 = no guestfish command, but otherwise OK
695 static struct parsed_command
696 parse_command_line (char *buf, int *exit_on_error_rtn)
698 struct parsed_command pcmd;
703 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
705 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
706 * fields do not need to be, but this silences a gcc warning.
708 memset (&pcmd, 0, sizeof pcmd);
711 /* Skip any initial whitespace before the command. */
712 while (*buf && c_isspace (*buf))
720 /* If the next character is '#' then this is a comment. */
726 /* If the next character is '!' then pass the whole lot to system(3). */
731 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
732 WEXITSTATUS (r) != 0)
739 /* If the next two characters are "<!" then pass the command to
740 * popen(3), read the result and execute it as guestfish commands.
742 if (buf[0] == '<' && buf[1] == '!') {
743 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
751 /* If the next character is '-' allow the command to fail without
752 * exiting on error (just for this one command though).
755 *exit_on_error_rtn = 0;
760 /* Get the command (cannot be quoted). */
761 len = strcspn (buf, " \t");
770 if (buf[len] == '\0') {
778 p += strspn (p, " \t");
780 /* Get the parameters. */
781 while (*p && i < argv_len) {
784 /* Parameters which start with quotes or pipes are treated
785 * specially. Bare parameters are delimited by whitespace.
789 len = parse_quoted_string (p);
794 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
796 _("%s: command arguments not separated by whitespace\n"),
801 pend = p[len+1] ? &p[len+2] : &p[len+1];
802 } else if (*p == '\'') {
804 len = strcspn (p, "'");
805 if (p[len] == '\0') {
806 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
810 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
812 _("%s: command arguments not separated by whitespace\n"),
818 pend = p[len+1] ? &p[len+2] : &p[len+1];
819 } else if (*p == '|') {
823 } else if (*p != ' ' && *p != '\t') {
824 /* If the first character is a ~ then note that this parameter
825 * is a candidate for ~username expansion. NB this does not
826 * apply to quoted parameters.
828 tilde_candidate = *p == '~';
829 len = strcspn (p, " \t");
836 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
841 if (!tilde_candidate)
844 pcmd.argv[i] = try_tilde_expansion (p);
849 p += strspn (p, " \t");
853 fprintf (stderr, _("%s: too many arguments\n"), program_name);
868 case '0'...'9': return d - '0';
869 case 'a'...'f': return d - 'a' + 10;
870 case 'A'...'F': return d - 'A' + 10;
875 /* Parse double-quoted strings, replacing backslash escape sequences
876 * with the true character. Since the string is returned in place,
877 * the escapes must make the string shorter.
880 parse_quoted_string (char *p)
884 for (; *p && *p != '"'; p++) {
890 case 'a': *p = '\a'; break;
891 case 'b': *p = '\b'; break;
892 case 'f': *p = '\f'; break;
893 case 'n': *p = '\n'; break;
894 case 'r': *p = '\r'; break;
895 case 't': *p = '\t'; break;
896 case 'v': *p = '\v'; break;
897 case '"': *p = '"'; break;
898 case '\'': *p = '\''; break;
899 case '?': *p = '?'; break;
901 case '0'...'7': /* octal escape - always 3 digits */
903 if (p[2] >= '0' && p[2] <= '7' &&
904 p[3] >= '0' && p[3] <= '7') {
905 c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
906 if (c < 1 || c > 255)
914 case 'x': /* hex escape - always 2 digits */
916 if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
917 c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
918 if (c < 1 || c > 255)
928 fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
929 program_name, (int) (p - start));
932 memmove (p+1, p+1+m, strlen (p+1+m) + 1);
937 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
945 /* Used to handle "<!" (execute command and inline result). */
947 execute_and_inline (const char *cmd, int global_exit_on_error)
954 struct parsed_command pcmd;
956 pp = popen (cmd, "r");
962 while ((n = getline (&line, &len, pp)) != -1) {
963 exit_on_error = global_exit_on_error;
965 /* Chomp final line ending which parse_command_line would not expect. */
966 if (n > 0 && line[n-1] == '\n')
969 pcmd = parse_command_line (line, &exit_on_error);
970 if (pcmd.status == -1 && exit_on_error)
972 if (pcmd.status == 1) {
973 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
974 if (exit_on_error) exit (EXIT_FAILURE);
981 if (pclose (pp) != 0) {
990 cmdline (char *argv[], int optind, int argc)
998 if (optind >= argc) return;
1000 cmd = argv[optind++];
1001 if (STREQ (cmd, ":")) {
1002 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
1003 exit (EXIT_FAILURE);
1006 /* Allow -cmd on the command line to mean (temporarily) override
1007 * the normal exit on error (RHBZ#578407).
1009 if (cmd[0] == '-') {
1014 params = &argv[optind];
1016 /* Search for end of command list or ":" ... */
1017 while (optind < argc && STRNEQ (argv[optind], ":"))
1020 if (optind == argc) {
1021 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1022 exit (EXIT_FAILURE);
1024 argv[optind] = NULL;
1025 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1026 exit (EXIT_FAILURE);
1027 cmdline (argv, optind+1, argc);
1031 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1032 * pass to the remote server (when issuing --remote commands). It
1033 * does not cause issue_command itself to exit on error.
1036 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1037 int rc_exit_on_error_flag)
1040 int stdout_saved_fd = -1;
1044 reset_progress_bar ();
1046 /* This counts the commands issued, starting at 1. */
1049 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1053 if (fflush (stdout) == EOF) {
1054 perror ("failed to flush standard output");
1057 if (pipe (fd) < 0) {
1058 perror ("pipe failed");
1067 if (pid == 0) { /* Child process. */
1069 if (dup2 (fd[0], 0) < 0) {
1070 perror ("dup2 of stdin failed");
1074 r = system (pipecmd);
1079 _exit (WEXITSTATUS (r));
1082 if ((stdout_saved_fd = dup (1)) < 0) {
1083 perror ("failed to dup stdout");
1087 if (dup2 (fd[1], 1) < 0) {
1088 perror ("failed to dup stdout");
1089 close (stdout_saved_fd);
1095 for (argc = 0; argv[argc] != NULL; ++argc)
1098 /* If --remote was set, then send this command to a remote process. */
1100 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1102 /* Otherwise execute it locally. */
1103 else if (STRCASEEQ (cmd, "help")) {
1108 r = display_command (argv[0]);
1110 else if (STRCASEEQ (cmd, "quit") ||
1111 STRCASEEQ (cmd, "exit") ||
1112 STRCASEEQ (cmd, "q")) {
1117 r = run_action (cmd, argc, argv);
1119 /* Always flush stdout after every command, so that messages, results
1120 * etc appear immediately.
1122 if (fflush (stdout) == EOF) {
1123 perror ("failed to flush standard output");
1129 if (dup2 (stdout_saved_fd, 1) < 0) {
1130 perror ("failed to dup2 standard output");
1133 close (stdout_saved_fd);
1134 if (waitpid (pid, NULL, 0) < 0) {
1135 perror ("waiting for command to complete");
1144 list_builtin_commands (void)
1146 /* help and quit should appear at the top */
1147 printf ("%-20s %s\n",
1148 "help", _("display a list of commands or help on a command"));
1149 printf ("%-20s %s\n",
1150 "quit", _("quit guestfish"));
1152 /* actions are printed after this (see list_commands) */
1156 display_builtin_command (const char *cmd)
1158 /* help for actions is auto-generated, see display_command */
1160 if (STRCASEEQ (cmd, "help")) {
1161 printf (_("help - display a list of commands or help on a command\n"
1166 else if (STRCASEEQ (cmd, "quit") ||
1167 STRCASEEQ (cmd, "exit") ||
1168 STRCASEEQ (cmd, "q")) {
1169 printf (_("quit - quit guestfish\n"
1174 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1180 /* This is printed when the user types in an unknown command for the
1181 * first command issued. A common case is the user doing:
1182 * guestfish disk.img
1183 * expecting guestfish to open 'disk.img' (in fact, this tried to
1184 * run a command 'disk.img').
1187 extended_help_message (void)
1190 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1191 "For a list of commands: guestfish -h\n"
1192 "For complete documentation: man guestfish\n"));
1196 free_strings (char **argv)
1200 for (argc = 0; argv[argc] != NULL; ++argc)
1206 count_strings (char *const *argv)
1210 for (c = 0; argv[c]; ++c)
1216 print_strings (char *const *argv)
1220 for (argc = 0; argv[argc] != NULL; ++argc)
1221 printf ("%s\n", argv[argc]);
1225 print_table (char *const *argv)
1229 for (i = 0; argv[i] != NULL; i += 2)
1230 printf ("%s: %s\n", argv[i], argv[i+1]);
1234 is_true (const char *str)
1237 STRCASENEQ (str, "0") &&
1238 STRCASENEQ (str, "f") &&
1239 STRCASENEQ (str, "false") &&
1240 STRCASENEQ (str, "n") &&
1241 STRCASENEQ (str, "no");
1244 /* Free strings from a non-NULL terminated char** */
1246 free_n_strings (char **str, size_t len)
1250 for (i = 0; i < len; i++) {
1257 parse_string_list (const char *str)
1260 size_t argv_len = 0;
1262 /* Current position pointer */
1263 const char *p = str;
1265 /* Token might be simple:
1268 * 'This is a single token'
1269 * or contain embedded single-quoted sections:
1270 * This' is a sing'l'e to'ken
1272 * The latter may seem over-complicated, but it's what a normal shell does.
1273 * Not doing it risks surprising somebody.
1275 * This outer loop is over complete tokens.
1281 /* Skip leading whitespace */
1282 p += strspn (p, " \t");
1286 /* This loop is over token 'fragments'. A token can be in multiple bits if
1287 * it contains single quotes. We also treat both sides of an escaped quote
1288 * as separate fragments because we can't just copy it: we have to remove
1291 while (*p && (!c_isblank (*p) || in_quote)) {
1292 const char *end = p;
1294 /* Check if the fragment starts with a quote */
1296 /* Toggle in_quote */
1297 in_quote = !in_quote;
1299 /* Skip the quote */
1303 /* If we're in a quote, look for an end quote */
1305 end += strcspn (end, "'");
1308 /* Otherwise, look for whitespace or a quote */
1310 end += strcspn (end, " \t'");
1313 /* Grow the token to accommodate the fragment */
1314 size_t tok_end = tok_len;
1316 char *tok_new = realloc (tok, tok_len + 1);
1317 if (NULL == tok_new) {
1319 free_n_strings (argv, argv_len);
1321 exit (EXIT_FAILURE);
1325 /* Check if we stopped on an escaped quote */
1326 if ('\'' == *end && end != p && *(end-1) == '\\') {
1327 /* Add everything before \' to the token */
1328 memcpy (&tok[tok_end], p, end - p - 1);
1331 tok[tok_len-1] = '\'';
1333 /* Already processed the quote */
1338 /* Add the whole fragment */
1339 memcpy (&tok[tok_end], p, end - p);
1345 /* We've reached the end of a token. We shouldn't still be in quotes. */
1347 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1348 free_n_strings (argv, argv_len);
1353 /* Add this token if there is one. There might not be if there was
1354 * whitespace at the end of the input string */
1356 /* Add the NULL terminator */
1357 tok[tok_len] = '\0';
1359 /* Add the argument to the argument list */
1361 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1362 if (NULL == argv_new) {
1364 free_n_strings (argv, argv_len-1);
1366 exit (EXIT_FAILURE);
1370 argv[argv_len-1] = tok;
1374 /* NULL terminate the argument list */
1376 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1377 if (NULL == argv_new) {
1379 free_n_strings (argv, argv_len-1);
1380 exit (EXIT_FAILURE);
1384 argv[argv_len-1] = NULL;
1389 #ifdef HAVE_LIBREADLINE
1390 static char histfile[1024];
1391 static int nr_history_lines = 0;
1395 initialize_readline (void)
1397 #ifdef HAVE_LIBREADLINE
1400 home = getenv ("HOME");
1402 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1404 (void) read_history (histfile);
1407 rl_readline_name = "guestfish";
1408 rl_attempted_completion_function = do_completion;
1410 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1411 * call the readline(), which happens later. Therefore, these
1412 * provide default values which can be overridden by the user if
1415 (void) rl_variable_bind ("completion-ignore-case", "on");
1420 cleanup_readline (void)
1422 #ifdef HAVE_LIBREADLINE
1425 if (histfile[0] != '\0') {
1426 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1433 #ifdef HAVE_APPEND_HISTORY
1434 (void) append_history (nr_history_lines, histfile);
1436 (void) write_history (histfile);
1443 #ifdef HAVE_LIBREADLINE
1445 add_history_line (const char *line)
1453 xwrite (int fd, const void *v_buf, size_t len)
1456 const char *buf = v_buf;
1459 r = write (fd, buf, len);
1471 /* Resolve the special "win:..." form for Windows-specific paths. The
1472 * generated code calls this for all device or path arguments.
1474 * The function returns a newly allocated string, and the caller must
1475 * free this string; else display an error and return NULL.
1477 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1480 win_prefix (const char *path)
1485 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1486 if (STRCASENEQLEN (path, "win:", 4)) {
1487 ret = strdup (path);
1495 /* If there is a drive letter, rewrite the path. */
1496 if (c_isalpha (path[0]) && path[1] == ':') {
1497 char drive_letter = c_tolower (path[0]);
1498 /* This returns the newly allocated string. */
1499 ret = win_prefix_drive_letter (drive_letter, path + 2);
1511 ret = strdup (path);
1518 /* Blindly convert any backslashes into forward slashes. Is this good? */
1519 for (i = 0; i < strlen (ret); ++i)
1523 char *t = guestfs_case_sensitive_path (g, ret);
1531 win_prefix_drive_letter (char drive_letter, const char *path)
1533 char **roots = NULL;
1534 char **drives = NULL;
1535 char **mountpoints = NULL;
1536 char *device, *mountpoint, *ret = NULL;
1539 /* Resolve the drive letter using the drive mappings table. */
1540 roots = guestfs_inspect_get_roots (g);
1543 if (roots[0] == NULL) {
1544 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1548 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1549 if (drives == NULL || drives[0] == NULL) {
1550 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1556 for (i = 0; drives[i] != NULL; i += 2) {
1557 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1558 device = drives[i+1];
1563 if (device == NULL) {
1564 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1565 program_name, drive_letter, roots[0]);
1569 /* This drive letter must be mounted somewhere (we won't do it). */
1570 mountpoints = guestfs_mountpoints (g);
1571 if (mountpoints == NULL)
1575 for (i = 0; mountpoints[i] != NULL; i += 2) {
1576 if (STREQ (mountpoints[i], device)) {
1577 mountpoint = mountpoints[i+1];
1582 if (mountpoint == NULL) {
1583 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1584 program_name, drive_letter, device, device);
1588 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1589 if (asprintf (&ret, "%s%s%s",
1590 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1591 perror ("asprintf");
1597 free_strings (roots);
1599 free_strings (drives);
1601 free_strings (mountpoints);
1606 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1607 * The caller (cmds.c) will call free_file_in after the command has
1608 * run which should clean up resources.
1610 static char *file_in_heredoc (const char *endmarker);
1611 static char *file_in_tmpfile = NULL;
1614 file_in (const char *arg)
1618 if (STREQ (arg, "-")) {
1619 ret = strdup ("/dev/stdin");
1625 else if (STRPREFIX (arg, "-<<")) {
1626 const char *endmarker = &arg[3];
1627 if (*endmarker == '\0') {
1628 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1632 ret = file_in_heredoc (endmarker);
1648 file_in_heredoc (const char *endmarker)
1650 TMP_TEMPLATE_ON_STACK (template);
1651 file_in_tmpfile = strdup (template);
1652 if (file_in_tmpfile == NULL) {
1657 int fd = mkstemp (file_in_tmpfile);
1663 size_t markerlen = strlen (endmarker);
1665 char buffer[BUFSIZ];
1666 int write_error = 0;
1667 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1668 /* Look for "END"<EOF> or "END\n" in input. */
1669 size_t blen = strlen (buffer);
1670 if (STREQLEN (buffer, endmarker, markerlen) &&
1671 (blen == markerlen ||
1672 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1675 if (xwrite (fd, buffer, blen) == -1) {
1676 if (!write_error) perror ("write");
1678 /* continue reading up to the end marker */
1682 /* Reached EOF of stdin without finding the end marker, which
1683 * is likely to be an error.
1685 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1686 program_name, endmarker);
1695 if (close (fd) == -1) {
1700 return file_in_tmpfile;
1703 unlink (file_in_tmpfile);
1706 free (file_in_tmpfile);
1707 file_in_tmpfile = NULL;
1712 free_file_in (char *s)
1714 if (file_in_tmpfile) {
1715 if (unlink (file_in_tmpfile) == -1)
1716 perror (file_in_tmpfile);
1717 file_in_tmpfile = NULL;
1720 /* Free the device or file name which was strdup'd in file_in().
1721 * Note it's not immediately clear, but for -<< heredocs,
1722 * s == file_in_tmpfile, so this frees up that buffer.
1727 /* Resolve the special FileOut paths ("-" or filename).
1728 * The caller (cmds.c) will call free (str) after the command has run.
1731 file_out (const char *arg)
1735 if (STREQ (arg, "-"))
1736 ret = strdup ("/dev/stdout");