/** * @file interact.c * @brief Reading commands from a terminal: prompts and line input. * * input_fill() calls interact_read() when the input is a terminal and the * shell is interactive. It reports finished background jobs, expands and * shows the prompt, reads a line (through the line editor when one of the * editing options is on and the terminal can do it) and records the line * in the history. */ #include #include #include #include #include #include #include "charset.h" #include "exec.h" #include "expand.h" #include "interact.h" #include "sys.h" /** @brief Size of the block read from a terminal without the editor. */ #define TTY_BUFSZ ((size_t)4096) /** * @brief Append text that will be parsed as a here-document, protecting * the characters that parsing would otherwise act on. * @param sb Destination. * @param s Text to append literally. */ static void put_protected(strbuf *sb, const char *s) { for (; *s; s++) { if (*s == '$' || *s == '`' || *s == '\\') sb_putc(sb, '\\'); sb_putc(sb, *s); } } /** * @brief Replace the FreeBSD-style backslash escapes of a prompt string. * * | Escape | Becomes | * |--------|------------------------------------------------------| * | `\h` | host name up to the first dot | * | `\H` | full host name | * | `\u` | user name | * | `\w` | working directory, with `$HOME` shown as `~` | * | `\W` | last component of the working directory | * | `\$` | `#` for the superuser, otherwise `$` | * | `\S` | z/OS system name (elsewhere the short host name) | * | `\n` | a newline | * | `\e` | the escape character (for colour sequences) | * | `\\` | a backslash | * * Other backslashes are left alone. The result is still to be expanded * (see prompt_text()), so inserted values are protected against that. * * @param raw The prompt as set by the user. * @return The rewritten prompt, in scratch memory. */ static char *prompt_escapes(const char *raw) { strbuf sb; sb_init(&sb, &scratch); for (const char *p = raw; *p; p++) { if (*p != '\\' || !p[1]) { sb_putc(&sb, *p); continue; } char host[256]; const char *pwd; const char *home; switch (*++p) { case 'h': case 'H': if (gethostname(host, sizeof host) < 0) host[0] = '\0'; host[sizeof host - 1] = '\0'; if (*p == 'h') host[strcspn(host, ".")] = '\0'; put_protected(&sb, host); break; case 'u': { const char *user = var_get("USER"); if (!user) user = var_get("LOGNAME"); if (!user) { const struct passwd *pw = getpwuid(geteuid()); user = pw ? pw->pw_name : "?"; } put_protected(&sb, user); break; } case 'w': case 'W': pwd = var_get("PWD"); if (!pwd) pwd = "?"; home = var_get("HOME"); if (*p == 'W') { const char *slash = strrchr(pwd, '/'); put_protected(&sb, slash && slash[1] ? slash + 1 : pwd); } else if (home && *home && !strncmp(pwd, home, strlen(home)) && (pwd[strlen(home)] == '/' || !pwd[strlen(home)])) { sb_putc(&sb, '~'); put_protected(&sb, pwd + strlen(home)); } else { put_protected(&sb, pwd); } break; case '$': sb_puts(&sb, geteuid() == 0 ? "#" : "\\$"); break; case 'n': sb_putc(&sb, '\n'); break; case 'S': { /* z/OS system name; elsewhere the short host name */ const char *sys = SYS_MVS ? sys_info(SI_SYSNAME) : NULL; if (!sys) { if (gethostname(host, sizeof host) < 0) host[0] = '\0'; host[sizeof host - 1] = '\0'; host[strcspn(host, ".")] = '\0'; sys = host; } put_protected(&sb, sys); break; } case 'e': sb_putc(&sb, CH_ESC); break; case '[': /* bash's "this part is not printed" markers: the width * rule already skips control sequences, so drop them */ case ']': break; case '\\': sb_puts(&sb, "\\\\"); break; default: sb_putc(&sb, '\\'); sb_putc(&sb, *p); break; } } return sb_cstr(&sb); } /** * @brief Produce the text of a prompt. * * The value of PS1 or PS2 goes through the backslash escapes above and * then through parameter expansion, command substitution and arithmetic * expansion, as POSIX specifies for PS1. * * A prompt is expanded from inside the lexer, possibly half way through * a command, so the parser's state is saved around the expansion. And an * error in the expansion must not come back as an error at the prompt * (which would prompt again, and fail again), so on error the raw value * is used. * * @param which 1 for PS1, 2 for PS2. * @return The prompt, in scratch memory. */ static const char *prompt_text(int which) { const char *raw = var_get(which == 1 ? "PS1" : "PS2"); if (!raw) return ""; if (!strpbrk(raw, "$`\\")) return raw; /* nothing to expand: the usual "$ " */ return expand_quietly(raw, true); } /** * @brief Expand text as a double-quoted word, with errors contained. * * Used for prompts and for `ENV`. An expansion error (`${x?}`, a bad * substitution) prints its message and the text is used unexpanded. It * never unwinds into the caller, and `$?` is preserved. * * @param raw The text. * @param escapes Process prompt backslash escapes first. * @return The expansion, in scratch memory, or `raw` on error. */ const char *expand_quietly(const char *raw, bool escapes) { _Alignas(max_align_t) char pstate[PARSER_STATE_SIZE]; jmploc jl; jmploc *prev = exc_handler; unwind u; arena *volatile pa = arena_new(); const char *volatile result = raw; int saved_status = exitstatus; parser_save(pstate); unwind_save(&u); if (setjmp(jl.buf) == 0) { exc_handler = &jl; const char *text = escapes ? prompt_escapes(raw) : raw; result = expand_string(parse_text_parts(pa, text, strlen(text)), 0); } else { unwind_restore(&u); } exc_handler = prev; parser_restore(pstate); arena_unref(pa); exitstatus = saved_status; return result; } /** * @brief Read a line from the terminal with a plain read(). * * Used when line editing is off or the terminal cannot support it. The * terminal driver does the editing. * * @param in The terminal input. * @param prompt Prompt to print first. * @return Number of bytes read into in->buf. 0 at end of input. */ static size_t plain_read(input_src *in, const char *prompt) { out_puts(&out2, prompt); out_flush(&out2); ssize_t n; while ((n = read(in->fd, in->buf, TTY_BUFSZ)) < 0) { if (errno != EINTR) return 0; trap_poll(); /* ^C: does not return */ } return (size_t)n; } /** * @brief Get the next line of commands from the terminal. * * @param in The terminal input. In->p and in->end are set to the line. * @return false at end of input. */ bool interact_read(input_src *in) { int which = prompt_state == 2 ? 2 : 1; if (which == 1) jobs_notify(); arena_marker mark = arena_mark(&scratch); const char *prompt = prompt_text(which); size_t len; if ((opt.emacs || opt.vi) && edit_usable()) { const char *line = edit_readline(prompt, &len); if (!line) { arena_release(&scratch, mark); return false; } if (len + 2 > TTY_BUFSZ) in->buf = xrealloc(in->buf, len + 2); memcpy(in->buf, line, len); in->buf[len++] = '\n'; } else { len = plain_read(in, prompt); } arena_release(&scratch, mark); if (!len) return false; prompt_state = 2; hist_add(in->buf, len, which == 2); in->p = in->buf; in->end = in->buf + len; return true; } /** * @brief Decide whether an end-of-file at the prompt should be ignored. * * `set -o ignoreeof` makes `^D` harmless, and a shell with stopped jobs * refuses to leave once, as `exit` does. * * @return true if the shell should print a new prompt instead of exiting. */ bool interact_refuse_eof(void) { static bool warned; if (opt.ignoreeof) { sh_warn("use \"exit\" to leave the shell"); return true; } if (!warned && jobs_stopped()) { warned = true; sh_warn("there are stopped jobs"); return true; } return false; } /** @brief Prepare the interactive layer: editing mode and history. */ void interact_init(void) { if (!opt.vi) opt.emacs = true; hist_init(); } /** @brief Leave the interactive layer: save the history. */ void interact_exit(void) { if (opt.interactive) hist_save(); }