summaryrefslogtreecommitdiffhomepage
path: root/src/interact.c
blob: dfd095c8c3e4473eafebdb314b053c191ea905e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/**
 * @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 <errno.h>
#include <limits.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#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();
}