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