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 /* Return from parse_command_line. See description below. */
49 struct parsed_command {
56 static void set_up_terminal (void);
57 static void prepare_drives (struct drv *drv);
58 static int launch (void);
59 static void interactive (void);
60 static void shell_script (void);
61 static void script (int prompt);
62 static void cmdline (char *argv[], int optind, int argc);
63 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
64 static void initialize_readline (void);
65 static void cleanup_readline (void);
66 #ifdef HAVE_LIBREADLINE
67 static void add_history_line (const char *);
70 static int override_progress_bars = -1;
72 /* Currently open libguestfs handle. */
78 int remote_control_listen = 0;
79 int remote_control_csh = 0;
80 int remote_control = 0;
82 int keys_from_stdin = 0;
84 const char *libvirt_uri = NULL;
87 int have_terminfo = 0;
88 int progress_bars = 0;
90 static void __attribute__((noreturn))
93 if (status != EXIT_SUCCESS)
94 fprintf (stderr, _("Try `%s --help' for more information.\n"),
98 _("%s: guest filesystem shell\n"
99 "%s lets you edit virtual machine filesystems\n"
100 "Copyright (C) 2009-2010 Red Hat Inc.\n"
102 " %s [--options] cmd [: cmd : cmd ...]\n"
103 " %s [--ro] -i -a disk-image\n"
104 " %s [--ro] -i -d libvirt-domain\n"
105 "or for interactive use:\n"
107 "or from a shell script:\n"
113 " -h|--cmd-help List available commands\n"
114 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
115 " -a|--add image Add image\n"
116 " -c|--connect uri Specify libvirt URI for -d option\n"
117 " --csh Make --listen csh-compatible\n"
118 " -d|--domain guest Add disks from libvirt guest\n"
119 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
120 " --echo-keys Don't turn off echo for passphrases\n"
121 " -f|--file file Read commands from file\n"
122 " --format[=raw|..] Force disk format for -a option\n"
123 " -i|--inspector Automatically mount filesystems\n"
124 " --keys-from-stdin Read passphrases from stdin\n"
125 " --listen Listen for remote commands\n"
126 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
127 " -n|--no-sync Don't autosync\n"
128 " -N|--new type Create prepared disk (test1.img, ...)\n"
129 " --progress-bars Enable progress bars even when not interactive\n"
130 " --no-progress-bars Disable progress bars\n"
131 " --remote[=pid] Send commands to remote %s\n"
132 " -r|--ro Mount read-only\n"
133 " --selinux Enable SELinux support\n"
134 " -v|--verbose Verbose messages\n"
135 " -V|--version Display version and exit\n"
136 " -x Echo each command before executing it\n"
137 "For more information, see the manpage %s(1).\n"),
138 program_name, program_name, program_name,
139 program_name, program_name, program_name,
140 program_name, program_name, program_name);
146 main (int argc, char *argv[])
148 /* Set global program name that is not polluted with libtool artifacts. */
149 set_program_name (argv[0]);
151 atexit (close_stdout);
153 setlocale (LC_ALL, "");
154 bindtextdomain (PACKAGE, LOCALEBASEDIR);
155 textdomain (PACKAGE);
159 enum { HELP_OPTION = CHAR_MAX + 1 };
161 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
162 static const struct option long_options[] = {
163 { "add", 1, 0, 'a' },
164 { "cmd-help", 2, 0, 'h' },
165 { "connect", 1, 0, 'c' },
167 { "domain", 1, 0, 'd' },
168 { "echo-keys", 0, 0, 0 },
169 { "file", 1, 0, 'f' },
170 { "format", 2, 0, 0 },
171 { "help", 0, 0, HELP_OPTION },
172 { "inspector", 0, 0, 'i' },
173 { "keys-from-stdin", 0, 0, 0 },
174 { "listen", 0, 0, 0 },
175 { "mount", 1, 0, 'm' },
176 { "new", 1, 0, 'N' },
177 { "no-dest-paths", 0, 0, 'D' },
178 { "no-sync", 0, 0, 'n' },
179 { "progress-bars", 0, 0, 0 },
180 { "no-progress-bars", 0, 0, 0 },
181 { "remote", 2, 0, 0 },
184 { "selinux", 0, 0, 0 },
185 { "verbose", 0, 0, 'v' },
186 { "version", 0, 0, 'V' },
189 struct drv *drvs = NULL;
191 struct mp *mps = NULL;
193 char *p, *file = NULL;
194 const char *format = NULL;
198 int next_prepared_drive = 1;
200 initialize_readline ();
202 memset (&sa, 0, sizeof sa);
203 sa.sa_handler = SIG_IGN;
204 sa.sa_flags = SA_RESTART;
205 sigaction (SIGPIPE, &sa, NULL);
207 /* guestfs_create is meant to be a lightweight operation, so
208 * it's OK to do it early here.
210 g = guestfs_create ();
212 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
216 /* If developing, add ./appliance to the path. Note that libtools
217 * interferes with this because uninstalled guestfish is a shell
218 * script that runs the real program with an absolute path. Detect
221 * BUT if LIBGUESTFS_PATH environment variable is already set by
222 * the user, then don't override it.
224 if (getenv ("LIBGUESTFS_PATH") == NULL &&
226 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
227 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
229 /* CAUTION: we are careful to modify argv[0] here, only after
230 * using it just above.
232 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
233 * of the original, in case it's needed below.
235 //char *real_argv0 = argv[0];
236 argv[0] = bad_cast (program_name);
239 c = getopt_long (argc, argv, options, long_options, &option_index);
243 case 0: /* options which are long only */
244 if (STREQ (long_options[option_index].name, "listen"))
245 remote_control_listen = 1;
246 else if (STREQ (long_options[option_index].name, "remote")) {
248 if (sscanf (optarg, "%d", &remote_control) != 1) {
249 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
250 program_name, optarg);
254 p = getenv ("GUESTFISH_PID");
255 if (!p || sscanf (p, "%d", &remote_control) != 1) {
256 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
257 " to the PID of the remote process\n"),
262 } else if (STREQ (long_options[option_index].name, "selinux")) {
263 guestfs_set_selinux (g, 1);
264 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
266 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
267 override_progress_bars = 1;
268 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
269 override_progress_bars = 0;
270 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
272 } else if (STREQ (long_options[option_index].name, "format")) {
273 if (!optarg || STREQ (optarg, ""))
277 } else if (STREQ (long_options[option_index].name, "csh")) {
278 remote_control_csh = 1;
280 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
281 program_name, long_options[option_index].name, option_index);
299 complete_dest_paths = 0;
304 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
315 r = display_command (optarg);
316 else if (argv[optind] && argv[optind][0] != '-')
317 r = display_command (argv[optind++]);
321 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
337 if (STRCASEEQ (optarg, "list") ||
338 STRCASEEQ (optarg, "help") ||
339 STRCASEEQ (optarg, "h") ||
340 STRCASEEQ (optarg, "?")) {
341 list_prepared_drives ();
344 drv = malloc (sizeof (struct drv));
352 if (asprintf (&drv->N.filename, "test%d.img",
353 next_prepared_drive++) == -1) {
357 drv->N.data = create_prepared_file (optarg, drv->N.filename);
358 drv->N.data_free = free_prep_data;
384 usage (EXIT_SUCCESS);
387 usage (EXIT_FAILURE);
391 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
392 * previously, if we have -i without any drives but with something
393 * on the command line, it must be old-style syntax.
395 if (inspector && drvs == NULL && optind < argc) {
396 while (optind < argc) {
397 if (strchr (argv[optind], '/') ||
398 access (argv[optind], F_OK) == 0) { /* simulate -a option */
399 drv = malloc (sizeof (struct drv));
405 drv->a.filename = argv[optind];
406 drv->a.format = NULL;
409 } else { /* simulate -d option */
410 drv = malloc (sizeof (struct drv));
416 drv->d.guest = argv[optind];
425 /* If we've got drives to add, add them now. */
426 add_drives (drvs, 'a');
428 /* If we've got mountpoints or prepared drives or -i option, we must
429 * launch the guest and mount them.
431 if (next_prepared_drive > 1 || mps != NULL || inspector) {
432 /* RHBZ#612178: If --listen flag is given, then we will fork into
433 * the background in rc_listen(). However you can't do this while
434 * holding a libguestfs handle open because the recovery process
435 * will think the main program has died and kill qemu. Therefore
436 * don't use the recovery process for this case. (A better
437 * solution would be to call launch () etc after the fork, but
438 * that greatly complicates the code here).
440 if (remote_control_listen)
441 guestfs_set_recovery_proc (g, 0);
443 if (launch () == -1) exit (EXIT_FAILURE);
448 prepare_drives (drvs);
452 /* Free up data structures, no longer needed after this point. */
456 /* Remote control? */
457 if (remote_control_listen && remote_control) {
459 _("%s: cannot use --listen and --remote options at the same time\n"),
464 if (remote_control_listen) {
467 _("%s: extra parameters on the command line with --listen flag\n"),
473 _("%s: cannot use --listen and --file options at the same time\n"),
480 /* -f (file) parameter? */
483 if (open (file, O_RDONLY) == -1) {
489 /* Decide if we display progress bars. */
491 override_progress_bars >= 0
492 ? override_progress_bars
493 : (optind >= argc && isatty (0));
496 guestfs_set_progress_callback (g, progress_callback, NULL);
498 /* Interactive, shell script, or command(s) on the command line? */
499 if (optind >= argc) {
506 cmdline (argv, optind, argc);
513 /* The <term.h> header file which defines this has "issues". */
514 extern int tgetent (char *, const char *);
517 set_up_terminal (void)
519 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
520 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
522 char *term = getenv ("TERM");
524 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
528 int r = tgetent (NULL, term);
530 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
534 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
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->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';
617 int global_exit_on_error = !prompt;
619 struct parsed_command pcmd;
623 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
624 "editing virtual machine filesystems.\n"
626 "Type: 'help' for help on commands\n"
627 " 'man' to read the manual\n"
628 " 'quit' to quit the shell\n"
632 print_inspect_prompt ();
638 exit_on_error = global_exit_on_error;
640 buf = rl_gets (prompt);
646 pcmd = parse_command_line (buf, &exit_on_error);
647 if (pcmd.status == -1 && exit_on_error)
649 if (pcmd.status == 1) {
650 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
651 if (exit_on_error) exit (EXIT_FAILURE);
655 if (prompt) printf ("\n");
658 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
659 * This destructively updates 'buf'.
661 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
662 * setting and to return the local setting (eg. if the command begins
665 * Returns in parsed_command.status:
666 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
667 * 0 = no guestfish command, but otherwise OK
670 static struct parsed_command
671 parse_command_line (char *buf, int *exit_on_error_rtn)
673 struct parsed_command pcmd;
678 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
680 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
681 * fields do not need to be, but this silences a gcc warning.
683 memset (&pcmd, 0, sizeof pcmd);
686 /* Skip any initial whitespace before the command. */
687 while (*buf && c_isspace (*buf))
695 /* If the next character is '#' then this is a comment. */
701 /* If the next character is '!' then pass the whole lot to system(3). */
706 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
707 WEXITSTATUS (r) != 0)
714 /* If the next character is '-' allow the command to fail without
715 * exiting on error (just for this one command though).
718 *exit_on_error_rtn = 0;
723 /* Get the command (cannot be quoted). */
724 len = strcspn (buf, " \t");
733 if (buf[len] == '\0') {
741 p += strspn (p, " \t");
743 /* Get the parameters. */
744 while (*p && i < argv_len) {
747 /* Parameters which start with quotes or pipes are treated
748 * specially. Bare parameters are delimited by whitespace.
752 len = strcspn (p, "\"");
753 if (p[len] == '\0') {
754 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
758 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
760 _("%s: command arguments not separated by whitespace\n"),
766 pend = p[len+1] ? &p[len+2] : &p[len+1];
767 } else if (*p == '\'') {
769 len = strcspn (p, "'");
770 if (p[len] == '\0') {
771 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
775 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
777 _("%s: command arguments not separated by whitespace\n"),
783 pend = p[len+1] ? &p[len+2] : &p[len+1];
784 } else if (*p == '|') {
788 } else if (*p != ' ' && *p != '\t') {
789 /* If the first character is a ~ then note that this parameter
790 * is a candidate for ~username expansion. NB this does not
791 * apply to quoted parameters.
793 tilde_candidate = *p == '~';
794 len = strcspn (p, " \t");
801 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
806 if (!tilde_candidate)
809 pcmd.argv[i] = try_tilde_expansion (p);
814 p += strspn (p, " \t");
818 fprintf (stderr, _("%s: too many arguments\n"), program_name);
830 cmdline (char *argv[], int optind, int argc)
838 if (optind >= argc) return;
840 cmd = argv[optind++];
841 if (STREQ (cmd, ":")) {
842 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
846 /* Allow -cmd on the command line to mean (temporarily) override
847 * the normal exit on error (RHBZ#578407).
854 params = &argv[optind];
856 /* Search for end of command list or ":" ... */
857 while (optind < argc && STRNEQ (argv[optind], ":"))
860 if (optind == argc) {
861 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
865 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
867 cmdline (argv, optind+1, argc);
871 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
872 * pass to the remote server (when issuing --remote commands). It
873 * does not cause issue_command itself to exit on error.
876 issue_command (const char *cmd, char *argv[], const char *pipecmd,
877 int rc_exit_on_error_flag)
880 int stdout_saved_fd = -1;
884 reset_progress_bar ();
886 /* This counts the commands issued, starting at 1. */
889 /* For | ... commands. Annoyingly we can't use popen(3) here. */
893 if (fflush (stdout) == EOF) {
894 perror ("failed to flush standard output");
898 perror ("pipe failed");
907 if (pid == 0) { /* Child process. */
909 if (dup2 (fd[0], 0) < 0) {
910 perror ("dup2 of stdin failed");
914 r = system (pipecmd);
919 _exit (WEXITSTATUS (r));
922 if ((stdout_saved_fd = dup (1)) < 0) {
923 perror ("failed to dup stdout");
927 if (dup2 (fd[1], 1) < 0) {
928 perror ("failed to dup stdout");
929 close (stdout_saved_fd);
935 for (argc = 0; argv[argc] != NULL; ++argc)
938 /* If --remote was set, then send this command to a remote process. */
940 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
942 /* Otherwise execute it locally. */
943 else if (STRCASEEQ (cmd, "help")) {
948 r = display_command (argv[0]);
950 else if (STRCASEEQ (cmd, "quit") ||
951 STRCASEEQ (cmd, "exit") ||
952 STRCASEEQ (cmd, "q")) {
957 r = run_action (cmd, argc, argv);
959 /* Always flush stdout after every command, so that messages, results
960 * etc appear immediately.
962 if (fflush (stdout) == EOF) {
963 perror ("failed to flush standard output");
969 if (dup2 (stdout_saved_fd, 1) < 0) {
970 perror ("failed to dup2 standard output");
973 close (stdout_saved_fd);
974 if (waitpid (pid, NULL, 0) < 0) {
975 perror ("waiting for command to complete");
984 list_builtin_commands (void)
986 /* help and quit should appear at the top */
987 printf ("%-20s %s\n",
988 "help", _("display a list of commands or help on a command"));
989 printf ("%-20s %s\n",
990 "quit", _("quit guestfish"));
992 /* actions are printed after this (see list_commands) */
996 display_builtin_command (const char *cmd)
998 /* help for actions is auto-generated, see display_command */
1000 if (STRCASEEQ (cmd, "help")) {
1001 printf (_("help - display a list of commands or help on a command\n"
1006 else if (STRCASEEQ (cmd, "quit") ||
1007 STRCASEEQ (cmd, "exit") ||
1008 STRCASEEQ (cmd, "q")) {
1009 printf (_("quit - quit guestfish\n"
1014 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1020 /* This is printed when the user types in an unknown command for the
1021 * first command issued. A common case is the user doing:
1022 * guestfish disk.img
1023 * expecting guestfish to open 'disk.img' (in fact, this tried to
1024 * run a command 'disk.img').
1027 extended_help_message (void)
1030 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1031 "For a list of commands: guestfish -h\n"
1032 "For complete documentation: man guestfish\n"));
1036 free_strings (char **argv)
1040 for (argc = 0; argv[argc] != NULL; ++argc)
1046 count_strings (char *const *argv)
1050 for (c = 0; argv[c]; ++c)
1056 print_strings (char *const *argv)
1060 for (argc = 0; argv[argc] != NULL; ++argc)
1061 printf ("%s\n", argv[argc]);
1065 print_table (char *const *argv)
1069 for (i = 0; argv[i] != NULL; i += 2)
1070 printf ("%s: %s\n", argv[i], argv[i+1]);
1074 is_true (const char *str)
1077 STRCASENEQ (str, "0") &&
1078 STRCASENEQ (str, "f") &&
1079 STRCASENEQ (str, "false") &&
1080 STRCASENEQ (str, "n") &&
1081 STRCASENEQ (str, "no");
1084 /* Free strings from a non-NULL terminated char** */
1086 free_n_strings (char **str, size_t len)
1090 for (i = 0; i < len; i++) {
1097 parse_string_list (const char *str)
1100 size_t argv_len = 0;
1102 /* Current position pointer */
1103 const char *p = str;
1105 /* Token might be simple:
1108 * 'This is a single token'
1109 * or contain embedded single-quoted sections:
1110 * This' is a sing'l'e to'ken
1112 * The latter may seem over-complicated, but it's what a normal shell does.
1113 * Not doing it risks surprising somebody.
1115 * This outer loop is over complete tokens.
1121 /* Skip leading whitespace */
1122 p += strspn (p, " \t");
1126 /* This loop is over token 'fragments'. A token can be in multiple bits if
1127 * it contains single quotes. We also treat both sides of an escaped quote
1128 * as separate fragments because we can't just copy it: we have to remove
1131 while (*p && (!c_isblank (*p) || in_quote)) {
1132 const char *end = p;
1134 /* Check if the fragment starts with a quote */
1136 /* Toggle in_quote */
1137 in_quote = !in_quote;
1139 /* Skip the quote */
1143 /* If we're in a quote, look for an end quote */
1145 end += strcspn (end, "'");
1148 /* Otherwise, look for whitespace or a quote */
1150 end += strcspn (end, " \t'");
1153 /* Grow the token to accommodate the fragment */
1154 size_t tok_end = tok_len;
1156 char *tok_new = realloc (tok, tok_len + 1);
1157 if (NULL == tok_new) {
1159 free_n_strings (argv, argv_len);
1161 exit (EXIT_FAILURE);
1165 /* Check if we stopped on an escaped quote */
1166 if ('\'' == *end && end != p && *(end-1) == '\\') {
1167 /* Add everything before \' to the token */
1168 memcpy (&tok[tok_end], p, end - p - 1);
1171 tok[tok_len-1] = '\'';
1173 /* Already processed the quote */
1178 /* Add the whole fragment */
1179 memcpy (&tok[tok_end], p, end - p);
1185 /* We've reached the end of a token. We shouldn't still be in quotes. */
1187 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1189 free_n_strings (argv, argv_len);
1194 /* Add this token if there is one. There might not be if there was
1195 * whitespace at the end of the input string */
1197 /* Add the NULL terminator */
1198 tok[tok_len] = '\0';
1200 /* Add the argument to the argument list */
1202 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1203 if (NULL == argv_new) {
1205 free_n_strings (argv, argv_len-1);
1207 exit (EXIT_FAILURE);
1211 argv[argv_len-1] = tok;
1215 /* NULL terminate the argument list */
1217 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1218 if (NULL == argv_new) {
1220 free_n_strings (argv, argv_len-1);
1221 exit (EXIT_FAILURE);
1225 argv[argv_len-1] = NULL;
1230 #ifdef HAVE_LIBREADLINE
1231 static char histfile[1024];
1232 static int nr_history_lines = 0;
1236 initialize_readline (void)
1238 #ifdef HAVE_LIBREADLINE
1241 home = getenv ("HOME");
1243 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1245 (void) read_history (histfile);
1248 rl_readline_name = "guestfish";
1249 rl_attempted_completion_function = do_completion;
1251 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1252 * call the readline(), which happens later. Therefore, these
1253 * provide default values which can be overridden by the user if
1256 (void) rl_variable_bind ("completion-ignore-case", "on");
1261 cleanup_readline (void)
1263 #ifdef HAVE_LIBREADLINE
1266 if (histfile[0] != '\0') {
1267 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1274 #ifdef HAVE_APPEND_HISTORY
1275 (void) append_history (nr_history_lines, histfile);
1277 (void) write_history (histfile);
1284 #ifdef HAVE_LIBREADLINE
1286 add_history_line (const char *line)
1294 xwrite (int fd, const void *v_buf, size_t len)
1297 const char *buf = v_buf;
1300 r = write (fd, buf, len);
1312 /* Resolve the special "win:..." form for Windows-specific paths.
1313 * This always returns a newly allocated string which is freed by the
1314 * caller function in "cmds.c".
1317 resolve_win_path (const char *path)
1322 if (STRCASENEQLEN (path, "win:", 4)) {
1323 ret = strdup (path);
1331 /* Drop drive letter, if it's "C:". */
1332 if (STRCASEEQLEN (path, "c:", 2))
1342 ret = strdup (path);
1348 /* Blindly convert any backslashes into forward slashes. Is this good? */
1349 for (i = 0; i < strlen (ret); ++i)
1353 char *t = guestfs_case_sensitive_path (g, ret);
1360 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1361 * The caller (cmds.c) will call free_file_in after the command has
1362 * run which should clean up resources.
1364 static char *file_in_heredoc (const char *endmarker);
1365 static char *file_in_tmpfile = NULL;
1368 file_in (const char *arg)
1372 if (STREQ (arg, "-")) {
1373 ret = strdup ("/dev/stdin");
1379 else if (STRPREFIX (arg, "-<<")) {
1380 const char *endmarker = &arg[3];
1381 if (*endmarker == '\0') {
1382 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1386 ret = file_in_heredoc (endmarker);
1402 file_in_heredoc (const char *endmarker)
1404 TMP_TEMPLATE_ON_STACK (template);
1405 file_in_tmpfile = strdup (template);
1406 if (file_in_tmpfile == NULL) {
1411 int fd = mkstemp (file_in_tmpfile);
1417 size_t markerlen = strlen (endmarker);
1419 char buffer[BUFSIZ];
1420 int write_error = 0;
1421 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1422 /* Look for "END"<EOF> or "END\n" in input. */
1423 size_t blen = strlen (buffer);
1424 if (STREQLEN (buffer, endmarker, markerlen) &&
1425 (blen == markerlen ||
1426 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1429 if (xwrite (fd, buffer, blen) == -1) {
1430 if (!write_error) perror ("write");
1432 /* continue reading up to the end marker */
1436 /* Reached EOF of stdin without finding the end marker, which
1437 * is likely to be an error.
1439 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1440 program_name, endmarker);
1449 if (close (fd) == -1) {
1454 return file_in_tmpfile;
1457 unlink (file_in_tmpfile);
1460 free (file_in_tmpfile);
1461 file_in_tmpfile = NULL;
1466 free_file_in (char *s)
1468 if (file_in_tmpfile) {
1469 if (unlink (file_in_tmpfile) == -1)
1470 perror (file_in_tmpfile);
1471 file_in_tmpfile = NULL;
1474 /* Free the device or file name which was strdup'd in file_in().
1475 * Note it's not immediately clear, but for -<< heredocs,
1476 * s == file_in_tmpfile, so this frees up that buffer.
1481 /* Resolve the special FileOut paths ("-" or filename).
1482 * The caller (cmds.c) will call free (str) after the command has run.
1485 file_out (const char *arg)
1489 if (STREQ (arg, "-"))
1490 ret = strdup ("/dev/stdout");