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?Vwx";
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 },
174 { "selinux", 0, 0, 0 },
175 { "verbose", 0, 0, 'v' },
176 { "version", 0, 0, 'V' },
179 struct drv *drvs = NULL;
181 struct mp *mps = NULL;
183 char *p, *file = NULL;
184 const char *format = NULL;
188 int next_prepared_drive = 1;
190 initialize_readline ();
192 memset (&sa, 0, sizeof sa);
193 sa.sa_handler = SIG_IGN;
194 sa.sa_flags = SA_RESTART;
195 sigaction (SIGPIPE, &sa, NULL);
197 /* guestfs_create is meant to be a lightweight operation, so
198 * it's OK to do it early here.
200 g = guestfs_create ();
202 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
206 /* If developing, add ./appliance to the path. Note that libtools
207 * interferes with this because uninstalled guestfish is a shell
208 * script that runs the real program with an absolute path. Detect
211 * BUT if LIBGUESTFS_PATH environment variable is already set by
212 * the user, then don't override it.
214 if (getenv ("LIBGUESTFS_PATH") == NULL &&
216 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
217 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
219 /* CAUTION: we are careful to modify argv[0] here, only after
220 * using it just above.
222 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
223 * of the original, in case it's needed below.
225 char *real_argv0 = argv[0];
226 argv[0] = bad_cast (program_name);
229 c = getopt_long (argc, argv, options, long_options, &option_index);
233 case 0: /* options which are long only */
234 if (STREQ (long_options[option_index].name, "listen"))
235 remote_control_listen = 1;
236 else if (STREQ (long_options[option_index].name, "remote")) {
238 if (sscanf (optarg, "%d", &remote_control) != 1) {
239 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
240 program_name, optarg);
244 p = getenv ("GUESTFISH_PID");
245 if (!p || sscanf (p, "%d", &remote_control) != 1) {
246 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
247 " to the PID of the remote process\n"),
252 } else if (STREQ (long_options[option_index].name, "selinux")) {
253 guestfs_set_selinux (g, 1);
254 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
256 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
257 override_progress_bars = 1;
258 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
259 override_progress_bars = 0;
260 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
262 } else if (STREQ (long_options[option_index].name, "format")) {
263 if (!optarg || STREQ (optarg, ""))
268 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
269 program_name, long_options[option_index].name, option_index);
287 complete_dest_paths = 0;
292 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
303 r = display_command (optarg);
304 else if (argv[optind] && argv[optind][0] != '-')
305 r = display_command (argv[optind++]);
309 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
325 if (STRCASEEQ (optarg, "list") ||
326 STRCASEEQ (optarg, "help") ||
327 STRCASEEQ (optarg, "h") ||
328 STRCASEEQ (optarg, "?")) {
329 list_prepared_drives ();
332 drv = malloc (sizeof (struct drv));
338 if (asprintf (&drv->N.filename, "test%d.img",
339 next_prepared_drive++) == -1) {
343 drv->N.data = create_prepared_file (optarg, drv->N.filename);
344 drv->N.data_free = free_prep_data;
345 drv->N.device = NULL; /* filled in by add_drives */
371 usage (EXIT_SUCCESS);
374 usage (EXIT_FAILURE);
378 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
379 * previously, if we have -i without any drives but with something
380 * on the command line, it must be old-style syntax.
382 if (inspector && drvs == NULL && optind < argc) {
383 while (optind < argc) {
384 if (strchr (argv[optind], '/') ||
385 access (argv[optind], F_OK) == 0) { /* simulate -a option */
386 drv = malloc (sizeof (struct drv));
392 drv->a.filename = argv[optind];
393 drv->a.format = NULL;
396 } else { /* simulate -d option */
397 drv = malloc (sizeof (struct drv));
403 drv->d.guest = argv[optind];
412 /* If we've got drives to add, add them now. */
413 add_drives (drvs, 'a');
415 /* If we've got mountpoints or prepared drives or -i option, we must
416 * launch the guest and mount them.
418 if (next_prepared_drive > 1 || mps != NULL || inspector) {
419 /* RHBZ#612178: If --listen flag is given, then we will fork into
420 * the background in rc_listen(). However you can't do this while
421 * holding a libguestfs handle open because the recovery process
422 * will think the main program has died and kill qemu. Therefore
423 * don't use the recovery process for this case. (A better
424 * solution would be to call launch () etc after the fork, but
425 * that greatly complicates the code here).
427 if (remote_control_listen)
428 guestfs_set_recovery_proc (g, 0);
430 if (launch () == -1) exit (EXIT_FAILURE);
435 prepare_drives (drvs);
439 /* Free up data structures, no longer needed after this point. */
443 /* Remote control? */
444 if (remote_control_listen && remote_control) {
446 _("%s: cannot use --listen and --remote options at the same time\n"),
451 if (remote_control_listen) {
454 _("%s: extra parameters on the command line with --listen flag\n"),
460 _("%s: cannot use --listen and --file options at the same time\n"),
467 /* -f (file) parameter? */
470 if (open (file, O_RDONLY) == -1) {
476 /* Decide if we display progress bars. */
478 override_progress_bars >= 0
479 ? override_progress_bars
480 : (optind >= argc && isatty (0));
483 guestfs_set_progress_callback (g, progress_callback, NULL);
485 /* Interactive, shell script, or command(s) on the command line? */
486 if (optind >= argc) {
493 cmdline (argv, optind, argc);
500 /* The <term.h> header file which defines this has "issues". */
501 extern int tgetent (char *, const char *);
504 set_up_terminal (void)
506 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
507 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
509 char *term = getenv ("TERM");
511 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
515 int r = tgetent (NULL, term);
517 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
521 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
530 pod2text (const char *name, const char *shortdesc, const char *str)
534 fp = popen ("pod2text", "w");
536 /* pod2text failed, maybe not found, so let's just print the
537 * source instead, since that's better than doing nothing.
539 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
542 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
548 prepare_drives (struct drv *drv)
551 prepare_drives (drv->next);
552 if (drv->type == drv_N)
553 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
560 if (guestfs_is_config (g)) {
561 if (guestfs_launch (g) == -1)
579 #define FISH "><fs> "
581 static char *line_read = NULL;
586 #ifdef HAVE_LIBREADLINE
594 line_read = readline (prompt ? FISH : "");
596 if (line_read && *line_read)
597 add_history_line (line_read);
602 #endif /* HAVE_LIBREADLINE */
604 static char buf[8192];
607 if (prompt) printf (FISH);
608 line_read = fgets (buf, sizeof buf, stdin);
611 len = strlen (line_read);
612 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
626 int global_exit_on_error = !prompt;
631 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
632 "editing virtual machine filesystems.\n"
634 "Type: 'help' for a list of commands\n"
635 " 'man' to read the manual\n"
636 " 'quit' to quit the shell\n"
640 print_inspect_prompt ();
648 exit_on_error = global_exit_on_error;
650 buf = rl_gets (prompt);
656 /* Skip any initial whitespace before the command. */
658 while (*buf && c_isspace (*buf))
663 /* If the next character is '#' then this is a comment. */
664 if (*buf == '#') continue;
666 /* If the next character is '!' then pass the whole lot to system(3). */
674 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
675 WEXITSTATUS (r) != 0)
681 /* If the next character is '-' allow the command to fail without
682 * exiting on error (just for this one command though).
690 /* Get the command (cannot be quoted). */
691 len = strcspn (buf, " \t");
693 if (len == 0) continue;
697 if (buf[len] == '\0') {
704 p += strspn (p, " \t");
706 /* Get the parameters. */
707 while (*p && i < sizeof argv / sizeof argv[0]) {
710 /* Parameters which start with quotes or pipes are treated
711 * specially. Bare parameters are delimited by whitespace.
715 len = strcspn (p, "\"");
716 if (p[len] == '\0') {
717 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
718 if (exit_on_error) exit (EXIT_FAILURE);
721 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
723 _("%s: command arguments not separated by whitespace\n"),
725 if (exit_on_error) exit (EXIT_FAILURE);
729 pend = p[len+1] ? &p[len+2] : &p[len+1];
730 } else if (*p == '\'') {
732 len = strcspn (p, "'");
733 if (p[len] == '\0') {
734 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
735 if (exit_on_error) exit (EXIT_FAILURE);
738 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
740 _("%s: command arguments not separated by whitespace\n"),
742 if (exit_on_error) exit (EXIT_FAILURE);
746 pend = p[len+1] ? &p[len+2] : &p[len+1];
747 } else if (*p == '|') {
752 } else if (*p == '[') {
756 while (*pend && c != 0) {
757 if (*pend == '[') c++;
758 else if (*pend == ']') c--;
763 _("%s: unterminated \"[...]\" sequence\n"), program_name);
764 if (exit_on_error) exit (EXIT_FAILURE);
767 if (*pend && (*pend != ' ' && *pend != '\t')) {
769 _("%s: command arguments not separated by whitespace\n"),
771 if (exit_on_error) exit (EXIT_FAILURE);
776 } else if (*p != ' ' && *p != '\t') {
777 /* If the first character is a ~ then note that this parameter
778 * is a candidate for ~username expansion. NB this does not
779 * apply to quoted parameters.
781 tilde_candidate = *p == '~';
782 len = strcspn (p, " \t");
789 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
794 if (!tilde_candidate)
797 argv[i] = try_tilde_expansion (p);
802 p += strspn (p, " \t");
805 if (i == sizeof argv / sizeof argv[0]) {
806 fprintf (stderr, _("%s: too many arguments\n"), program_name);
807 if (exit_on_error) exit (EXIT_FAILURE);
814 if (issue_command (cmd, argv, pipe) == -1) {
815 if (exit_on_error) exit (EXIT_FAILURE);
820 if (prompt) printf ("\n");
824 cmdline (char *argv[], int optind, int argc)
831 if (optind >= argc) return;
833 cmd = argv[optind++];
834 if (STREQ (cmd, ":")) {
835 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
839 /* Allow -cmd on the command line to mean (temporarily) override
840 * the normal exit on error (RHBZ#578407).
847 params = &argv[optind];
849 /* Search for end of command list or ":" ... */
850 while (optind < argc && STRNEQ (argv[optind], ":"))
853 if (optind == argc) {
854 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
858 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
860 cmdline (argv, optind+1, argc);
865 issue_command (const char *cmd, char *argv[], const char *pipecmd)
868 int stdout_saved_fd = -1;
872 reset_progress_bar ();
874 /* This counts the commands issued, starting at 1. */
877 /* For | ... commands. Annoyingly we can't use popen(3) here. */
881 if (fflush (stdout) == EOF) {
882 perror ("failed to flush standard output");
886 perror ("pipe failed");
895 if (pid == 0) { /* Child process. */
897 if (dup2 (fd[0], 0) < 0) {
898 perror ("dup2 of stdin failed");
902 r = system (pipecmd);
907 _exit (WEXITSTATUS (r));
910 if ((stdout_saved_fd = dup (1)) < 0) {
911 perror ("failed to dup stdout");
915 if (dup2 (fd[1], 1) < 0) {
916 perror ("failed to dup stdout");
917 close (stdout_saved_fd);
923 for (argc = 0; argv[argc] != NULL; ++argc)
926 /* If --remote was set, then send this command to a remote process. */
928 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
930 /* Otherwise execute it locally. */
931 else if (STRCASEEQ (cmd, "help")) {
936 r = display_command (argv[0]);
938 else if (STRCASEEQ (cmd, "quit") ||
939 STRCASEEQ (cmd, "exit") ||
940 STRCASEEQ (cmd, "q")) {
945 r = run_action (cmd, argc, argv);
947 /* Always flush stdout after every command, so that messages, results
948 * etc appear immediately.
950 if (fflush (stdout) == EOF) {
951 perror ("failed to flush standard output");
957 if (dup2 (stdout_saved_fd, 1) < 0) {
958 perror ("failed to dup2 standard output");
961 close (stdout_saved_fd);
962 if (waitpid (pid, NULL, 0) < 0) {
963 perror ("waiting for command to complete");
972 list_builtin_commands (void)
974 /* help and quit should appear at the top */
975 printf ("%-20s %s\n",
976 "help", _("display a list of commands or help on a command"));
977 printf ("%-20s %s\n",
978 "quit", _("quit guestfish"));
980 /* actions are printed after this (see list_commands) */
984 display_builtin_command (const char *cmd)
986 /* help for actions is auto-generated, see display_command */
988 if (STRCASEEQ (cmd, "help")) {
989 printf (_("help - display a list of commands or help on a command\n"
994 else if (STRCASEEQ (cmd, "quit") ||
995 STRCASEEQ (cmd, "exit") ||
996 STRCASEEQ (cmd, "q")) {
997 printf (_("quit - quit guestfish\n"
1002 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1008 /* This is printed when the user types in an unknown command for the
1009 * first command issued. A common case is the user doing:
1010 * guestfish disk.img
1011 * expecting guestfish to open 'disk.img' (in fact, this tried to
1012 * run a command 'disk.img').
1015 extended_help_message (void)
1018 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1019 "For a list of commands: guestfish -h\n"
1020 "For complete documentation: man guestfish\n"));
1024 free_strings (char **argv)
1028 for (argc = 0; argv[argc] != NULL; ++argc)
1034 count_strings (char *const *argv)
1038 for (c = 0; argv[c]; ++c)
1044 print_strings (char *const *argv)
1048 for (argc = 0; argv[argc] != NULL; ++argc)
1049 printf ("%s\n", argv[argc]);
1053 print_table (char *const *argv)
1057 for (i = 0; argv[i] != NULL; i += 2)
1058 printf ("%s: %s\n", argv[i], argv[i+1]);
1062 is_true (const char *str)
1065 STRCASENEQ (str, "0") &&
1066 STRCASENEQ (str, "f") &&
1067 STRCASENEQ (str, "false") &&
1068 STRCASENEQ (str, "n") &&
1069 STRCASENEQ (str, "no");
1072 /* Free strings from a non-NULL terminated char** */
1074 free_n_strings (char **str, size_t len)
1078 for (i = 0; i < len; i++) {
1085 parse_string_list (const char *str)
1088 size_t argv_len = 0;
1090 /* Current position pointer */
1091 const char *p = str;
1093 /* Token might be simple:
1096 * 'This is a single token'
1097 * or contain embedded single-quoted sections:
1098 * This' is a sing'l'e to'ken
1100 * The latter may seem over-complicated, but it's what a normal shell does.
1101 * Not doing it risks surprising somebody.
1103 * This outer loop is over complete tokens.
1109 /* Skip leading whitespace */
1110 p += strspn (p, " \t");
1114 /* This loop is over token 'fragments'. A token can be in multiple bits if
1115 * it contains single quotes. We also treat both sides of an escaped quote
1116 * as separate fragments because we can't just copy it: we have to remove
1119 while (*p && (!c_isblank (*p) || in_quote)) {
1120 const char *end = p;
1122 /* Check if the fragment starts with a quote */
1124 /* Toggle in_quote */
1125 in_quote = !in_quote;
1127 /* Skip the quote */
1131 /* If we're in a quote, look for an end quote */
1133 end += strcspn (end, "'");
1136 /* Otherwise, look for whitespace or a quote */
1138 end += strcspn (end, " \t'");
1141 /* Grow the token to accommodate the fragment */
1142 size_t tok_end = tok_len;
1144 char *tok_new = realloc (tok, tok_len + 1);
1145 if (NULL == tok_new) {
1147 free_n_strings (argv, argv_len);
1149 exit (EXIT_FAILURE);
1153 /* Check if we stopped on an escaped quote */
1154 if ('\'' == *end && end != p && *(end-1) == '\\') {
1155 /* Add everything before \' to the token */
1156 memcpy (&tok[tok_end], p, end - p - 1);
1159 tok[tok_len-1] = '\'';
1161 /* Already processed the quote */
1166 /* Add the whole fragment */
1167 memcpy (&tok[tok_end], p, end - p);
1173 /* We've reached the end of a token. We shouldn't still be in quotes. */
1175 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1177 free_n_strings (argv, argv_len);
1182 /* Add this token if there is one. There might not be if there was
1183 * whitespace at the end of the input string */
1185 /* Add the NULL terminator */
1186 tok[tok_len] = '\0';
1188 /* Add the argument to the argument list */
1190 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1191 if (NULL == argv_new) {
1193 free_n_strings (argv, argv_len-1);
1195 exit (EXIT_FAILURE);
1199 argv[argv_len-1] = tok;
1203 /* NULL terminate the argument list */
1205 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1206 if (NULL == argv_new) {
1208 free_n_strings (argv, argv_len-1);
1209 exit (EXIT_FAILURE);
1213 argv[argv_len-1] = NULL;
1218 #ifdef HAVE_LIBREADLINE
1219 static char histfile[1024];
1220 static int nr_history_lines = 0;
1224 initialize_readline (void)
1226 #ifdef HAVE_LIBREADLINE
1229 home = getenv ("HOME");
1231 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1233 (void) read_history (histfile);
1236 rl_readline_name = "guestfish";
1237 rl_attempted_completion_function = do_completion;
1239 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1240 * call the readline(), which happens later. Therefore, these
1241 * provide default values which can be overridden by the user if
1244 (void) rl_variable_bind ("completion-ignore-case", "on");
1249 cleanup_readline (void)
1251 #ifdef HAVE_LIBREADLINE
1254 if (histfile[0] != '\0') {
1255 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1262 #ifdef HAVE_APPEND_HISTORY
1263 (void) append_history (nr_history_lines, histfile);
1265 (void) write_history (histfile);
1272 #ifdef HAVE_LIBREADLINE
1274 add_history_line (const char *line)
1282 xwrite (int fd, const void *v_buf, size_t len)
1285 const char *buf = v_buf;
1288 r = write (fd, buf, len);
1300 /* Resolve the special "win:..." form for Windows-specific paths.
1301 * This always returns a newly allocated string which is freed by the
1302 * caller function in "cmds.c".
1305 resolve_win_path (const char *path)
1310 if (STRCASENEQLEN (path, "win:", 4)) {
1311 ret = strdup (path);
1319 /* Drop drive letter, if it's "C:". */
1320 if (STRCASEEQLEN (path, "c:", 2))
1330 ret = strdup (path);
1336 /* Blindly convert any backslashes into forward slashes. Is this good? */
1337 for (i = 0; i < strlen (ret); ++i)
1341 char *t = guestfs_case_sensitive_path (g, ret);
1348 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1349 * The caller (cmds.c) will call free_file_in after the command has
1350 * run which should clean up resources.
1352 static char *file_in_heredoc (const char *endmarker);
1353 static char *file_in_tmpfile = NULL;
1356 file_in (const char *arg)
1360 if (STREQ (arg, "-")) {
1361 ret = strdup ("/dev/stdin");
1367 else if (STRPREFIX (arg, "-<<")) {
1368 const char *endmarker = &arg[3];
1369 if (*endmarker == '\0') {
1370 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1374 ret = file_in_heredoc (endmarker);
1390 file_in_heredoc (const char *endmarker)
1392 TMP_TEMPLATE_ON_STACK (template);
1393 file_in_tmpfile = strdup (template);
1394 if (file_in_tmpfile == NULL) {
1399 int fd = mkstemp (file_in_tmpfile);
1405 size_t markerlen = strlen (endmarker);
1407 char buffer[BUFSIZ];
1408 int write_error = 0;
1409 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1410 /* Look for "END"<EOF> or "END\n" in input. */
1411 size_t blen = strlen (buffer);
1412 if (STREQLEN (buffer, endmarker, markerlen) &&
1413 (blen == markerlen ||
1414 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1417 if (xwrite (fd, buffer, blen) == -1) {
1418 if (!write_error) perror ("write");
1420 /* continue reading up to the end marker */
1424 /* Reached EOF of stdin without finding the end marker, which
1425 * is likely to be an error.
1427 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1428 program_name, endmarker);
1437 if (close (fd) == -1) {
1442 return file_in_tmpfile;
1445 unlink (file_in_tmpfile);
1448 free (file_in_tmpfile);
1449 file_in_tmpfile = NULL;
1454 free_file_in (char *s)
1456 if (file_in_tmpfile) {
1457 if (unlink (file_in_tmpfile) == -1)
1458 perror (file_in_tmpfile);
1459 file_in_tmpfile = NULL;
1462 /* Free the device or file name which was strdup'd in file_in().
1463 * Note it's not immediately clear, but for -<< heredocs,
1464 * s == file_in_tmpfile, so this frees up that buffer.
1469 /* Resolve the special FileOut paths ("-" or filename).
1470 * The caller (cmds.c) will call free (str) after the command has run.
1473 file_out (const char *arg)
1477 if (STREQ (arg, "-"))
1478 ret = strdup ("/dev/stdout");
1489 /* Read a passphrase ('Key') from /dev/tty with echo off.
1490 * The caller (cmds.c) will call free on the string afterwards.
1491 * Based on the code in cryptsetup file lib/utils.c.
1494 read_key (const char *param)
1497 struct termios orig, temp;
1500 /* Read and write to /dev/tty if available. */
1501 if (keys_from_stdin ||
1502 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1507 /* Print the prompt and set no echo. */
1508 int tty = isatty (fileno (infp));
1511 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1514 if (tcgetattr (fileno (infp), &orig) == -1) {
1515 perror ("tcgetattr");
1518 memcpy (&temp, &orig, sizeof temp);
1519 temp.c_lflag &= ~ECHO;
1521 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1528 len = getline (&ret, &n, infp);
1535 /* Remove the terminating \n if there is one. */
1536 if (len > 0 && ret[len-1] == '\n')
1540 /* Restore echo, close file descriptor. */
1543 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1547 fclose (infp); /* outfp == infp, so this is closed also */