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_csh = 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 " --csh Make --listen csh-compatible\n"
110 " -d|--domain guest Add disks from libvirt guest\n"
111 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
112 " --echo-keys Don't turn off echo for passphrases\n"
113 " -f|--file file Read commands from file\n"
114 " --format[=raw|..] Force disk format for -a option\n"
115 " -i|--inspector Automatically mount filesystems\n"
116 " --keys-from-stdin Read passphrases from stdin\n"
117 " --listen Listen for remote commands\n"
118 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
119 " -n|--no-sync Don't autosync\n"
120 " -N|--new type Create prepared disk (test1.img, ...)\n"
121 " --progress-bars Enable progress bars even when not interactive\n"
122 " --no-progress-bars Disable progress bars\n"
123 " --remote[=pid] Send commands to remote %s\n"
124 " -r|--ro Mount read-only\n"
125 " --selinux Enable SELinux support\n"
126 " -v|--verbose Verbose messages\n"
127 " -V|--version Display version and exit\n"
128 " -x Echo each command before executing it\n"
129 "For more information, see the manpage %s(1).\n"),
130 program_name, program_name, program_name,
131 program_name, program_name, program_name,
132 program_name, program_name, program_name);
138 main (int argc, char *argv[])
140 /* Set global program name that is not polluted with libtool artifacts. */
141 set_program_name (argv[0]);
143 atexit (close_stdout);
145 setlocale (LC_ALL, "");
146 bindtextdomain (PACKAGE, LOCALEBASEDIR);
147 textdomain (PACKAGE);
151 enum { HELP_OPTION = CHAR_MAX + 1 };
153 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
154 static const struct option long_options[] = {
155 { "add", 1, 0, 'a' },
156 { "cmd-help", 2, 0, 'h' },
157 { "connect", 1, 0, 'c' },
159 { "domain", 1, 0, 'd' },
160 { "echo-keys", 0, 0, 0 },
161 { "file", 1, 0, 'f' },
162 { "format", 2, 0, 0 },
163 { "help", 0, 0, HELP_OPTION },
164 { "inspector", 0, 0, 'i' },
165 { "keys-from-stdin", 0, 0, 0 },
166 { "listen", 0, 0, 0 },
167 { "mount", 1, 0, 'm' },
168 { "new", 1, 0, 'N' },
169 { "no-dest-paths", 0, 0, 'D' },
170 { "no-sync", 0, 0, 'n' },
171 { "progress-bars", 0, 0, 0 },
172 { "no-progress-bars", 0, 0, 0 },
173 { "remote", 2, 0, 0 },
176 { "selinux", 0, 0, 0 },
177 { "verbose", 0, 0, 'v' },
178 { "version", 0, 0, 'V' },
181 struct drv *drvs = NULL;
183 struct mp *mps = NULL;
185 char *p, *file = NULL;
186 const char *format = NULL;
190 int next_prepared_drive = 1;
192 initialize_readline ();
194 memset (&sa, 0, sizeof sa);
195 sa.sa_handler = SIG_IGN;
196 sa.sa_flags = SA_RESTART;
197 sigaction (SIGPIPE, &sa, NULL);
199 /* guestfs_create is meant to be a lightweight operation, so
200 * it's OK to do it early here.
202 g = guestfs_create ();
204 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
208 /* If developing, add ./appliance to the path. Note that libtools
209 * interferes with this because uninstalled guestfish is a shell
210 * script that runs the real program with an absolute path. Detect
213 * BUT if LIBGUESTFS_PATH environment variable is already set by
214 * the user, then don't override it.
216 if (getenv ("LIBGUESTFS_PATH") == NULL &&
218 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
219 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
221 /* CAUTION: we are careful to modify argv[0] here, only after
222 * using it just above.
224 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
225 * of the original, in case it's needed below.
227 //char *real_argv0 = argv[0];
228 argv[0] = bad_cast (program_name);
231 c = getopt_long (argc, argv, options, long_options, &option_index);
235 case 0: /* options which are long only */
236 if (STREQ (long_options[option_index].name, "listen"))
237 remote_control_listen = 1;
238 else if (STREQ (long_options[option_index].name, "remote")) {
240 if (sscanf (optarg, "%d", &remote_control) != 1) {
241 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
242 program_name, optarg);
246 p = getenv ("GUESTFISH_PID");
247 if (!p || sscanf (p, "%d", &remote_control) != 1) {
248 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
249 " to the PID of the remote process\n"),
254 } else if (STREQ (long_options[option_index].name, "selinux")) {
255 guestfs_set_selinux (g, 1);
256 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
258 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
259 override_progress_bars = 1;
260 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
261 override_progress_bars = 0;
262 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
264 } else if (STREQ (long_options[option_index].name, "format")) {
265 if (!optarg || STREQ (optarg, ""))
269 } else if (STREQ (long_options[option_index].name, "csh")) {
270 remote_control_csh = 1;
272 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
273 program_name, long_options[option_index].name, option_index);
291 complete_dest_paths = 0;
296 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
307 r = display_command (optarg);
308 else if (argv[optind] && argv[optind][0] != '-')
309 r = display_command (argv[optind++]);
313 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
329 if (STRCASEEQ (optarg, "list") ||
330 STRCASEEQ (optarg, "help") ||
331 STRCASEEQ (optarg, "h") ||
332 STRCASEEQ (optarg, "?")) {
333 list_prepared_drives ();
336 drv = malloc (sizeof (struct drv));
344 if (asprintf (&drv->N.filename, "test%d.img",
345 next_prepared_drive++) == -1) {
349 drv->N.data = create_prepared_file (optarg, drv->N.filename);
350 drv->N.data_free = free_prep_data;
376 usage (EXIT_SUCCESS);
379 usage (EXIT_FAILURE);
383 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
384 * previously, if we have -i without any drives but with something
385 * on the command line, it must be old-style syntax.
387 if (inspector && drvs == NULL && optind < argc) {
388 while (optind < argc) {
389 if (strchr (argv[optind], '/') ||
390 access (argv[optind], F_OK) == 0) { /* simulate -a option */
391 drv = malloc (sizeof (struct drv));
397 drv->a.filename = argv[optind];
398 drv->a.format = NULL;
401 } else { /* simulate -d option */
402 drv = malloc (sizeof (struct drv));
408 drv->d.guest = argv[optind];
417 /* If we've got drives to add, add them now. */
418 add_drives (drvs, 'a');
420 /* If we've got mountpoints or prepared drives or -i option, we must
421 * launch the guest and mount them.
423 if (next_prepared_drive > 1 || mps != NULL || inspector) {
424 /* RHBZ#612178: If --listen flag is given, then we will fork into
425 * the background in rc_listen(). However you can't do this while
426 * holding a libguestfs handle open because the recovery process
427 * will think the main program has died and kill qemu. Therefore
428 * don't use the recovery process for this case. (A better
429 * solution would be to call launch () etc after the fork, but
430 * that greatly complicates the code here).
432 if (remote_control_listen)
433 guestfs_set_recovery_proc (g, 0);
435 if (launch () == -1) exit (EXIT_FAILURE);
440 prepare_drives (drvs);
444 /* Free up data structures, no longer needed after this point. */
448 /* Remote control? */
449 if (remote_control_listen && remote_control) {
451 _("%s: cannot use --listen and --remote options at the same time\n"),
456 if (remote_control_listen) {
459 _("%s: extra parameters on the command line with --listen flag\n"),
465 _("%s: cannot use --listen and --file options at the same time\n"),
472 /* -f (file) parameter? */
475 if (open (file, O_RDONLY) == -1) {
481 /* Decide if we display progress bars. */
483 override_progress_bars >= 0
484 ? override_progress_bars
485 : (optind >= argc && isatty (0));
488 guestfs_set_progress_callback (g, progress_callback, NULL);
490 /* Interactive, shell script, or command(s) on the command line? */
491 if (optind >= argc) {
498 cmdline (argv, optind, argc);
505 /* The <term.h> header file which defines this has "issues". */
506 extern int tgetent (char *, const char *);
509 set_up_terminal (void)
511 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
512 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
514 char *term = getenv ("TERM");
516 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
520 int r = tgetent (NULL, term);
522 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
526 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
535 prepare_drives (struct drv *drv)
538 prepare_drives (drv->next);
539 if (drv->type == drv_N)
540 prepare_drive (drv->N.filename, drv->N.data, drv->device);
547 if (guestfs_is_config (g)) {
548 if (guestfs_launch (g) == -1)
566 #define FISH "><fs> "
568 static char *line_read = NULL;
573 #ifdef HAVE_LIBREADLINE
581 line_read = readline (prompt ? FISH : "");
583 if (line_read && *line_read)
584 add_history_line (line_read);
589 #endif /* HAVE_LIBREADLINE */
591 static char buf[8192];
594 if (prompt) printf (FISH);
595 line_read = fgets (buf, sizeof buf, stdin);
598 len = strlen (line_read);
599 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
613 int global_exit_on_error = !prompt;
618 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
619 "editing virtual machine filesystems.\n"
621 "Type: 'help' for help on commands\n"
622 " 'man' to read the manual\n"
623 " 'quit' to quit the shell\n"
627 print_inspect_prompt ();
635 exit_on_error = global_exit_on_error;
637 buf = rl_gets (prompt);
643 /* Skip any initial whitespace before the command. */
645 while (*buf && c_isspace (*buf))
650 /* If the next character is '#' then this is a comment. */
651 if (*buf == '#') continue;
653 /* If the next character is '!' then pass the whole lot to system(3). */
661 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
662 WEXITSTATUS (r) != 0)
668 /* If the next character is '-' allow the command to fail without
669 * exiting on error (just for this one command though).
677 /* Get the command (cannot be quoted). */
678 len = strcspn (buf, " \t");
680 if (len == 0) continue;
684 if (buf[len] == '\0') {
691 p += strspn (p, " \t");
693 /* Get the parameters. */
694 while (*p && i < sizeof argv / sizeof argv[0]) {
697 /* Parameters which start with quotes or pipes are treated
698 * specially. Bare parameters are delimited by whitespace.
702 len = strcspn (p, "\"");
703 if (p[len] == '\0') {
704 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
705 if (exit_on_error) exit (EXIT_FAILURE);
708 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
710 _("%s: command arguments not separated by whitespace\n"),
712 if (exit_on_error) exit (EXIT_FAILURE);
716 pend = p[len+1] ? &p[len+2] : &p[len+1];
717 } else if (*p == '\'') {
719 len = strcspn (p, "'");
720 if (p[len] == '\0') {
721 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
722 if (exit_on_error) exit (EXIT_FAILURE);
725 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
727 _("%s: command arguments not separated by whitespace\n"),
729 if (exit_on_error) exit (EXIT_FAILURE);
733 pend = p[len+1] ? &p[len+2] : &p[len+1];
734 } else if (*p == '|') {
739 } else if (*p == '[') {
743 while (*pend && c != 0) {
744 if (*pend == '[') c++;
745 else if (*pend == ']') c--;
750 _("%s: unterminated \"[...]\" sequence\n"), program_name);
751 if (exit_on_error) exit (EXIT_FAILURE);
754 if (*pend && (*pend != ' ' && *pend != '\t')) {
756 _("%s: command arguments not separated by whitespace\n"),
758 if (exit_on_error) exit (EXIT_FAILURE);
763 } else if (*p != ' ' && *p != '\t') {
764 /* If the first character is a ~ then note that this parameter
765 * is a candidate for ~username expansion. NB this does not
766 * apply to quoted parameters.
768 tilde_candidate = *p == '~';
769 len = strcspn (p, " \t");
776 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
781 if (!tilde_candidate)
784 argv[i] = try_tilde_expansion (p);
789 p += strspn (p, " \t");
792 if (i == sizeof argv / sizeof argv[0]) {
793 fprintf (stderr, _("%s: too many arguments\n"), program_name);
794 if (exit_on_error) exit (EXIT_FAILURE);
801 if (issue_command (cmd, argv, pipe) == -1) {
802 if (exit_on_error) exit (EXIT_FAILURE);
807 if (prompt) printf ("\n");
811 cmdline (char *argv[], int optind, int argc)
818 if (optind >= argc) return;
820 cmd = argv[optind++];
821 if (STREQ (cmd, ":")) {
822 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
826 /* Allow -cmd on the command line to mean (temporarily) override
827 * the normal exit on error (RHBZ#578407).
834 params = &argv[optind];
836 /* Search for end of command list or ":" ... */
837 while (optind < argc && STRNEQ (argv[optind], ":"))
840 if (optind == argc) {
841 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
845 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
847 cmdline (argv, optind+1, argc);
852 issue_command (const char *cmd, char *argv[], const char *pipecmd)
855 int stdout_saved_fd = -1;
859 reset_progress_bar ();
861 /* This counts the commands issued, starting at 1. */
864 /* For | ... commands. Annoyingly we can't use popen(3) here. */
868 if (fflush (stdout) == EOF) {
869 perror ("failed to flush standard output");
873 perror ("pipe failed");
882 if (pid == 0) { /* Child process. */
884 if (dup2 (fd[0], 0) < 0) {
885 perror ("dup2 of stdin failed");
889 r = system (pipecmd);
894 _exit (WEXITSTATUS (r));
897 if ((stdout_saved_fd = dup (1)) < 0) {
898 perror ("failed to dup stdout");
902 if (dup2 (fd[1], 1) < 0) {
903 perror ("failed to dup stdout");
904 close (stdout_saved_fd);
910 for (argc = 0; argv[argc] != NULL; ++argc)
913 /* If --remote was set, then send this command to a remote process. */
915 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
917 /* Otherwise execute it locally. */
918 else if (STRCASEEQ (cmd, "help")) {
923 r = display_command (argv[0]);
925 else if (STRCASEEQ (cmd, "quit") ||
926 STRCASEEQ (cmd, "exit") ||
927 STRCASEEQ (cmd, "q")) {
932 r = run_action (cmd, argc, argv);
934 /* Always flush stdout after every command, so that messages, results
935 * etc appear immediately.
937 if (fflush (stdout) == EOF) {
938 perror ("failed to flush standard output");
944 if (dup2 (stdout_saved_fd, 1) < 0) {
945 perror ("failed to dup2 standard output");
948 close (stdout_saved_fd);
949 if (waitpid (pid, NULL, 0) < 0) {
950 perror ("waiting for command to complete");
959 list_builtin_commands (void)
961 /* help and quit should appear at the top */
962 printf ("%-20s %s\n",
963 "help", _("display a list of commands or help on a command"));
964 printf ("%-20s %s\n",
965 "quit", _("quit guestfish"));
967 /* actions are printed after this (see list_commands) */
971 display_builtin_command (const char *cmd)
973 /* help for actions is auto-generated, see display_command */
975 if (STRCASEEQ (cmd, "help")) {
976 printf (_("help - display a list of commands or help on a command\n"
981 else if (STRCASEEQ (cmd, "quit") ||
982 STRCASEEQ (cmd, "exit") ||
983 STRCASEEQ (cmd, "q")) {
984 printf (_("quit - quit guestfish\n"
989 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
995 /* This is printed when the user types in an unknown command for the
996 * first command issued. A common case is the user doing:
998 * expecting guestfish to open 'disk.img' (in fact, this tried to
999 * run a command 'disk.img').
1002 extended_help_message (void)
1005 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1006 "For a list of commands: guestfish -h\n"
1007 "For complete documentation: man guestfish\n"));
1011 free_strings (char **argv)
1015 for (argc = 0; argv[argc] != NULL; ++argc)
1021 count_strings (char *const *argv)
1025 for (c = 0; argv[c]; ++c)
1031 print_strings (char *const *argv)
1035 for (argc = 0; argv[argc] != NULL; ++argc)
1036 printf ("%s\n", argv[argc]);
1040 print_table (char *const *argv)
1044 for (i = 0; argv[i] != NULL; i += 2)
1045 printf ("%s: %s\n", argv[i], argv[i+1]);
1049 is_true (const char *str)
1052 STRCASENEQ (str, "0") &&
1053 STRCASENEQ (str, "f") &&
1054 STRCASENEQ (str, "false") &&
1055 STRCASENEQ (str, "n") &&
1056 STRCASENEQ (str, "no");
1059 /* Free strings from a non-NULL terminated char** */
1061 free_n_strings (char **str, size_t len)
1065 for (i = 0; i < len; i++) {
1072 parse_string_list (const char *str)
1075 size_t argv_len = 0;
1077 /* Current position pointer */
1078 const char *p = str;
1080 /* Token might be simple:
1083 * 'This is a single token'
1084 * or contain embedded single-quoted sections:
1085 * This' is a sing'l'e to'ken
1087 * The latter may seem over-complicated, but it's what a normal shell does.
1088 * Not doing it risks surprising somebody.
1090 * This outer loop is over complete tokens.
1096 /* Skip leading whitespace */
1097 p += strspn (p, " \t");
1101 /* This loop is over token 'fragments'. A token can be in multiple bits if
1102 * it contains single quotes. We also treat both sides of an escaped quote
1103 * as separate fragments because we can't just copy it: we have to remove
1106 while (*p && (!c_isblank (*p) || in_quote)) {
1107 const char *end = p;
1109 /* Check if the fragment starts with a quote */
1111 /* Toggle in_quote */
1112 in_quote = !in_quote;
1114 /* Skip the quote */
1118 /* If we're in a quote, look for an end quote */
1120 end += strcspn (end, "'");
1123 /* Otherwise, look for whitespace or a quote */
1125 end += strcspn (end, " \t'");
1128 /* Grow the token to accommodate the fragment */
1129 size_t tok_end = tok_len;
1131 char *tok_new = realloc (tok, tok_len + 1);
1132 if (NULL == tok_new) {
1134 free_n_strings (argv, argv_len);
1136 exit (EXIT_FAILURE);
1140 /* Check if we stopped on an escaped quote */
1141 if ('\'' == *end && end != p && *(end-1) == '\\') {
1142 /* Add everything before \' to the token */
1143 memcpy (&tok[tok_end], p, end - p - 1);
1146 tok[tok_len-1] = '\'';
1148 /* Already processed the quote */
1153 /* Add the whole fragment */
1154 memcpy (&tok[tok_end], p, end - p);
1160 /* We've reached the end of a token. We shouldn't still be in quotes. */
1162 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1164 free_n_strings (argv, argv_len);
1169 /* Add this token if there is one. There might not be if there was
1170 * whitespace at the end of the input string */
1172 /* Add the NULL terminator */
1173 tok[tok_len] = '\0';
1175 /* Add the argument to the argument list */
1177 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1178 if (NULL == argv_new) {
1180 free_n_strings (argv, argv_len-1);
1182 exit (EXIT_FAILURE);
1186 argv[argv_len-1] = tok;
1190 /* NULL terminate the argument list */
1192 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1193 if (NULL == argv_new) {
1195 free_n_strings (argv, argv_len-1);
1196 exit (EXIT_FAILURE);
1200 argv[argv_len-1] = NULL;
1205 #ifdef HAVE_LIBREADLINE
1206 static char histfile[1024];
1207 static int nr_history_lines = 0;
1211 initialize_readline (void)
1213 #ifdef HAVE_LIBREADLINE
1216 home = getenv ("HOME");
1218 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1220 (void) read_history (histfile);
1223 rl_readline_name = "guestfish";
1224 rl_attempted_completion_function = do_completion;
1226 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1227 * call the readline(), which happens later. Therefore, these
1228 * provide default values which can be overridden by the user if
1231 (void) rl_variable_bind ("completion-ignore-case", "on");
1236 cleanup_readline (void)
1238 #ifdef HAVE_LIBREADLINE
1241 if (histfile[0] != '\0') {
1242 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1249 #ifdef HAVE_APPEND_HISTORY
1250 (void) append_history (nr_history_lines, histfile);
1252 (void) write_history (histfile);
1259 #ifdef HAVE_LIBREADLINE
1261 add_history_line (const char *line)
1269 xwrite (int fd, const void *v_buf, size_t len)
1272 const char *buf = v_buf;
1275 r = write (fd, buf, len);
1287 /* Resolve the special "win:..." form for Windows-specific paths.
1288 * This always returns a newly allocated string which is freed by the
1289 * caller function in "cmds.c".
1292 resolve_win_path (const char *path)
1297 if (STRCASENEQLEN (path, "win:", 4)) {
1298 ret = strdup (path);
1306 /* Drop drive letter, if it's "C:". */
1307 if (STRCASEEQLEN (path, "c:", 2))
1317 ret = strdup (path);
1323 /* Blindly convert any backslashes into forward slashes. Is this good? */
1324 for (i = 0; i < strlen (ret); ++i)
1328 char *t = guestfs_case_sensitive_path (g, ret);
1335 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1336 * The caller (cmds.c) will call free_file_in after the command has
1337 * run which should clean up resources.
1339 static char *file_in_heredoc (const char *endmarker);
1340 static char *file_in_tmpfile = NULL;
1343 file_in (const char *arg)
1347 if (STREQ (arg, "-")) {
1348 ret = strdup ("/dev/stdin");
1354 else if (STRPREFIX (arg, "-<<")) {
1355 const char *endmarker = &arg[3];
1356 if (*endmarker == '\0') {
1357 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1361 ret = file_in_heredoc (endmarker);
1377 file_in_heredoc (const char *endmarker)
1379 TMP_TEMPLATE_ON_STACK (template);
1380 file_in_tmpfile = strdup (template);
1381 if (file_in_tmpfile == NULL) {
1386 int fd = mkstemp (file_in_tmpfile);
1392 size_t markerlen = strlen (endmarker);
1394 char buffer[BUFSIZ];
1395 int write_error = 0;
1396 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1397 /* Look for "END"<EOF> or "END\n" in input. */
1398 size_t blen = strlen (buffer);
1399 if (STREQLEN (buffer, endmarker, markerlen) &&
1400 (blen == markerlen ||
1401 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1404 if (xwrite (fd, buffer, blen) == -1) {
1405 if (!write_error) perror ("write");
1407 /* continue reading up to the end marker */
1411 /* Reached EOF of stdin without finding the end marker, which
1412 * is likely to be an error.
1414 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1415 program_name, endmarker);
1424 if (close (fd) == -1) {
1429 return file_in_tmpfile;
1432 unlink (file_in_tmpfile);
1435 free (file_in_tmpfile);
1436 file_in_tmpfile = NULL;
1441 free_file_in (char *s)
1443 if (file_in_tmpfile) {
1444 if (unlink (file_in_tmpfile) == -1)
1445 perror (file_in_tmpfile);
1446 file_in_tmpfile = NULL;
1449 /* Free the device or file name which was strdup'd in file_in().
1450 * Note it's not immediately clear, but for -<< heredocs,
1451 * s == file_in_tmpfile, so this frees up that buffer.
1456 /* Resolve the special FileOut paths ("-" or filename).
1457 * The caller (cmds.c) will call free (str) after the command has run.
1460 file_out (const char *arg)
1464 if (STREQ (arg, "-"))
1465 ret = strdup ("/dev/stdout");