blob: 61fe00642378842d9fa29c50b973ecb551204cfe [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/* vi: set sw=4 ts=4: */
2/*
3 * Command line editing.
4 *
5 * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6 * Written by: Vladimir Oleynik <dzo@simtreas.ru>
7 *
8 * Used ideas:
9 * Adam Rogoyski <rogoyski@cs.utexas.edu>
10 * Dave Cinege <dcinege@psychosis.com>
11 * Jakub Jelinek (c) 1995
12 * Erik Andersen <andersen@codepoet.org> (Majorly adjusted for busybox)
13 *
14 * This code is 'as is' with no warranty.
15 */
16
17/*
18 * Usage and known bugs:
19 * Terminal key codes are not extensive, more needs to be added.
20 * This version was created on Debian GNU/Linux 2.x.
21 * Delete, Backspace, Home, End, and the arrow keys were tested
22 * to work in an Xterm and console. Ctrl-A also works as Home.
23 * Ctrl-E also works as End.
24 *
25 * The following readline-like commands are not implemented:
26 * ESC-b -- Move back one word
27 * ESC-f -- Move forward one word
28 * ESC-d -- Delete forward one word
29 * CTL-t -- Transpose two characters
30 *
31 * lineedit does not know that the terminal escape sequences do not
32 * take up space on the screen. The redisplay code assumes, unless
33 * told otherwise, that each character in the prompt is a printable
34 * character that takes up one character position on the screen.
35 * You need to tell lineedit that some sequences of characters
36 * in the prompt take up no screen space. Compatibly with readline,
37 * use the \[ escape to begin a sequence of non-printing characters,
38 * and the \] escape to signal the end of such a sequence. Example:
39 *
40 * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
41 */
42#include "libbb.h"
43#include "unicode.h"
44#ifndef _POSIX_VDISABLE
45# define _POSIX_VDISABLE '\0'
46#endif
47
48
49#ifdef TEST
50# define ENABLE_FEATURE_EDITING 0
51# define ENABLE_FEATURE_TAB_COMPLETION 0
52# define ENABLE_FEATURE_USERNAME_COMPLETION 0
53#endif
54
55
56/* Entire file (except TESTing part) sits inside this #if */
57#if ENABLE_FEATURE_EDITING
58
59
60#define ENABLE_USERNAME_OR_HOMEDIR \
61 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
62#define IF_USERNAME_OR_HOMEDIR(...)
63#if ENABLE_USERNAME_OR_HOMEDIR
64# undef IF_USERNAME_OR_HOMEDIR
65# define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
66#endif
67
68
69#undef CHAR_T
70#if ENABLE_UNICODE_SUPPORT
71# define BB_NUL ((wchar_t)0)
72# define CHAR_T wchar_t
73static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
74# if ENABLE_FEATURE_EDITING_VI
75static bool BB_isalnum(CHAR_T c) { return ((unsigned)c < 256 && isalnum(c)); }
76# endif
77static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
78# undef isspace
79# undef isalnum
80# undef ispunct
81# undef isprint
82# define isspace isspace_must_not_be_used
83# define isalnum isalnum_must_not_be_used
84# define ispunct ispunct_must_not_be_used
85# define isprint isprint_must_not_be_used
86#else
87# define BB_NUL '\0'
88# define CHAR_T char
89# define BB_isspace(c) isspace(c)
90# define BB_isalnum(c) isalnum(c)
91# define BB_ispunct(c) ispunct(c)
92#endif
93#if ENABLE_UNICODE_PRESERVE_BROKEN
94# define unicode_mark_raw_byte(wc) ((wc) | 0x20000000)
95# define unicode_is_raw_byte(wc) ((wc) & 0x20000000)
96#else
97# define unicode_is_raw_byte(wc) 0
98#endif
99
100
101#define ESC "\033"
102
103#define SEQ_CLEAR_TILL_END_OF_SCREEN ESC"[J"
104//#define SEQ_CLEAR_TILL_END_OF_LINE ESC"[K"
105
106
107enum {
108 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
109 ? CONFIG_FEATURE_EDITING_MAX_LEN
110 : 0x7ff0
111};
112
113#if ENABLE_USERNAME_OR_HOMEDIR
114static const char null_str[] ALIGN1 = "";
115#endif
116
117/* We try to minimize both static and stack usage. */
118struct lineedit_statics {
119 line_input_t *state;
120
121 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
122 sighandler_t previous_SIGWINCH_handler;
123
124 unsigned cmdedit_x; /* real x (col) terminal position */
125 unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
126 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
127
128 unsigned cursor;
129 int command_len; /* must be signed */
130 /* signed maxsize: we want x in "if (x > S.maxsize)"
131 * to _not_ be promoted to unsigned */
132 int maxsize;
133 CHAR_T *command_ps;
134
135 const char *cmdedit_prompt;
136#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
137 int num_ok_lines; /* = 1; */
138#endif
139
140#if ENABLE_USERNAME_OR_HOMEDIR
141 char *user_buf;
142 char *home_pwd_buf; /* = (char*)null_str; */
143#endif
144
145#if ENABLE_FEATURE_TAB_COMPLETION
146 char **matches;
147 unsigned num_matches;
148#endif
149
150#if ENABLE_FEATURE_EDITING_VI
151# define DELBUFSIZ 128
152 CHAR_T *delptr;
153 smallint newdelflag; /* whether delbuf should be reused yet */
154 CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
155#endif
156#if ENABLE_FEATURE_EDITING_ASK_TERMINAL
157 smallint sent_ESC_br6n;
158#endif
159};
160
161/* See lineedit_ptr_hack.c */
162extern struct lineedit_statics *const lineedit_ptr_to_statics;
163
164#define S (*lineedit_ptr_to_statics)
165#define state (S.state )
166#define cmdedit_termw (S.cmdedit_termw )
167#define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
168#define cmdedit_x (S.cmdedit_x )
169#define cmdedit_y (S.cmdedit_y )
170#define cmdedit_prmt_len (S.cmdedit_prmt_len)
171#define cursor (S.cursor )
172#define command_len (S.command_len )
173#define command_ps (S.command_ps )
174#define cmdedit_prompt (S.cmdedit_prompt )
175#define num_ok_lines (S.num_ok_lines )
176#define user_buf (S.user_buf )
177#define home_pwd_buf (S.home_pwd_buf )
178#define matches (S.matches )
179#define num_matches (S.num_matches )
180#define delptr (S.delptr )
181#define newdelflag (S.newdelflag )
182#define delbuf (S.delbuf )
183
184#define INIT_S() do { \
185 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
186 barrier(); \
187 cmdedit_termw = 80; \
188 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
189 IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
190} while (0)
191
192static void deinit_S(void)
193{
194#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
195 /* This one is allocated only if FANCY_PROMPT is on
196 * (otherwise it points to verbatim prompt (NOT malloced)) */
197 free((char*)cmdedit_prompt);
198#endif
199#if ENABLE_USERNAME_OR_HOMEDIR
200 free(user_buf);
201 if (home_pwd_buf != null_str)
202 free(home_pwd_buf);
203#endif
204 free(lineedit_ptr_to_statics);
205}
206#define DEINIT_S() deinit_S()
207
208
209#if ENABLE_UNICODE_SUPPORT
210static size_t load_string(const char *src)
211{
212 if (unicode_status == UNICODE_ON) {
213 ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
214 if (len < 0)
215 len = 0;
216 command_ps[len] = BB_NUL;
217 return len;
218 } else {
219 unsigned i = 0;
220 while (src[i] && i < S.maxsize - 1) {
221 command_ps[i] = src[i];
222 i++;
223 }
224 command_ps[i] = BB_NUL;
225 return i;
226 }
227}
228static unsigned save_string(char *dst, unsigned maxsize)
229{
230 if (unicode_status == UNICODE_ON) {
231# if !ENABLE_UNICODE_PRESERVE_BROKEN
232 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
233 if (len < 0)
234 len = 0;
235 dst[len] = '\0';
236 return len;
237# else
238 unsigned dstpos = 0;
239 unsigned srcpos = 0;
240
241 maxsize--;
242 while (dstpos < maxsize) {
243 wchar_t wc;
244 int n = srcpos;
245
246 /* Convert up to 1st invalid byte (or up to end) */
247 while ((wc = command_ps[srcpos]) != BB_NUL
248 && !unicode_is_raw_byte(wc)
249 ) {
250 srcpos++;
251 }
252 command_ps[srcpos] = BB_NUL;
253 n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
254 if (n < 0) /* should not happen */
255 break;
256 dstpos += n;
257 if (wc == BB_NUL) /* usually is */
258 break;
259
260 /* We do have invalid byte here! */
261 command_ps[srcpos] = wc; /* restore it */
262 srcpos++;
263 if (dstpos == maxsize)
264 break;
265 dst[dstpos++] = (char) wc;
266 }
267 dst[dstpos] = '\0';
268 return dstpos;
269# endif
270 } else {
271 unsigned i = 0;
272 while ((dst[i] = command_ps[i]) != 0)
273 i++;
274 return i;
275 }
276}
277/* I thought just fputwc(c, stdout) would work. But no... */
278static void BB_PUTCHAR(wchar_t c)
279{
280 if (unicode_status == UNICODE_ON) {
281 char buf[MB_CUR_MAX + 1];
282 mbstate_t mbst = { 0 };
283 ssize_t len = wcrtomb(buf, c, &mbst);
284 if (len > 0) {
285 buf[len] = '\0';
286 fputs(buf, stdout);
287 }
288 } else {
289 /* In this case, c is always one byte */
290 putchar(c);
291 }
292}
293# if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
294static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
295# else
296static wchar_t adjust_width_and_validate_wc(wchar_t wc)
297# define adjust_width_and_validate_wc(width_adj, wc) \
298 ((*(width_adj))++, adjust_width_and_validate_wc(wc))
299# endif
300{
301 int w = 1;
302
303 if (unicode_status == UNICODE_ON) {
304 if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
305 /* note: also true for unicode_is_raw_byte(wc) */
306 goto subst;
307 }
308 w = wcwidth(wc);
309 if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
310 || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
311 || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
312 ) {
313 subst:
314 w = 1;
315 wc = CONFIG_SUBST_WCHAR;
316 }
317 }
318
319# if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
320 *width_adj += w;
321#endif
322 return wc;
323}
324#else /* !UNICODE */
325static size_t load_string(const char *src)
326{
327 safe_strncpy(command_ps, src, S.maxsize);
328 return strlen(command_ps);
329}
330# if ENABLE_FEATURE_TAB_COMPLETION
331static void save_string(char *dst, unsigned maxsize)
332{
333 safe_strncpy(dst, command_ps, maxsize);
334}
335# endif
336# define BB_PUTCHAR(c) bb_putchar(c)
337/* Should never be called: */
338int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
339#endif
340
341
342/* Put 'command_ps[cursor]', cursor++.
343 * Advance cursor on screen. If we reached right margin, scroll text up
344 * and remove terminal margin effect by printing 'next_char' */
345#define HACK_FOR_WRONG_WIDTH 1
346static void put_cur_glyph_and_inc_cursor(void)
347{
348 CHAR_T c = command_ps[cursor];
349 unsigned width = 0;
350 int ofs_to_right;
351
352 if (c == BB_NUL) {
353 /* erase character after end of input string */
354 c = ' ';
355 } else {
356 /* advance cursor only if we aren't at the end yet */
357 cursor++;
358 if (unicode_status == UNICODE_ON) {
359 IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
360 c = adjust_width_and_validate_wc(&cmdedit_x, c);
361 IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
362 } else {
363 cmdedit_x++;
364 }
365 }
366
367 ofs_to_right = cmdedit_x - cmdedit_termw;
368 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
369 /* c fits on this line */
370 BB_PUTCHAR(c);
371 }
372
373 if (ofs_to_right >= 0) {
374 /* we go to the next line */
375#if HACK_FOR_WRONG_WIDTH
376 /* This works better if our idea of term width is wrong
377 * and it is actually wider (often happens on serial lines).
378 * Printing CR,LF *forces* cursor to next line.
379 * OTOH if terminal width is correct AND terminal does NOT
380 * have automargin (IOW: it is moving cursor to next line
381 * by itself (which is wrong for VT-10x terminals)),
382 * this will break things: there will be one extra empty line */
383 puts("\r"); /* + implicit '\n' */
384#else
385 /* VT-10x terminals don't wrap cursor to next line when last char
386 * on the line is printed - cursor stays "over" this char.
387 * Need to print _next_ char too (first one to appear on next line)
388 * to make cursor move down to next line.
389 */
390 /* Works ok only if cmdedit_termw is correct. */
391 c = command_ps[cursor];
392 if (c == BB_NUL)
393 c = ' ';
394 BB_PUTCHAR(c);
395 bb_putchar('\b');
396#endif
397 cmdedit_y++;
398 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
399 width = 0;
400 } else { /* ofs_to_right > 0 */
401 /* wide char c didn't fit on prev line */
402 BB_PUTCHAR(c);
403 }
404 cmdedit_x = width;
405 }
406}
407
408/* Move to end of line (by printing all chars till the end) */
409static void put_till_end_and_adv_cursor(void)
410{
411 while (cursor < command_len)
412 put_cur_glyph_and_inc_cursor();
413}
414
415/* Go to the next line */
416static void goto_new_line(void)
417{
418 put_till_end_and_adv_cursor();
419 if (cmdedit_x != 0)
420 bb_putchar('\n');
421}
422
423static void beep(void)
424{
425 bb_putchar('\007');
426}
427
428static void put_prompt(void)
429{
430 unsigned w;
431
432 fputs(cmdedit_prompt, stdout);
433 fflush_all();
434 cursor = 0;
435 w = cmdedit_termw; /* read volatile var once */
436 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
437 cmdedit_x = cmdedit_prmt_len % w;
438}
439
440/* Move back one character */
441/* (optimized for slow terminals) */
442static void input_backward(unsigned num)
443{
444 if (num > cursor)
445 num = cursor;
446 if (num == 0)
447 return;
448 cursor -= num;
449
450 if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
451 && unicode_status == UNICODE_ON
452 ) {
453 /* correct NUM to be equal to _screen_ width */
454 int n = num;
455 num = 0;
456 while (--n >= 0)
457 adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
458 if (num == 0)
459 return;
460 }
461
462 if (cmdedit_x >= num) {
463 cmdedit_x -= num;
464 if (num <= 4) {
465 /* This is longer by 5 bytes on x86.
466 * Also gets miscompiled for ARM users
467 * (busybox.net/bugs/view.php?id=2274).
468 * printf(("\b\b\b\b" + 4) - num);
469 * return;
470 */
471 do {
472 bb_putchar('\b');
473 } while (--num);
474 return;
475 }
476 printf(ESC"[%uD", num);
477 return;
478 }
479
480 /* Need to go one or more lines up */
481 if (ENABLE_UNICODE_WIDE_WCHARS) {
482 /* With wide chars, it is hard to "backtrack"
483 * and reliably figure out where to put cursor.
484 * Example (<> is a wide char; # is an ordinary char, _ cursor):
485 * |prompt: <><> |
486 * |<><><><><><> |
487 * |_ |
488 * and user presses left arrow. num = 1, cmdedit_x = 0,
489 * We need to go up one line, and then - how do we know that
490 * we need to go *10* positions to the right? Because
491 * |prompt: <>#<>|
492 * |<><><>#<><><>|
493 * |_ |
494 * in this situation we need to go *11* positions to the right.
495 *
496 * A simpler thing to do is to redraw everything from the start
497 * up to new cursor position (which is already known):
498 */
499 unsigned sv_cursor;
500 /* go to 1st column; go up to first line */
501 printf("\r" ESC"[%uA", cmdedit_y);
502 cmdedit_y = 0;
503 sv_cursor = cursor;
504 put_prompt(); /* sets cursor to 0 */
505 while (cursor < sv_cursor)
506 put_cur_glyph_and_inc_cursor();
507 } else {
508 int lines_up;
509 unsigned width;
510 /* num = chars to go back from the beginning of current line: */
511 num -= cmdedit_x;
512 width = cmdedit_termw; /* read volatile var once */
513 /* num=1...w: one line up, w+1...2w: two, etc: */
514 lines_up = 1 + (num - 1) / width;
515 cmdedit_x = (width * cmdedit_y - num) % width;
516 cmdedit_y -= lines_up;
517 /* go to 1st column; go up */
518 printf("\r" ESC"[%uA", lines_up);
519 /* go to correct column.
520 * xterm, konsole, Linux VT interpret 0 as 1 below! wow.
521 * need to *make sure* we skip it if cmdedit_x == 0 */
522 if (cmdedit_x)
523 printf(ESC"[%uC", cmdedit_x);
524 }
525}
526
527/* draw prompt, editor line, and clear tail */
528static void redraw(int y, int back_cursor)
529{
530 if (y > 0) /* up y lines */
531 printf(ESC"[%uA", y);
532 bb_putchar('\r');
533 put_prompt();
534 put_till_end_and_adv_cursor();
535 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
536 input_backward(back_cursor);
537}
538
539/* Delete the char in front of the cursor, optionally saving it
540 * for later putback */
541#if !ENABLE_FEATURE_EDITING_VI
542static void input_delete(void)
543#define input_delete(save) input_delete()
544#else
545static void input_delete(int save)
546#endif
547{
548 int j = cursor;
549
550 if (j == (int)command_len)
551 return;
552
553#if ENABLE_FEATURE_EDITING_VI
554 if (save) {
555 if (newdelflag) {
556 delptr = delbuf;
557 newdelflag = 0;
558 }
559 if ((delptr - delbuf) < DELBUFSIZ)
560 *delptr++ = command_ps[j];
561 }
562#endif
563
564 memmove(command_ps + j, command_ps + j + 1,
565 /* (command_len + 1 [because of NUL]) - (j + 1)
566 * simplified into (command_len - j) */
567 (command_len - j) * sizeof(command_ps[0]));
568 command_len--;
569 put_till_end_and_adv_cursor();
570 /* Last char is still visible, erase it (and more) */
571 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
572 input_backward(cursor - j); /* back to old pos cursor */
573}
574
575#if ENABLE_FEATURE_EDITING_VI
576static void put(void)
577{
578 int ocursor;
579 int j = delptr - delbuf;
580
581 if (j == 0)
582 return;
583 ocursor = cursor;
584 /* open hole and then fill it */
585 memmove(command_ps + cursor + j, command_ps + cursor,
586 (command_len - cursor + 1) * sizeof(command_ps[0]));
587 memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
588 command_len += j;
589 put_till_end_and_adv_cursor();
590 input_backward(cursor - ocursor - j + 1); /* at end of new text */
591}
592#endif
593
594/* Delete the char in back of the cursor */
595static void input_backspace(void)
596{
597 if (cursor > 0) {
598 input_backward(1);
599 input_delete(0);
600 }
601}
602
603/* Move forward one character */
604static void input_forward(void)
605{
606 if (cursor < command_len)
607 put_cur_glyph_and_inc_cursor();
608}
609
610#if ENABLE_FEATURE_TAB_COMPLETION
611
612//FIXME:
613//needs to be more clever: currently it thinks that "foo\ b<TAB>
614//matches the file named "foo bar", which is untrue.
615//Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
616//not "foo bar <cursor>...
617
618static void free_tab_completion_data(void)
619{
620 if (matches) {
621 while (num_matches)
622 free(matches[--num_matches]);
623 free(matches);
624 matches = NULL;
625 }
626}
627
628static void add_match(char *matched)
629{
630 /*CVE-2017-16544 https://git.busybox.net/busybox/commit/?id=c3797d40a1c57352192c6106cc0f435e7d9c11e8*/
631 unsigned char *p = (unsigned char*)matched;
632 while (*p) {
633 /* ESC attack fix: drop any string with control chars */
634 if (*p < ' '
635 || (!ENABLE_UNICODE_SUPPORT && *p >= 0x7f)
636 || (ENABLE_UNICODE_SUPPORT && *p == 0x7f)
637 ) {
638 free(matched);
639 return;
640 }
641 p++;
642 }
643 matches = xrealloc_vector(matches, 4, num_matches);
644 matches[num_matches] = matched;
645 num_matches++;
646}
647
648# if ENABLE_FEATURE_USERNAME_COMPLETION
649/* Replace "~user/..." with "/homedir/...".
650 * The parameter is malloced, free it or return it
651 * unchanged if no user is matched.
652 */
653static char *username_path_completion(char *ud)
654{
655 struct passwd *entry;
656 char *tilde_name = ud;
657 char *home = NULL;
658
659 ud++; /* skip ~ */
660 if (*ud == '/') { /* "~/..." */
661 home = home_pwd_buf;
662 } else {
663 /* "~user/..." */
664 ud = strchr(ud, '/');
665 *ud = '\0'; /* "~user" */
666 entry = getpwnam(tilde_name + 1);
667 *ud = '/'; /* restore "~user/..." */
668 if (entry)
669 home = entry->pw_dir;
670 }
671 if (home) {
672 ud = concat_path_file(home, ud);
673 free(tilde_name);
674 tilde_name = ud;
675 }
676 return tilde_name;
677}
678
679/* ~use<tab> - find all users with this prefix.
680 * Return the length of the prefix used for matching.
681 */
682static NOINLINE unsigned complete_username(const char *ud)
683{
684 /* Using _r function to avoid pulling in static buffers */
685 char line_buff[256];
686 struct passwd pwd;
687 struct passwd *result;
688 unsigned userlen;
689
690 ud++; /* skip ~ */
691 userlen = strlen(ud);
692
693 setpwent();
694 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
695 /* Null usernames should result in all users as possible completions. */
696 if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
697 add_match(xasprintf("~%s/", pwd.pw_name));
698 }
699 }
700 endpwent();
701
702 return 1 + userlen;
703}
704# endif /* FEATURE_USERNAME_COMPLETION */
705
706enum {
707 FIND_EXE_ONLY = 0,
708 FIND_DIR_ONLY = 1,
709 FIND_FILE_ONLY = 2,
710};
711
712static int path_parse(char ***p)
713{
714 int npth;
715 const char *pth;
716 char *tmp;
717 char **res;
718
719 if (state->flags & WITH_PATH_LOOKUP)
720 pth = state->path_lookup;
721 else
722 pth = getenv("PATH");
723
724 /* PATH="" or PATH=":"? */
725 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
726 return 1;
727
728 tmp = (char*)pth;
729 npth = 1; /* path component count */
730 while (1) {
731 tmp = strchr(tmp, ':');
732 if (!tmp)
733 break;
734 tmp++;
735 if (*tmp == '\0')
736 break; /* :<empty> */
737 npth++;
738 }
739
740 *p = res = xmalloc(npth * sizeof(res[0]));
741 res[0] = tmp = xstrdup(pth);
742 npth = 1;
743 while (1) {
744 tmp = strchr(tmp, ':');
745 if (!tmp)
746 break;
747 *tmp++ = '\0'; /* ':' -> '\0' */
748 if (*tmp == '\0')
749 break; /* :<empty> */
750 res[npth++] = tmp;
751 }
752 return npth;
753}
754
755/* Complete command, directory or file name.
756 * Return the length of the prefix used for matching.
757 */
758static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
759{
760 char *path1[1];
761 char **paths = path1;
762 int npaths;
763 int i;
764 unsigned pf_len;
765 const char *pfind;
766 char *dirbuf = NULL;
767
768 npaths = 1;
769 path1[0] = (char*)".";
770
771 pfind = strrchr(command, '/');
772 if (!pfind) {
773 if (type == FIND_EXE_ONLY)
774 npaths = path_parse(&paths);
775 pfind = command;
776 } else {
777 /* point to 'l' in "..../last_component" */
778 pfind++;
779 /* dirbuf = ".../.../.../" */
780 dirbuf = xstrndup(command, pfind - command);
781# if ENABLE_FEATURE_USERNAME_COMPLETION
782 if (dirbuf[0] == '~') /* ~/... or ~user/... */
783 dirbuf = username_path_completion(dirbuf);
784# endif
785 path1[0] = dirbuf;
786 }
787 pf_len = strlen(pfind);
788
789 for (i = 0; i < npaths; i++) {
790 DIR *dir;
791 struct dirent *next;
792 struct stat st;
793 char *found;
794
795 dir = opendir(paths[i]);
796 if (!dir)
797 continue; /* don't print an error */
798
799 while ((next = readdir(dir)) != NULL) {
800 unsigned len;
801 const char *name_found = next->d_name;
802
803 /* .../<tab>: bash 3.2.0 shows dotfiles, but not . and .. */
804 if (!pfind[0] && DOT_OR_DOTDOT(name_found))
805 continue;
806 /* match? */
807 if (strncmp(name_found, pfind, pf_len) != 0)
808 continue; /* no */
809
810 found = concat_path_file(paths[i], name_found);
811 /* NB: stat() first so that we see is it a directory;
812 * but if that fails, use lstat() so that
813 * we still match dangling links */
814 if (stat(found, &st) && lstat(found, &st))
815 goto cont; /* hmm, remove in progress? */
816
817 /* Save only name */
818 len = strlen(name_found);
819 found = xrealloc(found, len + 2); /* +2: for slash and NUL */
820 strcpy(found, name_found);
821
822 if (S_ISDIR(st.st_mode)) {
823 /* name is a directory, add slash */
824 found[len] = '/';
825 found[len + 1] = '\0';
826 } else {
827 /* skip files if looking for dirs only (example: cd) */
828 if (type == FIND_DIR_ONLY)
829 goto cont;
830 }
831 /* add it to the list */
832 add_match(found);
833 continue;
834 cont:
835 free(found);
836 }
837 closedir(dir);
838 } /* for every path */
839
840 if (paths != path1) {
841 free(paths[0]); /* allocated memory is only in first member */
842 free(paths);
843 }
844 free(dirbuf);
845
846 return pf_len;
847}
848
849/* build_match_prefix:
850 * On entry, match_buf contains everything up to cursor at the moment <tab>
851 * was pressed. This function looks at it, figures out what part of it
852 * constitutes the command/file/directory prefix to use for completion,
853 * and rewrites match_buf to contain only that part.
854 */
855#define dbg_bmp 0
856/* Helpers: */
857/* QUOT is used on elements of int_buf[], which are bytes,
858 * not Unicode chars. Therefore it works correctly even in Unicode mode.
859 */
860#define QUOT (UCHAR_MAX+1)
861static void remove_chunk(int16_t *int_buf, int beg, int end)
862{
863 /* beg must be <= end */
864 if (beg == end)
865 return;
866
867 while ((int_buf[beg] = int_buf[end]) != 0)
868 beg++, end++;
869
870 if (dbg_bmp) {
871 int i;
872 for (i = 0; int_buf[i]; i++)
873 bb_putchar((unsigned char)int_buf[i]);
874 bb_putchar('\n');
875 }
876}
877/* Caller ensures that match_buf points to a malloced buffer
878 * big enough to hold strlen(match_buf)*2 + 2
879 */
880static NOINLINE int build_match_prefix(char *match_buf)
881{
882 int i, j;
883 int command_mode;
884 int16_t *int_buf = (int16_t*)match_buf;
885
886 if (dbg_bmp) printf("\n%s\n", match_buf);
887
888 /* Copy in reverse order, since they overlap */
889 i = strlen(match_buf);
890 do {
891 int_buf[i] = (unsigned char)match_buf[i];
892 i--;
893 } while (i >= 0);
894
895 /* Mark every \c as "quoted c" */
896 for (i = 0; int_buf[i]; i++) {
897 if (int_buf[i] == '\\') {
898 remove_chunk(int_buf, i, i + 1);
899 int_buf[i] |= QUOT;
900 }
901 }
902 /* Quote-mark "chars" and 'chars', drop delimiters */
903 {
904 int in_quote = 0;
905 i = 0;
906 while (int_buf[i]) {
907 int cur = int_buf[i];
908 if (!cur)
909 break;
910 if (cur == '\'' || cur == '"') {
911 if (!in_quote || (cur == in_quote)) {
912 in_quote ^= cur;
913 remove_chunk(int_buf, i, i + 1);
914 continue;
915 }
916 }
917 if (in_quote)
918 int_buf[i] = cur | QUOT;
919 i++;
920 }
921 }
922
923 /* Remove everything up to command delimiters:
924 * ';' ';;' '&' '|' '&&' '||',
925 * but careful with '>&' '<&' '>|'
926 */
927 for (i = 0; int_buf[i]; i++) {
928 int cur = int_buf[i];
929 if (cur == ';' || cur == '&' || cur == '|') {
930 int prev = i ? int_buf[i - 1] : 0;
931 if (cur == '&' && (prev == '>' || prev == '<')) {
932 continue;
933 } else if (cur == '|' && prev == '>') {
934 continue;
935 }
936 remove_chunk(int_buf, 0, i + 1 + (cur == int_buf[i + 1]));
937 i = -1; /* back to square 1 */
938 }
939 }
940 /* Remove all `cmd` */
941 for (i = 0; int_buf[i]; i++) {
942 if (int_buf[i] == '`') {
943 for (j = i + 1; int_buf[j]; j++) {
944 if (int_buf[j] == '`') {
945 /* `cmd` should count as a word:
946 * `cmd` c<tab> should search for files c*,
947 * not commands c*. Therefore we don't drop
948 * `cmd` entirely, we replace it with single `.
949 */
950 remove_chunk(int_buf, i, j);
951 goto next;
952 }
953 }
954 /* No closing ` - command mode, remove all up to ` */
955 remove_chunk(int_buf, 0, i + 1);
956 break;
957 next: ;
958 }
959 }
960
961 /* Remove "cmd (" and "cmd {"
962 * Example: "if { c<tab>"
963 * In this example, c should be matched as command pfx.
964 */
965 for (i = 0; int_buf[i]; i++) {
966 if (int_buf[i] == '(' || int_buf[i] == '{') {
967 remove_chunk(int_buf, 0, i + 1);
968 i = -1; /* back to square 1 */
969 }
970 }
971
972 /* Remove leading unquoted spaces */
973 for (i = 0; int_buf[i]; i++)
974 if (int_buf[i] != ' ')
975 break;
976 remove_chunk(int_buf, 0, i);
977
978 /* Determine completion mode */
979 command_mode = FIND_EXE_ONLY;
980 for (i = 0; int_buf[i]; i++) {
981 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
982 if (int_buf[i] == ' '
983 && command_mode == FIND_EXE_ONLY
984 && (char)int_buf[0] == 'c'
985 && (char)int_buf[1] == 'd'
986 && i == 2 /* -> int_buf[2] == ' ' */
987 ) {
988 command_mode = FIND_DIR_ONLY;
989 } else {
990 command_mode = FIND_FILE_ONLY;
991 break;
992 }
993 }
994 }
995 if (dbg_bmp) printf("command_mode(0:exe/1:dir/2:file):%d\n", command_mode);
996
997 /* Remove everything except last word */
998 for (i = 0; int_buf[i]; i++) /* quasi-strlen(int_buf) */
999 continue;
1000 for (--i; i >= 0; i--) {
1001 int cur = int_buf[i];
1002 if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
1003 remove_chunk(int_buf, 0, i + 1);
1004 break;
1005 }
1006 }
1007
1008 /* Convert back to string of _chars_ */
1009 i = 0;
1010 while ((match_buf[i] = int_buf[i]) != '\0')
1011 i++;
1012
1013 if (dbg_bmp) printf("final match_buf:'%s'\n", match_buf);
1014
1015 return command_mode;
1016}
1017
1018/*
1019 * Display by column (original idea from ls applet,
1020 * very optimized by me [Vladimir] :)
1021 */
1022static void showfiles(void)
1023{
1024 int ncols, row;
1025 int column_width = 0;
1026 int nfiles = num_matches;
1027 int nrows = nfiles;
1028 int l;
1029
1030 /* find the longest file name - use that as the column width */
1031 for (row = 0; row < nrows; row++) {
1032 l = unicode_strwidth(matches[row]);
1033 if (column_width < l)
1034 column_width = l;
1035 }
1036 column_width += 2; /* min space for columns */
1037 ncols = cmdedit_termw / column_width;
1038
1039 if (ncols > 1) {
1040 nrows /= ncols;
1041 if (nfiles % ncols)
1042 nrows++; /* round up fractionals */
1043 } else {
1044 ncols = 1;
1045 }
1046 for (row = 0; row < nrows; row++) {
1047 int n = row;
1048 int nc;
1049
1050 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
1051 printf("%s%-*s", matches[n],
1052 (int)(column_width - unicode_strwidth(matches[n])), ""
1053 );
1054 }
1055 if (ENABLE_UNICODE_SUPPORT)
1056 puts(printable_string(NULL, matches[n]));
1057 else
1058 puts(matches[n]);
1059 }
1060}
1061
1062static const char *is_special_char(char c)
1063{
1064 return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
1065}
1066
1067static char *quote_special_chars(char *found)
1068{
1069 int l = 0;
1070 char *s = xzalloc((strlen(found) + 1) * 2);
1071
1072 while (*found) {
1073 if (is_special_char(*found))
1074 s[l++] = '\\';
1075 s[l++] = *found++;
1076 }
1077 /* s[l] = '\0'; - already is */
1078 return s;
1079}
1080
1081/* Do TAB completion */
1082static NOINLINE void input_tab(smallint *lastWasTab)
1083{
1084 char *chosen_match;
1085 char *match_buf;
1086 size_t len_found;
1087 /* Length of string used for matching */
1088 unsigned match_pfx_len = match_pfx_len;
1089 int find_type;
1090# if ENABLE_UNICODE_SUPPORT
1091 /* cursor pos in command converted to multibyte form */
1092 int cursor_mb;
1093# endif
1094 if (!(state->flags & TAB_COMPLETION))
1095 return;
1096
1097 if (*lastWasTab) {
1098 /* The last char was a TAB too.
1099 * Print a list of all the available choices.
1100 */
1101 if (num_matches > 0) {
1102 /* cursor will be changed by goto_new_line() */
1103 int sav_cursor = cursor;
1104 goto_new_line();
1105 showfiles();
1106 redraw(0, command_len - sav_cursor);
1107 }
1108 return;
1109 }
1110
1111 *lastWasTab = 1;
1112 chosen_match = NULL;
1113
1114 /* Make a local copy of the string up to the position of the cursor.
1115 * build_match_prefix will expand it into int16_t's, need to allocate
1116 * twice as much as the string_len+1.
1117 * (we then also (ab)use this extra space later - see (**))
1118 */
1119 match_buf = xmalloc(MAX_LINELEN * sizeof(int16_t));
1120# if !ENABLE_UNICODE_SUPPORT
1121 save_string(match_buf, cursor + 1); /* +1 for NUL */
1122# else
1123 {
1124 CHAR_T wc = command_ps[cursor];
1125 command_ps[cursor] = BB_NUL;
1126 save_string(match_buf, MAX_LINELEN);
1127 command_ps[cursor] = wc;
1128 cursor_mb = strlen(match_buf);
1129 }
1130# endif
1131 find_type = build_match_prefix(match_buf);
1132
1133 /* Free up any memory already allocated */
1134 free_tab_completion_data();
1135
1136# if ENABLE_FEATURE_USERNAME_COMPLETION
1137 /* If the word starts with ~ and there is no slash in the word,
1138 * then try completing this word as a username. */
1139 if (state->flags & USERNAME_COMPLETION)
1140 if (match_buf[0] == '~' && strchr(match_buf, '/') == NULL)
1141 match_pfx_len = complete_username(match_buf);
1142# endif
1143 /* If complete_username() did not match,
1144 * try to match a command in $PATH, or a directory, or a file */
1145 if (!matches)
1146 match_pfx_len = complete_cmd_dir_file(match_buf, find_type);
1147
1148 /* Account for backslashes which will be inserted
1149 * by quote_special_chars() later */
1150 {
1151 const char *e = match_buf + strlen(match_buf);
1152 const char *s = e - match_pfx_len;
1153 while (s < e)
1154 if (is_special_char(*s++))
1155 match_pfx_len++;
1156 }
1157
1158 /* Remove duplicates */
1159 if (matches) {
1160 unsigned i, n = 0;
1161 qsort_string_vector(matches, num_matches);
1162 for (i = 0; i < num_matches - 1; ++i) {
1163 //if (matches[i] && matches[i+1]) { /* paranoia */
1164 if (strcmp(matches[i], matches[i+1]) == 0) {
1165 free(matches[i]);
1166 //matches[i] = NULL; /* paranoia */
1167 } else {
1168 matches[n++] = matches[i];
1169 }
1170 //}
1171 }
1172 matches[n++] = matches[i];
1173 num_matches = n;
1174 }
1175
1176 /* Did we find exactly one match? */
1177 if (num_matches != 1) { /* no */
1178 char *cp;
1179 beep();
1180 if (!matches)
1181 goto ret; /* no matches at all */
1182 /* Find common prefix */
1183 chosen_match = xstrdup(matches[0]);
1184 for (cp = chosen_match; *cp; cp++) {
1185 unsigned n;
1186 for (n = 1; n < num_matches; n++) {
1187 if (matches[n][cp - chosen_match] != *cp) {
1188 goto stop;
1189 }
1190 }
1191 }
1192 stop:
1193 if (cp == chosen_match) { /* have unique prefix? */
1194 goto ret; /* no */
1195 }
1196 *cp = '\0';
1197 cp = quote_special_chars(chosen_match);
1198 free(chosen_match);
1199 chosen_match = cp;
1200 len_found = strlen(chosen_match);
1201 } else { /* exactly one match */
1202 /* Next <tab> is not a double-tab */
1203 *lastWasTab = 0;
1204
1205 chosen_match = quote_special_chars(matches[0]);
1206 len_found = strlen(chosen_match);
1207 if (chosen_match[len_found-1] != '/') {
1208 chosen_match[len_found] = ' ';
1209 chosen_match[++len_found] = '\0';
1210 }
1211 }
1212
1213# if !ENABLE_UNICODE_SUPPORT
1214 /* Have space to place the match? */
1215 /* The result consists of three parts with these lengths: */
1216 /* cursor + (len_found - match_pfx_len) + (command_len - cursor) */
1217 /* it simplifies into: */
1218 if ((int)(len_found - match_pfx_len + command_len) < S.maxsize) {
1219 int pos;
1220 /* save tail */
1221 strcpy(match_buf, &command_ps[cursor]);
1222 /* add match and tail */
1223 sprintf(&command_ps[cursor], "%s%s", chosen_match + match_pfx_len, match_buf);
1224 command_len = strlen(command_ps);
1225 /* new pos */
1226 pos = cursor + len_found - match_pfx_len;
1227 /* write out the matched command */
1228 redraw(cmdedit_y, command_len - pos);
1229 }
1230# else
1231 {
1232 /* Use 2nd half of match_buf as scratch space - see (**) */
1233 char *command = match_buf + MAX_LINELEN;
1234 int len = save_string(command, MAX_LINELEN);
1235 /* Have space to place the match? */
1236 /* cursor_mb + (len_found - match_pfx_len) + (len - cursor_mb) */
1237 if ((int)(len_found - match_pfx_len + len) < MAX_LINELEN) {
1238 int pos;
1239 /* save tail */
1240 strcpy(match_buf, &command[cursor_mb]);
1241 /* where do we want to have cursor after all? */
1242 strcpy(&command[cursor_mb], chosen_match + match_pfx_len);
1243 len = load_string(command);
1244 /* add match and tail */
1245 sprintf(&command[cursor_mb], "%s%s", chosen_match + match_pfx_len, match_buf);
1246 command_len = load_string(command);
1247 /* write out the matched command */
1248 /* paranoia: load_string can return 0 on conv error,
1249 * prevent passing pos = (0 - 12) to redraw */
1250 pos = command_len - len;
1251 redraw(cmdedit_y, pos >= 0 ? pos : 0);
1252 }
1253 }
1254# endif
1255 ret:
1256 free(chosen_match);
1257 free(match_buf);
1258}
1259
1260#endif /* FEATURE_TAB_COMPLETION */
1261
1262
1263line_input_t* FAST_FUNC new_line_input_t(int flags)
1264{
1265 line_input_t *n = xzalloc(sizeof(*n));
1266 n->flags = flags;
1267 n->max_history = MAX_HISTORY;
1268 return n;
1269}
1270
1271
1272#if MAX_HISTORY > 0
1273
1274unsigned size_from_HISTFILESIZE(const char *hp)
1275{
1276 int size = MAX_HISTORY;
1277 if (hp) {
1278 size = atoi(hp);
1279 if (size <= 0)
1280 return 1;
1281 if (size > MAX_HISTORY)
1282 return MAX_HISTORY;
1283 }
1284 return size;
1285}
1286
1287static void save_command_ps_at_cur_history(void)
1288{
1289 if (command_ps[0] != BB_NUL) {
1290 int cur = state->cur_history;
1291 free(state->history[cur]);
1292
1293# if ENABLE_UNICODE_SUPPORT
1294 {
1295 char tbuf[MAX_LINELEN];
1296 save_string(tbuf, sizeof(tbuf));
1297 state->history[cur] = xstrdup(tbuf);
1298 }
1299# else
1300 state->history[cur] = xstrdup(command_ps);
1301# endif
1302 }
1303}
1304
1305/* state->flags is already checked to be nonzero */
1306static int get_previous_history(void)
1307{
1308 if ((state->flags & DO_HISTORY) && state->cur_history) {
1309 save_command_ps_at_cur_history();
1310 state->cur_history--;
1311 return 1;
1312 }
1313 beep();
1314 return 0;
1315}
1316
1317static int get_next_history(void)
1318{
1319 if (state->flags & DO_HISTORY) {
1320 if (state->cur_history < state->cnt_history) {
1321 save_command_ps_at_cur_history(); /* save the current history line */
1322 return ++state->cur_history;
1323 }
1324 }
1325 beep();
1326 return 0;
1327}
1328
1329# if ENABLE_FEATURE_EDITING_SAVEHISTORY
1330/* We try to ensure that concurrent additions to the history
1331 * do not overwrite each other.
1332 * Otherwise shell users get unhappy.
1333 *
1334 * History file is trimmed lazily, when it grows several times longer
1335 * than configured MAX_HISTORY lines.
1336 */
1337
1338static void free_line_input_t(line_input_t *n)
1339{
1340 int i = n->cnt_history;
1341 while (i > 0)
1342 free(n->history[--i]);
1343 free(n);
1344}
1345
1346/* state->flags is already checked to be nonzero */
1347static void load_history(line_input_t *st_parm)
1348{
1349 char *temp_h[MAX_HISTORY];
1350 char *line;
1351 FILE *fp;
1352 unsigned idx, i, line_len;
1353
1354 /* NB: do not trash old history if file can't be opened */
1355
1356 fp = fopen_for_read(st_parm->hist_file);
1357 if (fp) {
1358 /* clean up old history */
1359 for (idx = st_parm->cnt_history; idx > 0;) {
1360 idx--;
1361 free(st_parm->history[idx]);
1362 st_parm->history[idx] = NULL;
1363 }
1364
1365 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1366 memset(temp_h, 0, sizeof(temp_h));
1367 idx = 0;
1368 st_parm->cnt_history_in_file = 0;
1369 while ((line = xmalloc_fgetline(fp)) != NULL) {
1370 if (line[0] == '\0') {
1371 free(line);
1372 continue;
1373 }
1374 free(temp_h[idx]);
1375 temp_h[idx] = line;
1376 st_parm->cnt_history_in_file++;
1377 idx++;
1378 if (idx == st_parm->max_history)
1379 idx = 0;
1380 }
1381 fclose(fp);
1382
1383 /* find first non-NULL temp_h[], if any */
1384 if (st_parm->cnt_history_in_file) {
1385 while (temp_h[idx] == NULL) {
1386 idx++;
1387 if (idx == st_parm->max_history)
1388 idx = 0;
1389 }
1390 }
1391
1392 /* copy temp_h[] to st_parm->history[] */
1393 for (i = 0; i < st_parm->max_history;) {
1394 line = temp_h[idx];
1395 if (!line)
1396 break;
1397 idx++;
1398 if (idx == st_parm->max_history)
1399 idx = 0;
1400 line_len = strlen(line);
1401 if (line_len >= MAX_LINELEN)
1402 line[MAX_LINELEN-1] = '\0';
1403 st_parm->history[i++] = line;
1404 }
1405 st_parm->cnt_history = i;
1406 if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
1407 st_parm->cnt_history_in_file = i;
1408 }
1409}
1410
1411# if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1412void save_history(line_input_t *st)
1413{
1414 FILE *fp;
1415
1416 if (!st->hist_file)
1417 return;
1418 if (st->cnt_history <= st->cnt_history_in_file)
1419 return;
1420
1421 fp = fopen(st->hist_file, "a");
1422 if (fp) {
1423 int i, fd;
1424 char *new_name;
1425 line_input_t *st_temp;
1426
1427 for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
1428 fprintf(fp, "%s\n", st->history[i]);
1429 fclose(fp);
1430
1431 /* we may have concurrently written entries from others.
1432 * load them */
1433 st_temp = new_line_input_t(st->flags);
1434 st_temp->hist_file = st->hist_file;
1435 st_temp->max_history = st->max_history;
1436 load_history(st_temp);
1437
1438 /* write out temp file and replace hist_file atomically */
1439 new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
1440 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1441 if (fd >= 0) {
1442 fp = xfdopen_for_write(fd);
1443 for (i = 0; i < st_temp->cnt_history; i++)
1444 fprintf(fp, "%s\n", st_temp->history[i]);
1445 fclose(fp);
1446 if (rename(new_name, st->hist_file) == 0)
1447 st->cnt_history_in_file = st_temp->cnt_history;
1448 }
1449 free(new_name);
1450 free_line_input_t(st_temp);
1451 }
1452}
1453# else
1454static void save_history(char *str)
1455{
1456 int fd;
1457 int len, len2;
1458
1459 if (!state->hist_file)
1460 return;
1461
1462 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
1463 if (fd < 0)
1464 return;
1465 xlseek(fd, 0, SEEK_END); /* paranoia */
1466 len = strlen(str);
1467 str[len] = '\n'; /* we (try to) do atomic write */
1468 len2 = full_write(fd, str, len + 1);
1469 str[len] = '\0';
1470 close(fd);
1471 if (len2 != len + 1)
1472 return; /* "wtf?" */
1473
1474 /* did we write so much that history file needs trimming? */
1475 state->cnt_history_in_file++;
1476 if (state->cnt_history_in_file > state->max_history * 4) {
1477 char *new_name;
1478 line_input_t *st_temp;
1479
1480 /* we may have concurrently written entries from others.
1481 * load them */
1482 st_temp = new_line_input_t(state->flags);
1483 st_temp->hist_file = state->hist_file;
1484 st_temp->max_history = state->max_history;
1485 load_history(st_temp);
1486
1487 /* write out temp file and replace hist_file atomically */
1488 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1489 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1490 if (fd >= 0) {
1491 FILE *fp;
1492 int i;
1493
1494 fp = xfdopen_for_write(fd);
1495 for (i = 0; i < st_temp->cnt_history; i++)
1496 fprintf(fp, "%s\n", st_temp->history[i]);
1497 fclose(fp);
1498 if (rename(new_name, state->hist_file) == 0)
1499 state->cnt_history_in_file = st_temp->cnt_history;
1500 }
1501 free(new_name);
1502 free_line_input_t(st_temp);
1503 }
1504}
1505# endif
1506# else
1507# define load_history(a) ((void)0)
1508# define save_history(a) ((void)0)
1509# endif /* FEATURE_COMMAND_SAVEHISTORY */
1510
1511static void remember_in_history(char *str)
1512{
1513 int i;
1514
1515 if (!(state->flags & DO_HISTORY))
1516 return;
1517 if (str[0] == '\0')
1518 return;
1519 i = state->cnt_history;
1520 /* Don't save dupes */
1521 if (i && strcmp(state->history[i-1], str) == 0)
1522 return;
1523
1524 free(state->history[state->max_history]); /* redundant, paranoia */
1525 state->history[state->max_history] = NULL; /* redundant, paranoia */
1526
1527 /* If history[] is full, remove the oldest command */
1528 /* we need to keep history[state->max_history] empty, hence >=, not > */
1529 if (i >= state->max_history) {
1530 free(state->history[0]);
1531 for (i = 0; i < state->max_history-1; i++)
1532 state->history[i] = state->history[i+1];
1533 /* i == state->max_history-1 */
1534# if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1535 if (state->cnt_history_in_file)
1536 state->cnt_history_in_file--;
1537# endif
1538 }
1539 /* i <= state->max_history-1 */
1540 state->history[i++] = xstrdup(str);
1541 /* i <= state->max_history */
1542 state->cur_history = i;
1543 state->cnt_history = i;
1544# if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1545 save_history(str);
1546# endif
1547 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1548}
1549
1550#else /* MAX_HISTORY == 0 */
1551# define remember_in_history(a) ((void)0)
1552#endif /* MAX_HISTORY */
1553
1554
1555#if ENABLE_FEATURE_EDITING_VI
1556/*
1557 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1558 */
1559static void
1560vi_Word_motion(int eat)
1561{
1562 CHAR_T *command = command_ps;
1563
1564 while (cursor < command_len && !BB_isspace(command[cursor]))
1565 input_forward();
1566 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1567 input_forward();
1568}
1569
1570static void
1571vi_word_motion(int eat)
1572{
1573 CHAR_T *command = command_ps;
1574
1575 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1576 while (cursor < command_len
1577 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1578 ) {
1579 input_forward();
1580 }
1581 } else if (BB_ispunct(command[cursor])) {
1582 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1583 input_forward();
1584 }
1585
1586 if (cursor < command_len)
1587 input_forward();
1588
1589 if (eat) {
1590 while (cursor < command_len && BB_isspace(command[cursor]))
1591 input_forward();
1592 }
1593}
1594
1595static void
1596vi_End_motion(void)
1597{
1598 CHAR_T *command = command_ps;
1599
1600 input_forward();
1601 while (cursor < command_len && BB_isspace(command[cursor]))
1602 input_forward();
1603 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1604 input_forward();
1605}
1606
1607static void
1608vi_end_motion(void)
1609{
1610 CHAR_T *command = command_ps;
1611
1612 if (cursor >= command_len-1)
1613 return;
1614 input_forward();
1615 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1616 input_forward();
1617 if (cursor >= command_len-1)
1618 return;
1619 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1620 while (cursor < command_len-1
1621 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1622 ) {
1623 input_forward();
1624 }
1625 } else if (BB_ispunct(command[cursor])) {
1626 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1627 input_forward();
1628 }
1629}
1630
1631static void
1632vi_Back_motion(void)
1633{
1634 CHAR_T *command = command_ps;
1635
1636 while (cursor > 0 && BB_isspace(command[cursor-1]))
1637 input_backward(1);
1638 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1639 input_backward(1);
1640}
1641
1642static void
1643vi_back_motion(void)
1644{
1645 CHAR_T *command = command_ps;
1646
1647 if (cursor <= 0)
1648 return;
1649 input_backward(1);
1650 while (cursor > 0 && BB_isspace(command[cursor]))
1651 input_backward(1);
1652 if (cursor <= 0)
1653 return;
1654 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1655 while (cursor > 0
1656 && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1657 ) {
1658 input_backward(1);
1659 }
1660 } else if (BB_ispunct(command[cursor])) {
1661 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1662 input_backward(1);
1663 }
1664}
1665#endif
1666
1667/* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1668static void ctrl_left(void)
1669{
1670 CHAR_T *command = command_ps;
1671
1672 while (1) {
1673 CHAR_T c;
1674
1675 input_backward(1);
1676 if (cursor == 0)
1677 break;
1678 c = command[cursor];
1679 if (c != ' ' && !BB_ispunct(c)) {
1680 /* we reached a "word" delimited by spaces/punct.
1681 * go to its beginning */
1682 while (1) {
1683 c = command[cursor - 1];
1684 if (c == ' ' || BB_ispunct(c))
1685 break;
1686 input_backward(1);
1687 if (cursor == 0)
1688 break;
1689 }
1690 break;
1691 }
1692 }
1693}
1694static void ctrl_right(void)
1695{
1696 CHAR_T *command = command_ps;
1697
1698 while (1) {
1699 CHAR_T c;
1700
1701 c = command[cursor];
1702 if (c == BB_NUL)
1703 break;
1704 if (c != ' ' && !BB_ispunct(c)) {
1705 /* we reached a "word" delimited by spaces/punct.
1706 * go to its end + 1 */
1707 while (1) {
1708 input_forward();
1709 c = command[cursor];
1710 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1711 break;
1712 }
1713 break;
1714 }
1715 input_forward();
1716 }
1717}
1718
1719
1720/*
1721 * read_line_input and its helpers
1722 */
1723
1724#if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1725static void ask_terminal(void)
1726{
1727 /* Ask terminal where is the cursor now.
1728 * lineedit_read_key handles response and corrects
1729 * our idea of current cursor position.
1730 * Testcase: run "echo -n long_line_long_line_long_line",
1731 * then type in a long, wrapping command and try to
1732 * delete it using backspace key.
1733 * Note: we print it _after_ prompt, because
1734 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
1735 */
1736 /* Problem: if there is buffered input on stdin,
1737 * the response will be delivered later,
1738 * possibly to an unsuspecting application.
1739 * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
1740 * Result:
1741 * ~/srcdevel/bbox/fix/busybox.t4 #
1742 * ~/srcdevel/bbox/fix/busybox.t4 #
1743 * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
1744 * ~/srcdevel/bbox/fix/busybox.t4 #
1745 *
1746 * Checking for input with poll only makes the race narrower,
1747 * I still can trigger it. Strace:
1748 *
1749 * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
1750 * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
1751 * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
1752 * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
1753 * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
1754 */
1755 struct pollfd pfd;
1756
1757 pfd.fd = STDIN_FILENO;
1758 pfd.events = POLLIN;
1759 if (safe_poll(&pfd, 1, 0) == 0) {
1760 S.sent_ESC_br6n = 1;
1761 fputs(ESC"[6n", stdout);
1762 fflush_all(); /* make terminal see it ASAP! */
1763 }
1764}
1765#else
1766#define ask_terminal() ((void)0)
1767#endif
1768
1769#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1770static void parse_and_put_prompt(const char *prmt_ptr)
1771{
1772 cmdedit_prompt = prmt_ptr;
1773 cmdedit_prmt_len = strlen(prmt_ptr);
1774 put_prompt();
1775}
1776#else
1777static void parse_and_put_prompt(const char *prmt_ptr)
1778{
1779 int prmt_len = 0;
1780 size_t cur_prmt_len = 0;
1781 char flg_not_length = '[';
1782 char *prmt_mem_ptr = xzalloc(1);
1783 char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1784 char cbuf[2];
1785 char c;
1786 char *pbuf;
1787
1788 cmdedit_prmt_len = 0;
1789
1790 if (!cwd_buf) {
1791 cwd_buf = (char *)bb_msg_unknown;
1792 }
1793
1794 cbuf[1] = '\0'; /* never changes */
1795
1796 while (*prmt_ptr) {
1797 char *free_me = NULL;
1798
1799 pbuf = cbuf;
1800 c = *prmt_ptr++;
1801 if (c == '\\') {
1802 const char *cp = prmt_ptr;
1803 int l;
1804
1805 c = bb_process_escape_sequence(&prmt_ptr);
1806 if (prmt_ptr == cp) {
1807 if (*cp == '\0')
1808 break;
1809 c = *prmt_ptr++;
1810
1811 switch (c) {
1812# if ENABLE_USERNAME_OR_HOMEDIR
1813 case 'u':
1814 pbuf = user_buf ? user_buf : (char*)"";
1815 break;
1816# endif
1817 case 'h':
1818 pbuf = free_me = safe_gethostname();
1819 *strchrnul(pbuf, '.') = '\0';
1820 break;
1821 case '$':
1822 c = (geteuid() == 0 ? '#' : '$');
1823 break;
1824# if ENABLE_USERNAME_OR_HOMEDIR
1825 case 'w':
1826 /* /home/user[/something] -> ~[/something] */
1827 pbuf = cwd_buf;
1828 l = strlen(home_pwd_buf);
1829 if (l != 0
1830 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1831 && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1832 && strlen(cwd_buf + l) < PATH_MAX
1833 ) {
1834 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1835 }
1836 break;
1837# endif
1838 case 'W':
1839 pbuf = cwd_buf;
1840 cp = strrchr(pbuf, '/');
1841 if (cp != NULL && cp != pbuf)
1842 pbuf += (cp-pbuf) + 1;
1843 break;
1844 case '!':
1845 pbuf = free_me = xasprintf("%d", num_ok_lines);
1846 break;
1847 case 'e': case 'E': /* \e \E = \033 */
1848 c = '\033';
1849 break;
1850 case 'x': case 'X': {
1851 char buf2[4];
1852 for (l = 0; l < 3;) {
1853 unsigned h;
1854 buf2[l++] = *prmt_ptr;
1855 buf2[l] = '\0';
1856 h = strtoul(buf2, &pbuf, 16);
1857 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1858 buf2[--l] = '\0';
1859 break;
1860 }
1861 prmt_ptr++;
1862 }
1863 c = (char)strtoul(buf2, NULL, 16);
1864 if (c == 0)
1865 c = '?';
1866 pbuf = cbuf;
1867 break;
1868 }
1869 case '[': case ']':
1870 if (c == flg_not_length) {
1871 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1872 continue;
1873 }
1874 break;
1875 } /* switch */
1876 } /* if */
1877 } /* if */
1878 cbuf[0] = c;
1879 cur_prmt_len = strlen(pbuf);
1880 prmt_len += cur_prmt_len;
1881 if (flg_not_length != ']')
1882 cmdedit_prmt_len += cur_prmt_len;
1883 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1884 free(free_me);
1885 } /* while */
1886
1887 if (cwd_buf != (char *)bb_msg_unknown)
1888 free(cwd_buf);
1889 cmdedit_prompt = prmt_mem_ptr;
1890 put_prompt();
1891}
1892#endif
1893
1894static void cmdedit_setwidth(unsigned w, int redraw_flg)
1895{
1896 cmdedit_termw = w;
1897 if (redraw_flg) {
1898 /* new y for current cursor */
1899 int new_y = (cursor + cmdedit_prmt_len) / w;
1900 /* redraw */
1901 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1902 fflush_all();
1903 }
1904}
1905
1906static void win_changed(int nsig)
1907{
1908 int sv_errno = errno;
1909 unsigned width;
1910
1911 get_terminal_width_height(0, &width, NULL);
1912//FIXME: cmdedit_setwidth() -> redraw() -> printf() -> KABOOM! (we are in signal handler!)
1913 cmdedit_setwidth(width, /*redraw_flg:*/ nsig);
1914
1915 errno = sv_errno;
1916}
1917
1918static int lineedit_read_key(char *read_key_buffer, int timeout)
1919{
1920 int64_t ic;
1921#if ENABLE_UNICODE_SUPPORT
1922 char unicode_buf[MB_CUR_MAX + 1];
1923 int unicode_idx = 0;
1924#endif
1925
1926 while (1) {
1927 /* Wait for input. TIMEOUT = -1 makes read_key wait even
1928 * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
1929 * insist on full MB_CUR_MAX buffer to declare input like
1930 * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
1931 *
1932 * Note: read_key sets errno to 0 on success.
1933 */
1934 ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
1935 if (errno) {
1936#if ENABLE_UNICODE_SUPPORT
1937 if (errno == EAGAIN && unicode_idx != 0)
1938 goto pushback;
1939#endif
1940 break;
1941 }
1942
1943#if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1944 if ((int32_t)ic == KEYCODE_CURSOR_POS
1945 && S.sent_ESC_br6n
1946 ) {
1947 S.sent_ESC_br6n = 0;
1948 if (cursor == 0) { /* otherwise it may be bogus */
1949 int col = ((ic >> 32) & 0x7fff) - 1;
1950 if (col > cmdedit_prmt_len) {
1951 cmdedit_x += (col - cmdedit_prmt_len);
1952 while (cmdedit_x >= cmdedit_termw) {
1953 cmdedit_x -= cmdedit_termw;
1954 cmdedit_y++;
1955 }
1956 }
1957 }
1958 continue;
1959 }
1960#endif
1961
1962#if ENABLE_UNICODE_SUPPORT
1963 if (unicode_status == UNICODE_ON) {
1964 wchar_t wc;
1965
1966 if ((int32_t)ic < 0) /* KEYCODE_xxx */
1967 break;
1968 // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
1969
1970 unicode_buf[unicode_idx++] = ic;
1971 unicode_buf[unicode_idx] = '\0';
1972 if (mbstowcs(&wc, unicode_buf, 1) != 1) {
1973 /* Not (yet?) a valid unicode char */
1974 if (unicode_idx < MB_CUR_MAX) {
1975 timeout = 50;
1976 continue;
1977 }
1978 pushback:
1979 /* Invalid sequence. Save all "bad bytes" except first */
1980 read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
1981# if !ENABLE_UNICODE_PRESERVE_BROKEN
1982 ic = CONFIG_SUBST_WCHAR;
1983# else
1984 ic = unicode_mark_raw_byte(unicode_buf[0]);
1985# endif
1986 } else {
1987 /* Valid unicode char, return its code */
1988 ic = wc;
1989 }
1990 }
1991#endif
1992 break;
1993 }
1994
1995 return ic;
1996}
1997
1998#if ENABLE_UNICODE_BIDI_SUPPORT
1999static int isrtl_str(void)
2000{
2001 int idx = cursor;
2002
2003 while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
2004 idx++;
2005 return unicode_bidi_isrtl(command_ps[idx]);
2006}
2007#else
2008# define isrtl_str() 0
2009#endif
2010
2011/* leave out the "vi-mode"-only case labels if vi editing isn't
2012 * configured. */
2013#define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
2014
2015/* convert uppercase ascii to equivalent control char, for readability */
2016#undef CTRL
2017#define CTRL(a) ((a) & ~0x40)
2018
2019enum {
2020 VI_CMDMODE_BIT = 0x40000000,
2021 /* 0x80000000 bit flags KEYCODE_xxx */
2022};
2023
2024#if ENABLE_FEATURE_REVERSE_SEARCH
2025/* Mimic readline Ctrl-R reverse history search.
2026 * When invoked, it shows the following prompt:
2027 * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
2028 * and typing results in search being performed:
2029 * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
2030 * Search is performed by looking at progressively older lines in history.
2031 * Ctrl-R again searches for the next match in history.
2032 * Backspace deletes last matched char.
2033 * Control keys exit search and return to normal editing (at current history line).
2034 */
2035static int32_t reverse_i_search(void)
2036{
2037 char match_buf[128]; /* for user input */
2038 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2039 const char *matched_history_line;
2040 const char *saved_prompt;
2041 int32_t ic;
2042
2043 matched_history_line = NULL;
2044 read_key_buffer[0] = 0;
2045 match_buf[0] = '\0';
2046
2047 /* Save and replace the prompt */
2048 saved_prompt = cmdedit_prompt;
2049 goto set_prompt;
2050
2051 while (1) {
2052 int h;
2053 unsigned match_buf_len = strlen(match_buf);
2054
2055 fflush_all();
2056//FIXME: correct timeout?
2057 ic = lineedit_read_key(read_key_buffer, -1);
2058
2059 switch (ic) {
2060 case CTRL('R'): /* searching for the next match */
2061 break;
2062
2063 case '\b':
2064 case '\x7f':
2065 /* Backspace */
2066 if (unicode_status == UNICODE_ON) {
2067 while (match_buf_len != 0) {
2068 uint8_t c = match_buf[--match_buf_len];
2069 if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
2070 break; /* yes */
2071 }
2072 } else {
2073 if (match_buf_len != 0)
2074 match_buf_len--;
2075 }
2076 match_buf[match_buf_len] = '\0';
2077 break;
2078
2079 default:
2080 if (ic < ' '
2081 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2082 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2083 ) {
2084 goto ret;
2085 }
2086
2087 /* Append this char */
2088#if ENABLE_UNICODE_SUPPORT
2089 if (unicode_status == UNICODE_ON) {
2090 mbstate_t mbstate = { 0 };
2091 char buf[MB_CUR_MAX + 1];
2092 int len = wcrtomb(buf, ic, &mbstate);
2093 if (len > 0) {
2094 buf[len] = '\0';
2095 if (match_buf_len + len < sizeof(match_buf))
2096 strcpy(match_buf + match_buf_len, buf);
2097 }
2098 } else
2099#endif
2100 if (match_buf_len < sizeof(match_buf) - 1) {
2101 match_buf[match_buf_len] = ic;
2102 match_buf[match_buf_len + 1] = '\0';
2103 }
2104 break;
2105 } /* switch (ic) */
2106
2107 /* Search in history for match_buf */
2108 h = state->cur_history;
2109 if (ic == CTRL('R'))
2110 h--;
2111 while (h >= 0) {
2112 if (state->history[h]) {
2113 char *match = strstr(state->history[h], match_buf);
2114 if (match) {
2115 state->cur_history = h;
2116 matched_history_line = state->history[h];
2117 command_len = load_string(matched_history_line);
2118 cursor = match - matched_history_line;
2119//FIXME: cursor position for Unicode case
2120
2121 free((char*)cmdedit_prompt);
2122 set_prompt:
2123 cmdedit_prompt = xasprintf("(reverse-i-search)'%s': ", match_buf);
2124 cmdedit_prmt_len = strlen(cmdedit_prompt);
2125 goto do_redraw;
2126 }
2127 }
2128 h--;
2129 }
2130
2131 /* Not found */
2132 match_buf[match_buf_len] = '\0';
2133 beep();
2134 continue;
2135
2136 do_redraw:
2137 redraw(cmdedit_y, command_len - cursor);
2138 } /* while (1) */
2139
2140 ret:
2141 if (matched_history_line)
2142 command_len = load_string(matched_history_line);
2143
2144 free((char*)cmdedit_prompt);
2145 cmdedit_prompt = saved_prompt;
2146 cmdedit_prmt_len = strlen(cmdedit_prompt);
2147 redraw(cmdedit_y, command_len - cursor);
2148
2149 return ic;
2150}
2151#endif
2152
2153/* maxsize must be >= 2.
2154 * Returns:
2155 * -1 on read errors or EOF, or on bare Ctrl-D,
2156 * 0 on ctrl-C (the line entered is still returned in 'command'),
2157 * >0 length of input string, including terminating '\n'
2158 */
2159int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize, int timeout)
2160{
2161 int len;
2162#if ENABLE_FEATURE_TAB_COMPLETION
2163 smallint lastWasTab = 0;
2164#endif
2165 smallint break_out = 0;
2166#if ENABLE_FEATURE_EDITING_VI
2167 smallint vi_cmdmode = 0;
2168#endif
2169 struct termios initial_settings;
2170 struct termios new_settings;
2171 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2172
2173 INIT_S();
2174
2175 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
2176 || !(initial_settings.c_lflag & ECHO)
2177 ) {
2178 /* Happens when e.g. stty -echo was run before */
2179 parse_and_put_prompt(prompt);
2180 /* fflush_all(); - done by parse_and_put_prompt */
2181 if (fgets(command, maxsize, stdin) == NULL)
2182 len = -1; /* EOF or error */
2183 else
2184 len = strlen(command);
2185 DEINIT_S();
2186 return len;
2187 }
2188
2189 init_unicode();
2190
2191// FIXME: audit & improve this
2192 if (maxsize > MAX_LINELEN)
2193 maxsize = MAX_LINELEN;
2194 S.maxsize = maxsize;
2195
2196 /* With zero flags, no other fields are ever used */
2197 state = st ? st : (line_input_t*) &const_int_0;
2198#if MAX_HISTORY > 0
2199# if ENABLE_FEATURE_EDITING_SAVEHISTORY
2200 if (state->hist_file)
2201 if (state->cnt_history == 0)
2202 load_history(state);
2203# endif
2204 if (state->flags & DO_HISTORY)
2205 state->cur_history = state->cnt_history;
2206#endif
2207
2208 /* prepare before init handlers */
2209 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
2210 command_len = 0;
2211#if ENABLE_UNICODE_SUPPORT
2212 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
2213#else
2214 command_ps = command;
2215 command[0] = '\0';
2216#endif
2217#define command command_must_not_be_used
2218
2219 new_settings = initial_settings;
2220 /* ~ICANON: unbuffered input (most c_cc[] are disabled, VMIN/VTIME are enabled) */
2221 /* ~ECHO, ~ECHONL: turn off echoing, including newline echoing */
2222 /* ~ISIG: turn off INTR (ctrl-C), QUIT, SUSP */
2223 new_settings.c_lflag &= ~(ICANON | ECHO | ECHONL | ISIG);
2224 /* reads would block only if < 1 char is available */
2225 new_settings.c_cc[VMIN] = 1;
2226 /* no timeout (reads block forever) */
2227 new_settings.c_cc[VTIME] = 0;
2228 /* Should be not needed if ISIG is off: */
2229 /* Turn off CTRL-C */
2230 /* new_settings.c_cc[VINTR] = _POSIX_VDISABLE; */
2231 tcsetattr_stdin_TCSANOW(&new_settings);
2232
2233#if ENABLE_USERNAME_OR_HOMEDIR
2234 {
2235 struct passwd *entry;
2236
2237 entry = getpwuid(geteuid());
2238 if (entry) {
2239 user_buf = xstrdup(entry->pw_name);
2240 home_pwd_buf = xstrdup(entry->pw_dir);
2241 }
2242 }
2243#endif
2244
2245#if 0
2246 for (i = 0; i <= state->max_history; i++)
2247 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
2248 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
2249#endif
2250
2251 /* Print out the command prompt, optionally ask where cursor is */
2252 parse_and_put_prompt(prompt);
2253 ask_terminal();
2254
2255 /* Install window resize handler (NB: after *all* init is complete) */
2256//FIXME: save entire sigaction!
2257 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
2258 win_changed(0); /* get initial window size */
2259
2260 read_key_buffer[0] = 0;
2261 while (1) {
2262 /*
2263 * The emacs and vi modes share much of the code in the big
2264 * command loop. Commands entered when in vi's command mode
2265 * (aka "escape mode") get an extra bit added to distinguish
2266 * them - this keeps them from being self-inserted. This
2267 * clutters the big switch a bit, but keeps all the code
2268 * in one place.
2269 */
2270 int32_t ic, ic_raw;
2271
2272 fflush_all();
2273 ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
2274
2275#if ENABLE_FEATURE_REVERSE_SEARCH
2276 again:
2277#endif
2278#if ENABLE_FEATURE_EDITING_VI
2279 newdelflag = 1;
2280 if (vi_cmdmode) {
2281 /* btw, since KEYCODE_xxx are all < 0, this doesn't
2282 * change ic if it contains one of them: */
2283 ic |= VI_CMDMODE_BIT;
2284 }
2285#endif
2286
2287 switch (ic) {
2288 case '\n':
2289 case '\r':
2290 vi_case('\n'|VI_CMDMODE_BIT:)
2291 vi_case('\r'|VI_CMDMODE_BIT:)
2292 /* Enter */
2293 goto_new_line();
2294 break_out = 1;
2295 break;
2296 case CTRL('A'):
2297 vi_case('0'|VI_CMDMODE_BIT:)
2298 /* Control-a -- Beginning of line */
2299 input_backward(cursor);
2300 break;
2301 case CTRL('B'):
2302 vi_case('h'|VI_CMDMODE_BIT:)
2303 vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
2304 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
2305 input_backward(1); /* Move back one character */
2306 break;
2307 case CTRL('E'):
2308 vi_case('$'|VI_CMDMODE_BIT:)
2309 /* Control-e -- End of line */
2310 put_till_end_and_adv_cursor();
2311 break;
2312 case CTRL('F'):
2313 vi_case('l'|VI_CMDMODE_BIT:)
2314 vi_case(' '|VI_CMDMODE_BIT:)
2315 input_forward(); /* Move forward one character */
2316 break;
2317 case '\b': /* ^H */
2318 case '\x7f': /* DEL */
2319 if (!isrtl_str())
2320 input_backspace();
2321 else
2322 input_delete(0);
2323 break;
2324 case KEYCODE_DELETE:
2325 if (!isrtl_str())
2326 input_delete(0);
2327 else
2328 input_backspace();
2329 break;
2330#if ENABLE_FEATURE_TAB_COMPLETION
2331 case '\t':
2332 input_tab(&lastWasTab);
2333 break;
2334#endif
2335 case CTRL('K'):
2336 /* Control-k -- clear to end of line */
2337 command_ps[cursor] = BB_NUL;
2338 command_len = cursor;
2339 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
2340 break;
2341 case CTRL('L'):
2342 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
2343 /* Control-l -- clear screen */
2344 printf(ESC"[H"); /* cursor to top,left */
2345 redraw(0, command_len - cursor);
2346 break;
2347#if MAX_HISTORY > 0
2348 case CTRL('N'):
2349 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
2350 vi_case('j'|VI_CMDMODE_BIT:)
2351 /* Control-n -- Get next command in history */
2352 if (get_next_history())
2353 goto rewrite_line;
2354 break;
2355 case CTRL('P'):
2356 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
2357 vi_case('k'|VI_CMDMODE_BIT:)
2358 /* Control-p -- Get previous command from history */
2359 if (get_previous_history())
2360 goto rewrite_line;
2361 break;
2362#endif
2363 case CTRL('U'):
2364 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
2365 /* Control-U -- Clear line before cursor */
2366 if (cursor) {
2367 command_len -= cursor;
2368 memmove(command_ps, command_ps + cursor,
2369 (command_len + 1) * sizeof(command_ps[0]));
2370 redraw(cmdedit_y, command_len);
2371 }
2372 break;
2373 case CTRL('W'):
2374 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
2375 /* Control-W -- Remove the last word */
2376 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
2377 input_backspace();
2378 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
2379 input_backspace();
2380 break;
2381#if ENABLE_FEATURE_REVERSE_SEARCH
2382 case CTRL('R'):
2383 ic = ic_raw = reverse_i_search();
2384 goto again;
2385#endif
2386
2387#if ENABLE_FEATURE_EDITING_VI
2388 case 'i'|VI_CMDMODE_BIT:
2389 vi_cmdmode = 0;
2390 break;
2391 case 'I'|VI_CMDMODE_BIT:
2392 input_backward(cursor);
2393 vi_cmdmode = 0;
2394 break;
2395 case 'a'|VI_CMDMODE_BIT:
2396 input_forward();
2397 vi_cmdmode = 0;
2398 break;
2399 case 'A'|VI_CMDMODE_BIT:
2400 put_till_end_and_adv_cursor();
2401 vi_cmdmode = 0;
2402 break;
2403 case 'x'|VI_CMDMODE_BIT:
2404 input_delete(1);
2405 break;
2406 case 'X'|VI_CMDMODE_BIT:
2407 if (cursor > 0) {
2408 input_backward(1);
2409 input_delete(1);
2410 }
2411 break;
2412 case 'W'|VI_CMDMODE_BIT:
2413 vi_Word_motion(1);
2414 break;
2415 case 'w'|VI_CMDMODE_BIT:
2416 vi_word_motion(1);
2417 break;
2418 case 'E'|VI_CMDMODE_BIT:
2419 vi_End_motion();
2420 break;
2421 case 'e'|VI_CMDMODE_BIT:
2422 vi_end_motion();
2423 break;
2424 case 'B'|VI_CMDMODE_BIT:
2425 vi_Back_motion();
2426 break;
2427 case 'b'|VI_CMDMODE_BIT:
2428 vi_back_motion();
2429 break;
2430 case 'C'|VI_CMDMODE_BIT:
2431 vi_cmdmode = 0;
2432 /* fall through */
2433 case 'D'|VI_CMDMODE_BIT:
2434 goto clear_to_eol;
2435
2436 case 'c'|VI_CMDMODE_BIT:
2437 vi_cmdmode = 0;
2438 /* fall through */
2439 case 'd'|VI_CMDMODE_BIT: {
2440 int nc, sc;
2441
2442 ic = lineedit_read_key(read_key_buffer, timeout);
2443 if (errno) /* error */
2444 goto return_error_indicator;
2445 if (ic == ic_raw) { /* "cc", "dd" */
2446 input_backward(cursor);
2447 goto clear_to_eol;
2448 break;
2449 }
2450
2451 sc = cursor;
2452 switch (ic) {
2453 case 'w':
2454 case 'W':
2455 case 'e':
2456 case 'E':
2457 switch (ic) {
2458 case 'w': /* "dw", "cw" */
2459 vi_word_motion(vi_cmdmode);
2460 break;
2461 case 'W': /* 'dW', 'cW' */
2462 vi_Word_motion(vi_cmdmode);
2463 break;
2464 case 'e': /* 'de', 'ce' */
2465 vi_end_motion();
2466 input_forward();
2467 break;
2468 case 'E': /* 'dE', 'cE' */
2469 vi_End_motion();
2470 input_forward();
2471 break;
2472 }
2473 nc = cursor;
2474 input_backward(cursor - sc);
2475 while (nc-- > cursor)
2476 input_delete(1);
2477 break;
2478 case 'b': /* "db", "cb" */
2479 case 'B': /* implemented as B */
2480 if (ic == 'b')
2481 vi_back_motion();
2482 else
2483 vi_Back_motion();
2484 while (sc-- > cursor)
2485 input_delete(1);
2486 break;
2487 case ' ': /* "d ", "c " */
2488 input_delete(1);
2489 break;
2490 case '$': /* "d$", "c$" */
2491 clear_to_eol:
2492 while (cursor < command_len)
2493 input_delete(1);
2494 break;
2495 }
2496 break;
2497 }
2498 case 'p'|VI_CMDMODE_BIT:
2499 input_forward();
2500 /* fallthrough */
2501 case 'P'|VI_CMDMODE_BIT:
2502 put();
2503 break;
2504 case 'r'|VI_CMDMODE_BIT:
2505//FIXME: unicode case?
2506 ic = lineedit_read_key(read_key_buffer, timeout);
2507 if (errno) /* error */
2508 goto return_error_indicator;
2509 if (ic < ' ' || ic > 255) {
2510 beep();
2511 } else {
2512 command_ps[cursor] = ic;
2513 bb_putchar(ic);
2514 bb_putchar('\b');
2515 }
2516 break;
2517 case '\x1b': /* ESC */
2518 if (state->flags & VI_MODE) {
2519 /* insert mode --> command mode */
2520 vi_cmdmode = 1;
2521 input_backward(1);
2522 }
2523 /* Handle a few ESC-<key> combinations the same way
2524 * standard readline bindings (IOW: bash) do.
2525 * Often, Alt-<key> generates ESC-<key>.
2526 */
2527 ic = lineedit_read_key(read_key_buffer, timeout);
2528 switch (ic) {
2529 //case KEYCODE_LEFT: - bash doesn't do this
2530 case 'b':
2531 ctrl_left();
2532 break;
2533 //case KEYCODE_RIGHT: - bash doesn't do this
2534 case 'f':
2535 ctrl_right();
2536 break;
2537 //case KEYCODE_DELETE: - bash doesn't do this
2538 case 'd': /* Alt-D */
2539 {
2540 /* Delete word forward */
2541 int nc, sc = cursor;
2542 ctrl_right();
2543 nc = cursor - sc;
2544 input_backward(nc);
2545 while (--nc >= 0)
2546 input_delete(1);
2547 break;
2548 }
2549 case '\b': /* Alt-Backspace(?) */
2550 case '\x7f': /* Alt-Backspace(?) */
2551 //case 'w': - bash doesn't do this
2552 {
2553 /* Delete word backward */
2554 int sc = cursor;
2555 ctrl_left();
2556 while (sc-- > cursor)
2557 input_delete(1);
2558 break;
2559 }
2560 }
2561 break;
2562#endif /* FEATURE_COMMAND_EDITING_VI */
2563
2564#if MAX_HISTORY > 0
2565 case KEYCODE_UP:
2566 if (get_previous_history())
2567 goto rewrite_line;
2568 beep();
2569 break;
2570 case KEYCODE_DOWN:
2571 if (!get_next_history())
2572 break;
2573 rewrite_line:
2574 /* Rewrite the line with the selected history item */
2575 /* change command */
2576 command_len = load_string(state->history[state->cur_history] ?
2577 state->history[state->cur_history] : "");
2578 /* redraw and go to eol (bol, in vi) */
2579 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2580 break;
2581#endif
2582 case KEYCODE_RIGHT:
2583 input_forward();
2584 break;
2585 case KEYCODE_LEFT:
2586 input_backward(1);
2587 break;
2588 case KEYCODE_CTRL_LEFT:
2589 case KEYCODE_ALT_LEFT: /* bash doesn't do it */
2590 ctrl_left();
2591 break;
2592 case KEYCODE_CTRL_RIGHT:
2593 case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
2594 ctrl_right();
2595 break;
2596 case KEYCODE_HOME:
2597 input_backward(cursor);
2598 break;
2599 case KEYCODE_END:
2600 put_till_end_and_adv_cursor();
2601 break;
2602
2603 default:
2604 if (initial_settings.c_cc[VINTR] != 0
2605 && ic_raw == initial_settings.c_cc[VINTR]
2606 ) {
2607 /* Ctrl-C (usually) - stop gathering input */
2608 goto_new_line();
2609 command_len = 0;
2610 break_out = -1; /* "do not append '\n'" */
2611 break;
2612 }
2613 if (initial_settings.c_cc[VEOF] != 0
2614 && ic_raw == initial_settings.c_cc[VEOF]
2615 ) {
2616 /* Ctrl-D (usually) - delete one character,
2617 * or exit if len=0 and no chars to delete */
2618 if (command_len == 0) {
2619 errno = 0;
2620
2621 case -1: /* error (e.g. EIO when tty is destroyed) */
2622 IF_FEATURE_EDITING_VI(return_error_indicator:)
2623 break_out = command_len = -1;
2624 break;
2625 }
2626 input_delete(0);
2627 break;
2628 }
2629// /* Control-V -- force insert of next char */
2630// if (c == CTRL('V')) {
2631// if (safe_read(STDIN_FILENO, &c, 1) < 1)
2632// goto return_error_indicator;
2633// if (c == 0) {
2634// beep();
2635// break;
2636// }
2637// }
2638 if (ic < ' '
2639 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2640 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2641 ) {
2642 /* If VI_CMDMODE_BIT is set, ic is >= 256
2643 * and vi mode ignores unexpected chars.
2644 * Otherwise, we are here if ic is a
2645 * control char or an unhandled ESC sequence,
2646 * which is also ignored.
2647 */
2648 break;
2649 }
2650 if ((int)command_len >= (maxsize - 2)) {
2651 /* Not enough space for the char and EOL */
2652 break;
2653 }
2654
2655 command_len++;
2656 if (cursor == (command_len - 1)) {
2657 /* We are at the end, append */
2658 command_ps[cursor] = ic;
2659 command_ps[cursor + 1] = BB_NUL;
2660 put_cur_glyph_and_inc_cursor();
2661 if (unicode_bidi_isrtl(ic))
2662 input_backward(1);
2663 } else {
2664 /* In the middle, insert */
2665 int sc = cursor;
2666
2667 memmove(command_ps + sc + 1, command_ps + sc,
2668 (command_len - sc) * sizeof(command_ps[0]));
2669 command_ps[sc] = ic;
2670 /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
2671 if (!isrtl_str())
2672 sc++; /* no */
2673 put_till_end_and_adv_cursor();
2674 /* to prev x pos + 1 */
2675 input_backward(cursor - sc);
2676 }
2677 break;
2678 } /* switch (ic) */
2679
2680 if (break_out)
2681 break;
2682
2683#if ENABLE_FEATURE_TAB_COMPLETION
2684 if (ic_raw != '\t')
2685 lastWasTab = 0;
2686#endif
2687 } /* while (1) */
2688
2689#if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2690 if (S.sent_ESC_br6n) {
2691 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2692 * We sent "ESC [ 6 n", but got '\n' first, and
2693 * KEYCODE_CURSOR_POS response is now buffered from terminal.
2694 * It's bad already and not much can be done with it
2695 * (it _will_ be visible for the next process to read stdin),
2696 * but without this delay it even shows up on the screen
2697 * as garbage because we restore echo settings with tcsetattr
2698 * before it comes in. UGLY!
2699 */
2700 usleep(20*1000);
2701 }
2702#endif
2703
2704/* End of bug-catching "command_must_not_be_used" trick */
2705#undef command
2706
2707#if ENABLE_UNICODE_SUPPORT
2708 command[0] = '\0';
2709 if (command_len > 0)
2710 command_len = save_string(command, maxsize - 1);
2711 free(command_ps);
2712#endif
2713
2714 if (command_len > 0)
2715 remember_in_history(command);
2716
2717 if (break_out > 0) {
2718 command[command_len++] = '\n';
2719 command[command_len] = '\0';
2720 }
2721
2722#if ENABLE_FEATURE_TAB_COMPLETION
2723 free_tab_completion_data();
2724#endif
2725
2726 /* restore initial_settings */
2727 tcsetattr_stdin_TCSANOW(&initial_settings);
2728 /* restore SIGWINCH handler */
2729 signal(SIGWINCH, previous_SIGWINCH_handler);
2730 fflush_all();
2731
2732 len = command_len;
2733 DEINIT_S();
2734
2735 return len; /* can't return command_len, DEINIT_S() destroys it */
2736}
2737
2738#else /* !FEATURE_EDITING */
2739
2740#undef read_line_input
2741int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2742{
2743 fputs(prompt, stdout);
2744 fflush_all();
2745 if (!fgets(command, maxsize, stdin))
2746 return -1;
2747 return strlen(command);
2748}
2749
2750#endif /* !FEATURE_EDITING */
2751
2752
2753/*
2754 * Testing
2755 */
2756
2757#ifdef TEST
2758
2759#include <locale.h>
2760
2761const char *applet_name = "debug stuff usage";
2762
2763int main(int argc, char **argv)
2764{
2765 char buff[MAX_LINELEN];
2766 char *prompt =
2767#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2768 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2769 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2770 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2771#else
2772 "% ";
2773#endif
2774
2775 while (1) {
2776 int l;
2777 l = read_line_input(prompt, buff);
2778 if (l <= 0 || buff[l-1] != '\n')
2779 break;
2780 buff[l-1] = '\0';
2781 printf("*** read_line_input() returned line =%s=\n", buff);
2782 }
2783 printf("*** read_line_input() detect ^D\n");
2784 return 0;
2785}
2786
2787#endif /* TEST */