1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2010 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>
35 #ifdef HAVE_LIBREADLINE
36 #include <readline/readline.h>
37 #include <readline/history.h>
49 static void set_up_terminal (void);
50 static void prepare_drives (struct drv *drv);
51 static int launch (void);
52 static void interactive (void);
53 static void shell_script (void);
54 static void script (int prompt);
55 static void cmdline (char *argv[], int optind, int argc);
56 static void initialize_readline (void);
57 static void cleanup_readline (void);
58 #ifdef HAVE_LIBREADLINE
59 static void add_history_line (const char *);
62 static int override_progress_bars = -1;
64 /* Currently open libguestfs handle. */
70 int remote_control_listen = 0;
71 int remote_control = 0;
72 int exit_on_error = 1;
74 int keys_from_stdin = 0;
76 const char *libvirt_uri = NULL;
79 int have_terminfo = 0;
80 int progress_bars = 0;
82 static void __attribute__((noreturn))
85 if (status != EXIT_SUCCESS)
86 fprintf (stderr, _("Try `%s --help' for more information.\n"),
90 _("%s: guest filesystem shell\n"
91 "%s lets you edit virtual machine filesystems\n"
92 "Copyright (C) 2009-2010 Red Hat Inc.\n"
94 " %s [--options] cmd [: cmd : cmd ...]\n"
95 " %s [--ro] -i -a disk-image\n"
96 " %s [--ro] -i -d libvirt-domain\n"
97 "or for interactive use:\n"
99 "or from a shell script:\n"
105 " -h|--cmd-help List available commands\n"
106 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
107 " -a|--add image Add image\n"
108 " -c|--connect uri Specify libvirt URI for -d option\n"
109 " -d|--domain guest Add disks from libvirt guest\n"
110 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
111 " --echo-keys Don't turn off echo for passphrases\n"
112 " -f|--file file Read commands from file\n"
113 " --format[=raw|..] Force disk format for -a option\n"
114 " -i|--inspector Automatically mount filesystems\n"
115 " --keys-from-stdin Read passphrases from stdin\n"
116 " --listen Listen for remote commands\n"
117 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
118 " -n|--no-sync Don't autosync\n"
119 " -N|--new type Create prepared disk (test1.img, ...)\n"
120 " --progress-bars Enable progress bars even when not interactive\n"
121 " --no-progress-bars Disable progress bars\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 " -V|--version Display version and exit\n"
127 " -x Echo each command before executing it\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);
150 enum { HELP_OPTION = CHAR_MAX + 1 };
152 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
153 static const struct option long_options[] = {
154 { "add", 1, 0, 'a' },
155 { "cmd-help", 2, 0, 'h' },
156 { "connect", 1, 0, 'c' },
157 { "domain", 1, 0, 'd' },
158 { "echo-keys", 0, 0, 0 },
159 { "file", 1, 0, 'f' },
160 { "format", 2, 0, 0 },
161 { "help", 0, 0, HELP_OPTION },
162 { "inspector", 0, 0, 'i' },
163 { "keys-from-stdin", 0, 0, 0 },
164 { "listen", 0, 0, 0 },
165 { "mount", 1, 0, 'm' },
166 { "new", 1, 0, 'N' },
167 { "no-dest-paths", 0, 0, 'D' },
168 { "no-sync", 0, 0, 'n' },
169 { "progress-bars", 0, 0, 0 },
170 { "no-progress-bars", 0, 0, 0 },
171 { "remote", 2, 0, 0 },
173 { "selinux", 0, 0, 0 },
174 { "verbose", 0, 0, 'v' },
175 { "version", 0, 0, 'V' },
178 struct drv *drvs = NULL;
180 struct mp *mps = NULL;
182 char *p, *file = NULL;
183 const char *format = NULL;
187 int next_prepared_drive = 1;
189 initialize_readline ();
191 memset (&sa, 0, sizeof sa);
192 sa.sa_handler = SIG_IGN;
193 sa.sa_flags = SA_RESTART;
194 sigaction (SIGPIPE, &sa, NULL);
196 /* guestfs_create is meant to be a lightweight operation, so
197 * it's OK to do it early here.
199 g = guestfs_create ();
201 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
205 /* If developing, add ./appliance to the path. Note that libtools
206 * interferes with this because uninstalled guestfish is a shell
207 * script that runs the real program with an absolute path. Detect
210 * BUT if LIBGUESTFS_PATH environment variable is already set by
211 * the user, then don't override it.
213 if (getenv ("LIBGUESTFS_PATH") == NULL &&
215 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
216 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
218 /* CAUTION: we are careful to modify argv[0] here, only after
219 * using it just above.
221 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
222 * of the original, in case it's needed below.
224 char *real_argv0 = argv[0];
225 argv[0] = bad_cast (program_name);
228 c = getopt_long (argc, argv, options, long_options, &option_index);
232 case 0: /* options which are long only */
233 if (STREQ (long_options[option_index].name, "listen"))
234 remote_control_listen = 1;
235 else if (STREQ (long_options[option_index].name, "remote")) {
237 if (sscanf (optarg, "%d", &remote_control) != 1) {
238 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
239 program_name, optarg);
243 p = getenv ("GUESTFISH_PID");
244 if (!p || sscanf (p, "%d", &remote_control) != 1) {
245 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
246 " to the PID of the remote process\n"),
251 } else if (STREQ (long_options[option_index].name, "selinux")) {
252 guestfs_set_selinux (g, 1);
253 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
255 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
256 override_progress_bars = 1;
257 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
258 override_progress_bars = 0;
259 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
261 } else if (STREQ (long_options[option_index].name, "format")) {
262 if (!optarg || STREQ (optarg, ""))
267 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
268 program_name, long_options[option_index].name, option_index);
286 complete_dest_paths = 0;
291 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
302 r = display_command (optarg);
303 else if (argv[optind] && argv[optind][0] != '-')
304 r = display_command (argv[optind++]);
308 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
324 if (STRCASEEQ (optarg, "list") ||
325 STRCASEEQ (optarg, "help") ||
326 STRCASEEQ (optarg, "h") ||
327 STRCASEEQ (optarg, "?")) {
328 list_prepared_drives ();
331 drv = malloc (sizeof (struct drv));
337 if (asprintf (&drv->N.filename, "test%d.img",
338 next_prepared_drive++) == -1) {
342 drv->N.data = create_prepared_file (optarg, drv->N.filename);
343 drv->N.data_free = free_prep_data;
344 drv->N.device = NULL; /* filled in by add_drives */
366 usage (EXIT_SUCCESS);
369 usage (EXIT_FAILURE);
373 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
374 * previously, if we have -i without any drives but with something
375 * on the command line, it must be old-style syntax.
377 if (inspector && drvs == NULL && optind < argc) {
378 while (optind < argc) {
379 if (strchr (argv[optind], '/') ||
380 access (argv[optind], F_OK) == 0) { /* simulate -a option */
381 drv = malloc (sizeof (struct drv));
387 drv->a.filename = argv[optind];
388 drv->a.format = NULL;
391 } else { /* simulate -d option */
392 drv = malloc (sizeof (struct drv));
398 drv->d.guest = argv[optind];
407 /* If we've got drives to add, add them now. */
408 add_drives (drvs, 'a');
410 /* If we've got mountpoints or prepared drives or -i option, we must
411 * launch the guest and mount them.
413 if (next_prepared_drive > 1 || mps != NULL || inspector) {
414 /* RHBZ#612178: If --listen flag is given, then we will fork into
415 * the background in rc_listen(). However you can't do this while
416 * holding a libguestfs handle open because the recovery process
417 * will think the main program has died and kill qemu. Therefore
418 * don't use the recovery process for this case. (A better
419 * solution would be to call launch () etc after the fork, but
420 * that greatly complicates the code here).
422 if (remote_control_listen)
423 guestfs_set_recovery_proc (g, 0);
425 if (launch () == -1) exit (EXIT_FAILURE);
430 prepare_drives (drvs);
434 /* Free up data structures, no longer needed after this point. */
438 /* Remote control? */
439 if (remote_control_listen && remote_control) {
441 _("%s: cannot use --listen and --remote options at the same time\n"),
446 if (remote_control_listen) {
449 _("%s: extra parameters on the command line with --listen flag\n"),
455 _("%s: cannot use --listen and --file options at the same time\n"),
462 /* -f (file) parameter? */
465 if (open (file, O_RDONLY) == -1) {
471 /* Decide if we display progress bars. */
473 override_progress_bars >= 0
474 ? override_progress_bars
475 : (optind >= argc && isatty (0));
478 guestfs_set_progress_callback (g, progress_callback, NULL);
480 /* Interactive, shell script, or command(s) on the command line? */
481 if (optind >= argc) {
488 cmdline (argv, optind, argc);
495 /* The <term.h> header file which defines this has "issues". */
496 extern int tgetent (char *, const char *);
499 set_up_terminal (void)
501 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
502 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
504 char *term = getenv ("TERM");
506 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
510 int r = tgetent (NULL, term);
512 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
516 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
525 pod2text (const char *name, const char *shortdesc, const char *str)
529 fp = popen ("pod2text", "w");
531 /* pod2text failed, maybe not found, so let's just print the
532 * source instead, since that's better than doing nothing.
534 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
537 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
543 prepare_drives (struct drv *drv)
546 prepare_drives (drv->next);
547 if (drv->type == drv_N)
548 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
555 if (guestfs_is_config (g)) {
556 if (guestfs_launch (g) == -1)
574 #define FISH "><fs> "
576 static char *line_read = NULL;
581 #ifdef HAVE_LIBREADLINE
589 line_read = readline (prompt ? FISH : "");
591 if (line_read && *line_read)
592 add_history_line (line_read);
597 #endif /* HAVE_LIBREADLINE */
599 static char buf[8192];
602 if (prompt) printf (FISH);
603 line_read = fgets (buf, sizeof buf, stdin);
606 len = strlen (line_read);
607 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
621 int global_exit_on_error = !prompt;
626 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
627 "editing virtual machine filesystems.\n"
629 "Type: 'help' for a list of commands\n"
630 " 'man' to read the manual\n"
631 " 'quit' to quit the shell\n"
635 print_inspect_prompt ();
643 exit_on_error = global_exit_on_error;
645 buf = rl_gets (prompt);
651 /* Skip any initial whitespace before the command. */
653 while (*buf && c_isspace (*buf))
658 /* If the next character is '#' then this is a comment. */
659 if (*buf == '#') continue;
661 /* If the next character is '!' then pass the whole lot to system(3). */
669 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
670 WEXITSTATUS (r) != 0)
676 /* If the next character is '-' allow the command to fail without
677 * exiting on error (just for this one command though).
685 /* Get the command (cannot be quoted). */
686 len = strcspn (buf, " \t");
688 if (len == 0) continue;
692 if (buf[len] == '\0') {
699 p += strspn (p, " \t");
701 /* Get the parameters. */
702 while (*p && i < sizeof argv / sizeof argv[0]) {
705 /* Parameters which start with quotes or pipes are treated
706 * specially. Bare parameters are delimited by whitespace.
710 len = strcspn (p, "\"");
711 if (p[len] == '\0') {
712 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
713 if (exit_on_error) exit (EXIT_FAILURE);
716 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
718 _("%s: command arguments not separated by whitespace\n"),
720 if (exit_on_error) exit (EXIT_FAILURE);
724 pend = p[len+1] ? &p[len+2] : &p[len+1];
725 } else if (*p == '\'') {
727 len = strcspn (p, "'");
728 if (p[len] == '\0') {
729 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
730 if (exit_on_error) exit (EXIT_FAILURE);
733 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
735 _("%s: command arguments not separated by whitespace\n"),
737 if (exit_on_error) exit (EXIT_FAILURE);
741 pend = p[len+1] ? &p[len+2] : &p[len+1];
742 } else if (*p == '|') {
747 } else if (*p == '[') {
751 while (*pend && c != 0) {
752 if (*pend == '[') c++;
753 else if (*pend == ']') c--;
758 _("%s: unterminated \"[...]\" sequence\n"), program_name);
759 if (exit_on_error) exit (EXIT_FAILURE);
762 if (*pend && (*pend != ' ' && *pend != '\t')) {
764 _("%s: command arguments not separated by whitespace\n"),
766 if (exit_on_error) exit (EXIT_FAILURE);
771 } else if (*p != ' ' && *p != '\t') {
772 /* If the first character is a ~ then note that this parameter
773 * is a candidate for ~username expansion. NB this does not
774 * apply to quoted parameters.
776 tilde_candidate = *p == '~';
777 len = strcspn (p, " \t");
784 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
789 if (!tilde_candidate)
792 argv[i] = try_tilde_expansion (p);
797 p += strspn (p, " \t");
800 if (i == sizeof argv / sizeof argv[0]) {
801 fprintf (stderr, _("%s: too many arguments\n"), program_name);
802 if (exit_on_error) exit (EXIT_FAILURE);
809 if (issue_command (cmd, argv, pipe) == -1) {
810 if (exit_on_error) exit (EXIT_FAILURE);
815 if (prompt) printf ("\n");
819 cmdline (char *argv[], int optind, int argc)
826 if (optind >= argc) return;
828 cmd = argv[optind++];
829 if (STREQ (cmd, ":")) {
830 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
834 /* Allow -cmd on the command line to mean (temporarily) override
835 * the normal exit on error (RHBZ#578407).
842 params = &argv[optind];
844 /* Search for end of command list or ":" ... */
845 while (optind < argc && STRNEQ (argv[optind], ":"))
848 if (optind == argc) {
849 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
853 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
855 cmdline (argv, optind+1, argc);
860 issue_command (const char *cmd, char *argv[], const char *pipecmd)
863 int stdout_saved_fd = -1;
867 reset_progress_bar ();
869 /* This counts the commands issued, starting at 1. */
872 /* For | ... commands. Annoyingly we can't use popen(3) here. */
876 if (fflush (stdout) == EOF) {
877 perror ("failed to flush standard output");
881 perror ("pipe failed");
890 if (pid == 0) { /* Child process. */
892 if (dup2 (fd[0], 0) < 0) {
893 perror ("dup2 of stdin failed");
897 r = system (pipecmd);
902 _exit (WEXITSTATUS (r));
905 if ((stdout_saved_fd = dup (1)) < 0) {
906 perror ("failed to dup stdout");
910 if (dup2 (fd[1], 1) < 0) {
911 perror ("failed to dup stdout");
912 close (stdout_saved_fd);
918 for (argc = 0; argv[argc] != NULL; ++argc)
921 /* If --remote was set, then send this command to a remote process. */
923 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
925 /* Otherwise execute it locally. */
926 else if (STRCASEEQ (cmd, "help")) {
931 r = display_command (argv[0]);
933 else if (STRCASEEQ (cmd, "quit") ||
934 STRCASEEQ (cmd, "exit") ||
935 STRCASEEQ (cmd, "q")) {
940 r = run_action (cmd, argc, argv);
942 /* Always flush stdout after every command, so that messages, results
943 * etc appear immediately.
945 if (fflush (stdout) == EOF) {
946 perror ("failed to flush standard output");
952 if (dup2 (stdout_saved_fd, 1) < 0) {
953 perror ("failed to dup2 standard output");
956 close (stdout_saved_fd);
957 if (waitpid (pid, NULL, 0) < 0) {
958 perror ("waiting for command to complete");
967 list_builtin_commands (void)
969 /* help and quit should appear at the top */
970 printf ("%-20s %s\n",
971 "help", _("display a list of commands or help on a command"));
972 printf ("%-20s %s\n",
973 "quit", _("quit guestfish"));
975 /* actions are printed after this (see list_commands) */
979 display_builtin_command (const char *cmd)
981 /* help for actions is auto-generated, see display_command */
983 if (STRCASEEQ (cmd, "help")) {
984 printf (_("help - display a list of commands or help on a command\n"
989 else if (STRCASEEQ (cmd, "quit") ||
990 STRCASEEQ (cmd, "exit") ||
991 STRCASEEQ (cmd, "q")) {
992 printf (_("quit - quit guestfish\n"
997 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1003 /* This is printed when the user types in an unknown command for the
1004 * first command issued. A common case is the user doing:
1005 * guestfish disk.img
1006 * expecting guestfish to open 'disk.img' (in fact, this tried to
1007 * run a command 'disk.img').
1010 extended_help_message (void)
1013 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1014 "For a list of commands: guestfish -h\n"
1015 "For complete documentation: man guestfish\n"));
1019 free_strings (char **argv)
1023 for (argc = 0; argv[argc] != NULL; ++argc)
1029 count_strings (char *const *argv)
1033 for (c = 0; argv[c]; ++c)
1039 print_strings (char *const *argv)
1043 for (argc = 0; argv[argc] != NULL; ++argc)
1044 printf ("%s\n", argv[argc]);
1048 print_table (char *const *argv)
1052 for (i = 0; argv[i] != NULL; i += 2)
1053 printf ("%s: %s\n", argv[i], argv[i+1]);
1057 is_true (const char *str)
1060 STRCASENEQ (str, "0") &&
1061 STRCASENEQ (str, "f") &&
1062 STRCASENEQ (str, "false") &&
1063 STRCASENEQ (str, "n") &&
1064 STRCASENEQ (str, "no");
1067 /* Free strings from a non-NULL terminated char** */
1069 free_n_strings (char **str, size_t len)
1073 for (i = 0; i < len; i++) {
1080 parse_string_list (const char *str)
1083 size_t argv_len = 0;
1085 /* Current position pointer */
1086 const char *p = str;
1088 /* Token might be simple:
1091 * 'This is a single token'
1092 * or contain embedded single-quoted sections:
1093 * This' is a sing'l'e to'ken
1095 * The latter may seem over-complicated, but it's what a normal shell does.
1096 * Not doing it risks surprising somebody.
1098 * This outer loop is over complete tokens.
1104 /* Skip leading whitespace */
1105 p += strspn (p, " \t");
1109 /* This loop is over token 'fragments'. A token can be in multiple bits if
1110 * it contains single quotes. We also treat both sides of an escaped quote
1111 * as separate fragments because we can't just copy it: we have to remove
1114 while (*p && (!c_isblank (*p) || in_quote)) {
1115 const char *end = p;
1117 /* Check if the fragment starts with a quote */
1119 /* Toggle in_quote */
1120 in_quote = !in_quote;
1122 /* Skip the quote */
1126 /* If we're in a quote, look for an end quote */
1128 end += strcspn (end, "'");
1131 /* Otherwise, look for whitespace or a quote */
1133 end += strcspn (end, " \t'");
1136 /* Grow the token to accommodate the fragment */
1137 size_t tok_end = tok_len;
1139 char *tok_new = realloc (tok, tok_len + 1);
1140 if (NULL == tok_new) {
1142 free_n_strings (argv, argv_len);
1144 exit (EXIT_FAILURE);
1148 /* Check if we stopped on an escaped quote */
1149 if ('\'' == *end && end != p && *(end-1) == '\\') {
1150 /* Add everything before \' to the token */
1151 memcpy (&tok[tok_end], p, end - p - 1);
1154 tok[tok_len-1] = '\'';
1156 /* Already processed the quote */
1161 /* Add the whole fragment */
1162 memcpy (&tok[tok_end], p, end - p);
1168 /* We've reached the end of a token. We shouldn't still be in quotes. */
1170 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1172 free_n_strings (argv, argv_len);
1177 /* Add this token if there is one. There might not be if there was
1178 * whitespace at the end of the input string */
1180 /* Add the NULL terminator */
1181 tok[tok_len] = '\0';
1183 /* Add the argument to the argument list */
1185 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1186 if (NULL == argv_new) {
1188 free_n_strings (argv, argv_len-1);
1190 exit (EXIT_FAILURE);
1194 argv[argv_len-1] = tok;
1198 /* NULL terminate the argument list */
1200 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1201 if (NULL == argv_new) {
1203 free_n_strings (argv, argv_len-1);
1204 exit (EXIT_FAILURE);
1208 argv[argv_len-1] = NULL;
1213 #ifdef HAVE_LIBREADLINE
1214 static char histfile[1024];
1215 static int nr_history_lines = 0;
1219 initialize_readline (void)
1221 #ifdef HAVE_LIBREADLINE
1224 home = getenv ("HOME");
1226 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1228 (void) read_history (histfile);
1231 rl_readline_name = "guestfish";
1232 rl_attempted_completion_function = do_completion;
1234 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1235 * call the readline(), which happens later. Therefore, these
1236 * provide default values which can be overridden by the user if
1239 (void) rl_variable_bind ("completion-ignore-case", "on");
1244 cleanup_readline (void)
1246 #ifdef HAVE_LIBREADLINE
1249 if (histfile[0] != '\0') {
1250 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1257 #ifdef HAVE_APPEND_HISTORY
1258 (void) append_history (nr_history_lines, histfile);
1260 (void) write_history (histfile);
1267 #ifdef HAVE_LIBREADLINE
1269 add_history_line (const char *line)
1277 xwrite (int fd, const void *v_buf, size_t len)
1280 const char *buf = v_buf;
1283 r = write (fd, buf, len);
1295 /* Resolve the special "win:..." form for Windows-specific paths.
1296 * This always returns a newly allocated string which is freed by the
1297 * caller function in "cmds.c".
1300 resolve_win_path (const char *path)
1305 if (STRCASENEQLEN (path, "win:", 4)) {
1306 ret = strdup (path);
1314 /* Drop drive letter, if it's "C:". */
1315 if (STRCASEEQLEN (path, "c:", 2))
1325 ret = strdup (path);
1331 /* Blindly convert any backslashes into forward slashes. Is this good? */
1332 for (i = 0; i < strlen (ret); ++i)
1336 char *t = guestfs_case_sensitive_path (g, ret);
1343 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1344 * The caller (cmds.c) will call free_file_in after the command has
1345 * run which should clean up resources.
1347 static char *file_in_heredoc (const char *endmarker);
1348 static char *file_in_tmpfile = NULL;
1351 file_in (const char *arg)
1355 if (STREQ (arg, "-")) {
1356 ret = strdup ("/dev/stdin");
1362 else if (STRPREFIX (arg, "-<<")) {
1363 const char *endmarker = &arg[3];
1364 if (*endmarker == '\0') {
1365 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1369 ret = file_in_heredoc (endmarker);
1385 file_in_heredoc (const char *endmarker)
1387 TMP_TEMPLATE_ON_STACK (template);
1388 file_in_tmpfile = strdup (template);
1389 if (file_in_tmpfile == NULL) {
1394 int fd = mkstemp (file_in_tmpfile);
1400 size_t markerlen = strlen (endmarker);
1402 char buffer[BUFSIZ];
1403 int write_error = 0;
1404 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1405 /* Look for "END"<EOF> or "END\n" in input. */
1406 size_t blen = strlen (buffer);
1407 if (STREQLEN (buffer, endmarker, markerlen) &&
1408 (blen == markerlen ||
1409 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1412 if (xwrite (fd, buffer, blen) == -1) {
1413 if (!write_error) perror ("write");
1415 /* continue reading up to the end marker */
1419 /* Reached EOF of stdin without finding the end marker, which
1420 * is likely to be an error.
1422 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1423 program_name, endmarker);
1432 if (close (fd) == -1) {
1437 return file_in_tmpfile;
1440 unlink (file_in_tmpfile);
1443 free (file_in_tmpfile);
1444 file_in_tmpfile = NULL;
1449 free_file_in (char *s)
1451 if (file_in_tmpfile) {
1452 if (unlink (file_in_tmpfile) == -1)
1453 perror (file_in_tmpfile);
1454 file_in_tmpfile = NULL;
1457 /* Free the device or file name which was strdup'd in file_in().
1458 * Note it's not immediately clear, but for -<< heredocs,
1459 * s == file_in_tmpfile, so this frees up that buffer.
1464 /* Resolve the special FileOut paths ("-" or filename).
1465 * The caller (cmds.c) will call free (str) after the command has run.
1468 file_out (const char *arg)
1472 if (STREQ (arg, "-"))
1473 ret = strdup ("/dev/stdout");
1484 /* Read a passphrase ('Key') from /dev/tty with echo off.
1485 * The caller (cmds.c) will call free on the string afterwards.
1486 * Based on the code in cryptsetup file lib/utils.c.
1489 read_key (const char *param)
1492 struct termios orig, temp;
1495 /* Read and write to /dev/tty if available. */
1496 if (keys_from_stdin ||
1497 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1502 /* Print the prompt and set no echo. */
1503 int tty = isatty (fileno (infp));
1506 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1509 if (tcgetattr (fileno (infp), &orig) == -1) {
1510 perror ("tcgetattr");
1513 memcpy (&temp, &orig, sizeof temp);
1514 temp.c_lflag &= ~ECHO;
1516 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1523 len = getline (&ret, &n, infp);
1530 /* Remove the terminating \n if there is one. */
1531 if (len > 0 && ret[len-1] == '\n')
1535 /* Restore echo, close file descriptor. */
1538 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1542 fclose (infp); /* outfp == infp, so this is closed also */