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>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
48 static void set_up_terminal (void);
49 static void prepare_drives (struct drv *drv);
50 static int launch (void);
51 static void interactive (void);
52 static void shell_script (void);
53 static void script (int prompt);
54 static void cmdline (char *argv[], int optind, int argc);
55 static void initialize_readline (void);
56 static void cleanup_readline (void);
57 #ifdef HAVE_LIBREADLINE
58 static void add_history_line (const char *);
61 static int override_progress_bars = -1;
63 /* Currently open libguestfs handle. */
69 int remote_control_listen = 0;
70 int remote_control = 0;
71 int exit_on_error = 1;
73 int keys_from_stdin = 0;
75 const char *libvirt_uri = NULL;
78 int have_terminfo = 0;
79 int progress_bars = 0;
81 static void __attribute__((noreturn))
84 if (status != EXIT_SUCCESS)
85 fprintf (stderr, _("Try `%s --help' for more information.\n"),
89 _("%s: guest filesystem shell\n"
90 "%s lets you edit virtual machine filesystems\n"
91 "Copyright (C) 2009-2010 Red Hat Inc.\n"
93 " %s [--options] cmd [: cmd : cmd ...]\n"
94 " %s [--ro] -i -a disk-image\n"
95 " %s [--ro] -i -d libvirt-domain\n"
96 "or for interactive use:\n"
98 "or from a shell script:\n"
104 " -h|--cmd-help List available commands\n"
105 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
106 " -a|--add image Add image\n"
107 " -c|--connect uri Specify libvirt URI for -d option\n"
108 " -d|--domain guest Add disks from libvirt guest\n"
109 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
110 " --echo-keys Don't turn off echo for passphrases\n"
111 " -f|--file file Read commands from file\n"
112 " --format[=raw|..] Force disk format for -a option\n"
113 " -i|--inspector Automatically mount filesystems\n"
114 " --keys-from-stdin Read passphrases from stdin\n"
115 " --listen Listen for remote commands\n"
116 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
117 " -n|--no-sync Don't autosync\n"
118 " -N|--new type Create prepared disk (test1.img, ...)\n"
119 " --progress-bars Enable progress bars even when not interactive\n"
120 " --no-progress-bars Disable progress bars\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 " -V|--version Display version and exit\n"
126 " -x Echo each command before executing it\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);
149 enum { HELP_OPTION = CHAR_MAX + 1 };
151 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
152 static const struct option long_options[] = {
153 { "add", 1, 0, 'a' },
154 { "cmd-help", 2, 0, 'h' },
155 { "connect", 1, 0, 'c' },
156 { "domain", 1, 0, 'd' },
157 { "echo-keys", 0, 0, 0 },
158 { "file", 1, 0, 'f' },
159 { "format", 2, 0, 0 },
160 { "help", 0, 0, HELP_OPTION },
161 { "inspector", 0, 0, 'i' },
162 { "keys-from-stdin", 0, 0, 0 },
163 { "listen", 0, 0, 0 },
164 { "mount", 1, 0, 'm' },
165 { "new", 1, 0, 'N' },
166 { "no-dest-paths", 0, 0, 'D' },
167 { "no-sync", 0, 0, 'n' },
168 { "progress-bars", 0, 0, 0 },
169 { "no-progress-bars", 0, 0, 0 },
170 { "remote", 2, 0, 0 },
172 { "selinux", 0, 0, 0 },
173 { "verbose", 0, 0, 'v' },
174 { "version", 0, 0, 'V' },
177 struct drv *drvs = NULL;
179 struct mp *mps = NULL;
181 char *p, *file = NULL;
182 const char *format = NULL;
186 int next_prepared_drive = 1;
188 initialize_readline ();
190 memset (&sa, 0, sizeof sa);
191 sa.sa_handler = SIG_IGN;
192 sa.sa_flags = SA_RESTART;
193 sigaction (SIGPIPE, &sa, NULL);
195 /* guestfs_create is meant to be a lightweight operation, so
196 * it's OK to do it early here.
198 g = guestfs_create ();
200 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
204 /* If developing, add ./appliance to the path. Note that libtools
205 * interferes with this because uninstalled guestfish is a shell
206 * script that runs the real program with an absolute path. Detect
209 * BUT if LIBGUESTFS_PATH environment variable is already set by
210 * the user, then don't override it.
212 if (getenv ("LIBGUESTFS_PATH") == NULL &&
214 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
215 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
217 /* CAUTION: we are careful to modify argv[0] here, only after
218 * using it just above.
220 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
221 * of the original, in case it's needed below.
223 char *real_argv0 = argv[0];
224 argv[0] = bad_cast (program_name);
227 c = getopt_long (argc, argv, options, long_options, &option_index);
231 case 0: /* options which are long only */
232 if (STREQ (long_options[option_index].name, "listen"))
233 remote_control_listen = 1;
234 else if (STREQ (long_options[option_index].name, "remote")) {
236 if (sscanf (optarg, "%d", &remote_control) != 1) {
237 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
238 program_name, optarg);
242 p = getenv ("GUESTFISH_PID");
243 if (!p || sscanf (p, "%d", &remote_control) != 1) {
244 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
245 " to the PID of the remote process\n"),
250 } else if (STREQ (long_options[option_index].name, "selinux")) {
251 guestfs_set_selinux (g, 1);
252 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
254 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
255 override_progress_bars = 1;
256 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
257 override_progress_bars = 0;
258 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
260 } else if (STREQ (long_options[option_index].name, "format")) {
261 if (!optarg || STREQ (optarg, ""))
266 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
267 program_name, long_options[option_index].name, option_index);
285 complete_dest_paths = 0;
290 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
301 r = display_command (optarg);
302 else if (argv[optind] && argv[optind][0] != '-')
303 r = display_command (argv[optind++]);
307 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
323 if (STRCASEEQ (optarg, "list") ||
324 STRCASEEQ (optarg, "help") ||
325 STRCASEEQ (optarg, "h") ||
326 STRCASEEQ (optarg, "?")) {
327 list_prepared_drives ();
330 drv = malloc (sizeof (struct drv));
336 if (asprintf (&drv->N.filename, "test%d.img",
337 next_prepared_drive++) == -1) {
341 drv->N.data = create_prepared_file (optarg, drv->N.filename);
342 drv->N.data_free = free_prep_data;
343 drv->N.device = NULL; /* filled in by add_drives */
365 usage (EXIT_SUCCESS);
368 usage (EXIT_FAILURE);
372 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
373 * previously, if we have -i without any drives but with something
374 * on the command line, it must be old-style syntax.
376 if (inspector && drvs == NULL && optind < argc) {
377 while (optind < argc) {
378 if (strchr (argv[optind], '/') ||
379 access (argv[optind], F_OK) == 0) { /* simulate -a option */
380 drv = malloc (sizeof (struct drv));
386 drv->a.filename = argv[optind];
387 drv->a.format = NULL;
390 } else { /* simulate -d option */
391 drv = malloc (sizeof (struct drv));
397 drv->d.guest = argv[optind];
406 /* If we've got drives to add, add them now. */
407 add_drives (drvs, 'a');
409 /* If we've got mountpoints or prepared drives or -i option, we must
410 * launch the guest and mount them.
412 if (next_prepared_drive > 1 || mps != NULL || inspector) {
413 /* RHBZ#612178: If --listen flag is given, then we will fork into
414 * the background in rc_listen(). However you can't do this while
415 * holding a libguestfs handle open because the recovery process
416 * will think the main program has died and kill qemu. Therefore
417 * don't use the recovery process for this case. (A better
418 * solution would be to call launch () etc after the fork, but
419 * that greatly complicates the code here).
421 if (remote_control_listen)
422 guestfs_set_recovery_proc (g, 0);
424 if (launch () == -1) exit (EXIT_FAILURE);
429 prepare_drives (drvs);
433 /* Free up data structures, no longer needed after this point. */
437 /* Remote control? */
438 if (remote_control_listen && remote_control) {
440 _("%s: cannot use --listen and --remote options at the same time\n"),
445 if (remote_control_listen) {
448 _("%s: extra parameters on the command line with --listen flag\n"),
454 _("%s: cannot use --listen and --file options at the same time\n"),
461 /* -f (file) parameter? */
464 if (open (file, O_RDONLY) == -1) {
470 /* Decide if we display progress bars. */
472 override_progress_bars >= 0
473 ? override_progress_bars
474 : (optind >= argc && isatty (0));
477 guestfs_set_progress_callback (g, progress_callback, NULL);
479 /* Interactive, shell script, or command(s) on the command line? */
480 if (optind >= argc) {
487 cmdline (argv, optind, argc);
494 /* The <term.h> header file which defines this has "issues". */
495 extern int tgetent (char *, const char *);
498 set_up_terminal (void)
500 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
501 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
503 char *term = getenv ("TERM");
505 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
509 int r = tgetent (NULL, term);
511 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
515 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
524 pod2text (const char *name, const char *shortdesc, const char *str)
528 fp = popen ("pod2text", "w");
530 /* pod2text failed, maybe not found, so let's just print the
531 * source instead, since that's better than doing nothing.
533 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
536 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
542 prepare_drives (struct drv *drv)
545 prepare_drives (drv->next);
546 if (drv->type == drv_N)
547 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
554 if (guestfs_is_config (g)) {
555 if (guestfs_launch (g) == -1)
573 #define FISH "><fs> "
575 static char *line_read = NULL;
580 #ifdef HAVE_LIBREADLINE
588 line_read = readline (prompt ? FISH : "");
590 if (line_read && *line_read)
591 add_history_line (line_read);
596 #endif /* HAVE_LIBREADLINE */
598 static char buf[8192];
601 if (prompt) printf (FISH);
602 line_read = fgets (buf, sizeof buf, stdin);
605 len = strlen (line_read);
606 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
620 int global_exit_on_error = !prompt;
625 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
626 "editing virtual machine filesystems.\n"
628 "Type: 'help' for help on commands\n"
629 " 'man' to read the manual\n"
630 " 'quit' to quit the shell\n"
634 print_inspect_prompt ();
642 exit_on_error = global_exit_on_error;
644 buf = rl_gets (prompt);
650 /* Skip any initial whitespace before the command. */
652 while (*buf && c_isspace (*buf))
657 /* If the next character is '#' then this is a comment. */
658 if (*buf == '#') continue;
660 /* If the next character is '!' then pass the whole lot to system(3). */
668 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
669 WEXITSTATUS (r) != 0)
675 /* If the next character is '-' allow the command to fail without
676 * exiting on error (just for this one command though).
684 /* Get the command (cannot be quoted). */
685 len = strcspn (buf, " \t");
687 if (len == 0) continue;
691 if (buf[len] == '\0') {
698 p += strspn (p, " \t");
700 /* Get the parameters. */
701 while (*p && i < sizeof argv / sizeof argv[0]) {
704 /* Parameters which start with quotes or pipes are treated
705 * specially. Bare parameters are delimited by whitespace.
709 len = strcspn (p, "\"");
710 if (p[len] == '\0') {
711 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
712 if (exit_on_error) exit (EXIT_FAILURE);
715 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
717 _("%s: command arguments not separated by whitespace\n"),
719 if (exit_on_error) exit (EXIT_FAILURE);
723 pend = p[len+1] ? &p[len+2] : &p[len+1];
724 } else if (*p == '\'') {
726 len = strcspn (p, "'");
727 if (p[len] == '\0') {
728 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
729 if (exit_on_error) exit (EXIT_FAILURE);
732 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
734 _("%s: command arguments not separated by whitespace\n"),
736 if (exit_on_error) exit (EXIT_FAILURE);
740 pend = p[len+1] ? &p[len+2] : &p[len+1];
741 } else if (*p == '|') {
746 } else if (*p == '[') {
750 while (*pend && c != 0) {
751 if (*pend == '[') c++;
752 else if (*pend == ']') c--;
757 _("%s: unterminated \"[...]\" sequence\n"), program_name);
758 if (exit_on_error) exit (EXIT_FAILURE);
761 if (*pend && (*pend != ' ' && *pend != '\t')) {
763 _("%s: command arguments not separated by whitespace\n"),
765 if (exit_on_error) exit (EXIT_FAILURE);
770 } else if (*p != ' ' && *p != '\t') {
771 /* If the first character is a ~ then note that this parameter
772 * is a candidate for ~username expansion. NB this does not
773 * apply to quoted parameters.
775 tilde_candidate = *p == '~';
776 len = strcspn (p, " \t");
783 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
788 if (!tilde_candidate)
791 argv[i] = try_tilde_expansion (p);
796 p += strspn (p, " \t");
799 if (i == sizeof argv / sizeof argv[0]) {
800 fprintf (stderr, _("%s: too many arguments\n"), program_name);
801 if (exit_on_error) exit (EXIT_FAILURE);
808 if (issue_command (cmd, argv, pipe) == -1) {
809 if (exit_on_error) exit (EXIT_FAILURE);
814 if (prompt) printf ("\n");
818 cmdline (char *argv[], int optind, int argc)
825 if (optind >= argc) return;
827 cmd = argv[optind++];
828 if (STREQ (cmd, ":")) {
829 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
833 /* Allow -cmd on the command line to mean (temporarily) override
834 * the normal exit on error (RHBZ#578407).
841 params = &argv[optind];
843 /* Search for end of command list or ":" ... */
844 while (optind < argc && STRNEQ (argv[optind], ":"))
847 if (optind == argc) {
848 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
852 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
854 cmdline (argv, optind+1, argc);
859 issue_command (const char *cmd, char *argv[], const char *pipecmd)
862 int stdout_saved_fd = -1;
866 reset_progress_bar ();
868 /* This counts the commands issued, starting at 1. */
871 /* For | ... commands. Annoyingly we can't use popen(3) here. */
875 if (fflush (stdout) == EOF) {
876 perror ("failed to flush standard output");
880 perror ("pipe failed");
889 if (pid == 0) { /* Child process. */
891 if (dup2 (fd[0], 0) < 0) {
892 perror ("dup2 of stdin failed");
896 r = system (pipecmd);
901 _exit (WEXITSTATUS (r));
904 if ((stdout_saved_fd = dup (1)) < 0) {
905 perror ("failed to dup stdout");
909 if (dup2 (fd[1], 1) < 0) {
910 perror ("failed to dup stdout");
911 close (stdout_saved_fd);
917 for (argc = 0; argv[argc] != NULL; ++argc)
920 /* If --remote was set, then send this command to a remote process. */
922 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
924 /* Otherwise execute it locally. */
925 else if (STRCASEEQ (cmd, "help")) {
930 r = display_command (argv[0]);
932 else if (STRCASEEQ (cmd, "quit") ||
933 STRCASEEQ (cmd, "exit") ||
934 STRCASEEQ (cmd, "q")) {
939 r = run_action (cmd, argc, argv);
941 /* Always flush stdout after every command, so that messages, results
942 * etc appear immediately.
944 if (fflush (stdout) == EOF) {
945 perror ("failed to flush standard output");
951 if (dup2 (stdout_saved_fd, 1) < 0) {
952 perror ("failed to dup2 standard output");
955 close (stdout_saved_fd);
956 if (waitpid (pid, NULL, 0) < 0) {
957 perror ("waiting for command to complete");
966 list_builtin_commands (void)
968 /* help and quit should appear at the top */
969 printf ("%-20s %s\n",
970 "help", _("display a list of commands or help on a command"));
971 printf ("%-20s %s\n",
972 "quit", _("quit guestfish"));
974 /* actions are printed after this (see list_commands) */
978 display_builtin_command (const char *cmd)
980 /* help for actions is auto-generated, see display_command */
982 if (STRCASEEQ (cmd, "help")) {
983 printf (_("help - display a list of commands or help on a command\n"
988 else if (STRCASEEQ (cmd, "quit") ||
989 STRCASEEQ (cmd, "exit") ||
990 STRCASEEQ (cmd, "q")) {
991 printf (_("quit - quit guestfish\n"
996 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1002 /* This is printed when the user types in an unknown command for the
1003 * first command issued. A common case is the user doing:
1004 * guestfish disk.img
1005 * expecting guestfish to open 'disk.img' (in fact, this tried to
1006 * run a command 'disk.img').
1009 extended_help_message (void)
1012 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1013 "For a list of commands: guestfish -h\n"
1014 "For complete documentation: man guestfish\n"));
1018 free_strings (char **argv)
1022 for (argc = 0; argv[argc] != NULL; ++argc)
1028 count_strings (char *const *argv)
1032 for (c = 0; argv[c]; ++c)
1038 print_strings (char *const *argv)
1042 for (argc = 0; argv[argc] != NULL; ++argc)
1043 printf ("%s\n", argv[argc]);
1047 print_table (char *const *argv)
1051 for (i = 0; argv[i] != NULL; i += 2)
1052 printf ("%s: %s\n", argv[i], argv[i+1]);
1056 is_true (const char *str)
1059 STRCASENEQ (str, "0") &&
1060 STRCASENEQ (str, "f") &&
1061 STRCASENEQ (str, "false") &&
1062 STRCASENEQ (str, "n") &&
1063 STRCASENEQ (str, "no");
1066 /* Free strings from a non-NULL terminated char** */
1068 free_n_strings (char **str, size_t len)
1072 for (i = 0; i < len; i++) {
1079 parse_string_list (const char *str)
1082 size_t argv_len = 0;
1084 /* Current position pointer */
1085 const char *p = str;
1087 /* Token might be simple:
1090 * 'This is a single token'
1091 * or contain embedded single-quoted sections:
1092 * This' is a sing'l'e to'ken
1094 * The latter may seem over-complicated, but it's what a normal shell does.
1095 * Not doing it risks surprising somebody.
1097 * This outer loop is over complete tokens.
1103 /* Skip leading whitespace */
1104 p += strspn (p, " \t");
1108 /* This loop is over token 'fragments'. A token can be in multiple bits if
1109 * it contains single quotes. We also treat both sides of an escaped quote
1110 * as separate fragments because we can't just copy it: we have to remove
1113 while (*p && (!c_isblank (*p) || in_quote)) {
1114 const char *end = p;
1116 /* Check if the fragment starts with a quote */
1118 /* Toggle in_quote */
1119 in_quote = !in_quote;
1121 /* Skip the quote */
1125 /* If we're in a quote, look for an end quote */
1127 end += strcspn (end, "'");
1130 /* Otherwise, look for whitespace or a quote */
1132 end += strcspn (end, " \t'");
1135 /* Grow the token to accommodate the fragment */
1136 size_t tok_end = tok_len;
1138 char *tok_new = realloc (tok, tok_len + 1);
1139 if (NULL == tok_new) {
1141 free_n_strings (argv, argv_len);
1143 exit (EXIT_FAILURE);
1147 /* Check if we stopped on an escaped quote */
1148 if ('\'' == *end && end != p && *(end-1) == '\\') {
1149 /* Add everything before \' to the token */
1150 memcpy (&tok[tok_end], p, end - p - 1);
1153 tok[tok_len-1] = '\'';
1155 /* Already processed the quote */
1160 /* Add the whole fragment */
1161 memcpy (&tok[tok_end], p, end - p);
1167 /* We've reached the end of a token. We shouldn't still be in quotes. */
1169 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1171 free_n_strings (argv, argv_len);
1176 /* Add this token if there is one. There might not be if there was
1177 * whitespace at the end of the input string */
1179 /* Add the NULL terminator */
1180 tok[tok_len] = '\0';
1182 /* Add the argument to the argument list */
1184 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1185 if (NULL == argv_new) {
1187 free_n_strings (argv, argv_len-1);
1189 exit (EXIT_FAILURE);
1193 argv[argv_len-1] = tok;
1197 /* NULL terminate the argument list */
1199 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1200 if (NULL == argv_new) {
1202 free_n_strings (argv, argv_len-1);
1203 exit (EXIT_FAILURE);
1207 argv[argv_len-1] = NULL;
1212 #ifdef HAVE_LIBREADLINE
1213 static char histfile[1024];
1214 static int nr_history_lines = 0;
1218 initialize_readline (void)
1220 #ifdef HAVE_LIBREADLINE
1223 home = getenv ("HOME");
1225 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1227 (void) read_history (histfile);
1230 rl_readline_name = "guestfish";
1231 rl_attempted_completion_function = do_completion;
1233 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1234 * call the readline(), which happens later. Therefore, these
1235 * provide default values which can be overridden by the user if
1238 (void) rl_variable_bind ("completion-ignore-case", "on");
1243 cleanup_readline (void)
1245 #ifdef HAVE_LIBREADLINE
1248 if (histfile[0] != '\0') {
1249 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1256 #ifdef HAVE_APPEND_HISTORY
1257 (void) append_history (nr_history_lines, histfile);
1259 (void) write_history (histfile);
1266 #ifdef HAVE_LIBREADLINE
1268 add_history_line (const char *line)
1276 xwrite (int fd, const void *v_buf, size_t len)
1279 const char *buf = v_buf;
1282 r = write (fd, buf, len);
1294 /* Resolve the special "win:..." form for Windows-specific paths.
1295 * This always returns a newly allocated string which is freed by the
1296 * caller function in "cmds.c".
1299 resolve_win_path (const char *path)
1304 if (STRCASENEQLEN (path, "win:", 4)) {
1305 ret = strdup (path);
1313 /* Drop drive letter, if it's "C:". */
1314 if (STRCASEEQLEN (path, "c:", 2))
1324 ret = strdup (path);
1330 /* Blindly convert any backslashes into forward slashes. Is this good? */
1331 for (i = 0; i < strlen (ret); ++i)
1335 char *t = guestfs_case_sensitive_path (g, ret);
1342 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1343 * The caller (cmds.c) will call free_file_in after the command has
1344 * run which should clean up resources.
1346 static char *file_in_heredoc (const char *endmarker);
1347 static char *file_in_tmpfile = NULL;
1350 file_in (const char *arg)
1354 if (STREQ (arg, "-")) {
1355 ret = strdup ("/dev/stdin");
1361 else if (STRPREFIX (arg, "-<<")) {
1362 const char *endmarker = &arg[3];
1363 if (*endmarker == '\0') {
1364 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1368 ret = file_in_heredoc (endmarker);
1384 file_in_heredoc (const char *endmarker)
1386 TMP_TEMPLATE_ON_STACK (template);
1387 file_in_tmpfile = strdup (template);
1388 if (file_in_tmpfile == NULL) {
1393 int fd = mkstemp (file_in_tmpfile);
1399 size_t markerlen = strlen (endmarker);
1401 char buffer[BUFSIZ];
1402 int write_error = 0;
1403 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1404 /* Look for "END"<EOF> or "END\n" in input. */
1405 size_t blen = strlen (buffer);
1406 if (STREQLEN (buffer, endmarker, markerlen) &&
1407 (blen == markerlen ||
1408 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1411 if (xwrite (fd, buffer, blen) == -1) {
1412 if (!write_error) perror ("write");
1414 /* continue reading up to the end marker */
1418 /* Reached EOF of stdin without finding the end marker, which
1419 * is likely to be an error.
1421 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1422 program_name, endmarker);
1431 if (close (fd) == -1) {
1436 return file_in_tmpfile;
1439 unlink (file_in_tmpfile);
1442 free (file_in_tmpfile);
1443 file_in_tmpfile = NULL;
1448 free_file_in (char *s)
1450 if (file_in_tmpfile) {
1451 if (unlink (file_in_tmpfile) == -1)
1452 perror (file_in_tmpfile);
1453 file_in_tmpfile = NULL;
1456 /* Free the device or file name which was strdup'd in file_in().
1457 * Note it's not immediately clear, but for -<< heredocs,
1458 * s == file_in_tmpfile, so this frees up that buffer.
1463 /* Resolve the special FileOut paths ("-" or filename).
1464 * The caller (cmds.c) will call free (str) after the command has run.
1467 file_out (const char *arg)
1471 if (STREQ (arg, "-"))
1472 ret = strdup ("/dev/stdout");