9aab63702eebf6ab47bd65043c49ff97b37b9de8
[oweals/busybox.git] / libbb / lineedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and 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, and more will probably
20    need to be added. 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    Small bugs (simple effect):
26    - not true viewing if terminal size (x*y symbols) less
27      size (prompt + editor's line + 2 symbols)
28    - not true viewing if length prompt less terminal width
29  */
30
31 #include "libbb.h"
32
33
34 /* FIXME: obsolete CONFIG item? */
35 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
36
37
38 #ifdef TEST
39
40 #define ENABLE_FEATURE_EDITING 0
41 #define ENABLE_FEATURE_TAB_COMPLETION 0
42 #define ENABLE_FEATURE_USERNAME_COMPLETION 0
43 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
44
45 #endif  /* TEST */
46
47
48 /* Entire file (except TESTing part) sits inside this #if */
49 #if ENABLE_FEATURE_EDITING
50
51 #if ENABLE_LOCALE_SUPPORT
52 #define Isprint(c) isprint(c)
53 #else
54 #define Isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
55 #endif
56
57 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
58         (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
59 #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
60 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
61 #undef USE_FEATURE_GETUSERNAME_AND_HOMEDIR
62 #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
63 #endif
64
65 enum {
66         /* We use int16_t for positions, need to limit line len */
67         MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
68                       ? CONFIG_FEATURE_EDITING_MAX_LEN
69                       : 0x7ff0
70 };
71
72 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
73 static const char null_str[] ALIGN1 = "";
74 #endif
75
76 /* We try to minimize both static and stack usage. */
77 struct statics {
78         line_input_t *state;
79
80         volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
81         sighandler_t previous_SIGWINCH_handler;
82
83
84         int cmdedit_x;           /* real x terminal position */
85         int cmdedit_y;           /* pseudoreal y terminal position */
86         int cmdedit_prmt_len;    /* length of prompt (without colors etc) */
87
88         unsigned cursor;
89         unsigned command_len;
90         char *command_ps;
91
92         const char *cmdedit_prompt;
93 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
94         int num_ok_lines; /* = 1; */
95 #endif
96
97 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
98         char *user_buf;
99         char *home_pwd_buf; /* = (char*)null_str; */
100 #endif
101
102 #if ENABLE_FEATURE_TAB_COMPLETION
103         char **matches;
104         unsigned num_matches;
105 #endif
106
107 #if ENABLE_FEATURE_EDITING_VI
108 #define DELBUFSIZ 128
109         char *delptr;
110         smallint newdelflag;     /* whether delbuf should be reused yet */
111         char delbuf[DELBUFSIZ];  /* a place to store deleted characters */
112 #endif
113
114         /* Formerly these were big buffers on stack: */
115 #if ENABLE_FEATURE_TAB_COMPLETION
116         char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
117         char input_tab__matchBuf[MAX_LINELEN];
118         int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
119         int16_t find_match__pos_buf[MAX_LINELEN + 1];
120 #endif
121 };
122
123 /* Make it reside in writable memory, yet make compiler understand
124  * that it is not going to change. */
125 static struct statics *const ptr_to_statics __attribute__ ((section (".data")));
126
127 #define S (*ptr_to_statics)
128 #define state            (S.state           )
129 #define cmdedit_termw    (S.cmdedit_termw   )
130 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
131 #define cmdedit_x        (S.cmdedit_x       )
132 #define cmdedit_y        (S.cmdedit_y       )
133 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
134 #define cursor           (S.cursor          )
135 #define command_len      (S.command_len     )
136 #define command_ps       (S.command_ps      )
137 #define cmdedit_prompt   (S.cmdedit_prompt  )
138 #define num_ok_lines     (S.num_ok_lines    )
139 #define user_buf         (S.user_buf        )
140 #define home_pwd_buf     (S.home_pwd_buf    )
141 #define matches          (S.matches         )
142 #define num_matches      (S.num_matches     )
143 #define delptr           (S.delptr          )
144 #define newdelflag       (S.newdelflag      )
145 #define delbuf           (S.delbuf          )
146
147 #define INIT_S() do { \
148         (*(struct statics**)&ptr_to_statics) = xzalloc(sizeof(S)); \
149         cmdedit_termw = 80; \
150         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
151         USE_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
152 } while (0)
153 static void deinit_S(void)
154 {
155 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
156         /* This one is allocated only if FANCY_PROMPT is on
157          * (otherwise it points to verbatim prompt (NOT malloced) */
158         free((char*)cmdedit_prompt);
159 #endif
160 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
161         free(user_buf);
162         if (home_pwd_buf != null_str)
163                 free(home_pwd_buf);
164 #endif
165         free(ptr_to_statics);
166 }
167 #define DEINIT_S() deinit_S()
168
169 /* Put 'command_ps[cursor]', cursor++.
170  * Advance cursor on screen. If we reached right margin, scroll text up
171  * and remove terminal margin effect by printing 'next_char' */
172 static void cmdedit_set_out_char(int next_char)
173 {
174         int c = (unsigned char)command_ps[cursor];
175
176         if (c == '\0') {
177                 /* erase character after end of input string */
178                 c = ' ';
179         }
180 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
181         /* Display non-printable characters in reverse */
182         if (!Isprint(c)) {
183                 if (c >= 128)
184                         c -= 128;
185                 if (c < ' ')
186                         c += '@';
187                 if (c == 127)
188                         c = '?';
189                 printf("\033[7m%c\033[0m", c);
190         } else
191 #endif
192         {
193                 bb_putchar(c);
194         }
195         if (++cmdedit_x >= cmdedit_termw) {
196                 /* terminal is scrolled down */
197                 cmdedit_y++;
198                 cmdedit_x = 0;
199                 /* destroy "(auto)margin" */
200                 bb_putchar(next_char);
201                 bb_putchar('\b');
202         }
203 // Huh? What if command_ps[cursor] == '\0' (we are at the end already?)
204         cursor++;
205 }
206
207 /* Move to end of line (by printing all chars till the end) */
208 static void input_end(void)
209 {
210         while (cursor < command_len)
211                 cmdedit_set_out_char(' ');
212 }
213
214 /* Go to the next line */
215 static void goto_new_line(void)
216 {
217         input_end();
218         if (cmdedit_x)
219                 bb_putchar('\n');
220 }
221
222
223 static void out1str(const char *s)
224 {
225         if (s)
226                 fputs(s, stdout);
227 }
228
229 static void beep(void)
230 {
231         bb_putchar('\007');
232 }
233
234 /* Move back one character */
235 /* (optimized for slow terminals) */
236 static void input_backward(unsigned num)
237 {
238         int count_y;
239
240         if (num > cursor)
241                 num = cursor;
242         if (!num)
243                 return;
244         cursor -= num;
245
246         if (cmdedit_x >= num) {
247                 cmdedit_x -= num;
248                 if (num <= 4) {
249                         /* This is longer by 5 bytes on x86.
250                          * Also gets mysteriously
251                          * miscompiled for some ARM users.
252                          * printf(("\b\b\b\b" + 4) - num);
253                          * return;
254                          */
255                         do {
256                                 bb_putchar('\b');
257                         } while (--num);
258                         return;
259                 }
260                 printf("\033[%uD", num);
261                 return;
262         }
263
264         /* Need to go one or more lines up */
265         num -= cmdedit_x;
266         count_y = 1 + (num / cmdedit_termw);
267         cmdedit_y -= count_y;
268         cmdedit_x = cmdedit_termw * count_y - num;
269         /* go to 1st column; go up; go to correct column */
270         printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
271 }
272
273 static void put_prompt(void)
274 {
275         out1str(cmdedit_prompt);
276         cmdedit_x = cmdedit_prmt_len;
277         cursor = 0;
278 // Huh? what if cmdedit_prmt_len >= width?
279         cmdedit_y = 0;                  /* new quasireal y */
280 }
281
282 /* draw prompt, editor line, and clear tail */
283 static void redraw(int y, int back_cursor)
284 {
285         if (y > 0)                              /* up to start y */
286                 printf("\033[%dA", y);
287         bb_putchar('\r');
288         put_prompt();
289         input_end();                            /* rewrite */
290         printf("\033[J");                       /* erase after cursor */
291         input_backward(back_cursor);
292 }
293
294 /* Delete the char in front of the cursor, optionally saving it
295  * for later putback */
296 static void input_delete(int save)
297 {
298         int j = cursor;
299
300         if (j == command_len)
301                 return;
302
303 #if ENABLE_FEATURE_EDITING_VI
304         if (save) {
305                 if (newdelflag) {
306                         delptr = delbuf;
307                         newdelflag = 0;
308                 }
309                 if ((delptr - delbuf) < DELBUFSIZ)
310                         *delptr++ = command_ps[j];
311         }
312 #endif
313
314         strcpy(command_ps + j, command_ps + j + 1);
315         command_len--;
316         input_end();                    /* rewrite new line */
317         cmdedit_set_out_char(' ');      /* erase char */
318         input_backward(cursor - j);     /* back to old pos cursor */
319 }
320
321 #if ENABLE_FEATURE_EDITING_VI
322 static void put(void)
323 {
324         int ocursor;
325         int j = delptr - delbuf;
326
327         if (j == 0)
328                 return;
329         ocursor = cursor;
330         /* open hole and then fill it */
331         memmove(command_ps + cursor + j, command_ps + cursor, command_len - cursor + 1);
332         strncpy(command_ps + cursor, delbuf, j);
333         command_len += j;
334         input_end();                    /* rewrite new line */
335         input_backward(cursor - ocursor - j + 1); /* at end of new text */
336 }
337 #endif
338
339 /* Delete the char in back of the cursor */
340 static void input_backspace(void)
341 {
342         if (cursor > 0) {
343                 input_backward(1);
344                 input_delete(0);
345         }
346 }
347
348 /* Move forward one character */
349 static void input_forward(void)
350 {
351         if (cursor < command_len)
352                 cmdedit_set_out_char(command_ps[cursor + 1]);
353 }
354
355 #if ENABLE_FEATURE_TAB_COMPLETION
356
357 static void free_tab_completion_data(void)
358 {
359         if (matches) {
360                 while (num_matches)
361                         free(matches[--num_matches]);
362                 free(matches);
363                 matches = NULL;
364         }
365 }
366
367 static void add_match(char *matched)
368 {
369         int nm = num_matches;
370         int nm1 = nm + 1;
371
372         matches = xrealloc(matches, nm1 * sizeof(char *));
373         matches[nm] = matched;
374         num_matches++;
375 }
376
377 #if ENABLE_FEATURE_USERNAME_COMPLETION
378 static void username_tab_completion(char *ud, char *with_shash_flg)
379 {
380         struct passwd *entry;
381         int userlen;
382
383         ud++;                           /* ~user/... to user/... */
384         userlen = strlen(ud);
385
386         if (with_shash_flg) {           /* "~/..." or "~user/..." */
387                 char *sav_ud = ud - 1;
388                 char *home = NULL;
389
390                 if (*ud == '/') {       /* "~/..."     */
391                         home = home_pwd_buf;
392                 } else {
393                         /* "~user/..." */
394                         char *temp;
395                         temp = strchr(ud, '/');
396                         *temp = '\0';           /* ~user\0 */
397                         entry = getpwnam(ud);
398                         *temp = '/';            /* restore ~user/... */
399                         ud = temp;
400                         if (entry)
401                                 home = entry->pw_dir;
402                 }
403                 if (home) {
404                         if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
405                                 /* /home/user/... */
406                                 sprintf(sav_ud, "%s%s", home, ud);
407                         }
408                 }
409         } else {
410                 /* "~[^/]*" */
411                 /* Using _r function to avoid pulling in static buffers */
412                 char line_buff[256];
413                 struct passwd pwd;
414                 struct passwd *result;
415
416                 setpwent();
417                 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
418                         /* Null usernames should result in all users as possible completions. */
419                         if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
420                                 add_match(xasprintf("~%s/", pwd.pw_name));
421                         }
422                 }
423                 endpwent();
424         }
425 }
426 #endif  /* FEATURE_COMMAND_USERNAME_COMPLETION */
427
428 enum {
429         FIND_EXE_ONLY = 0,
430         FIND_DIR_ONLY = 1,
431         FIND_FILE_ONLY = 2,
432 };
433
434 static int path_parse(char ***p, int flags)
435 {
436         int npth;
437         const char *pth;
438         char *tmp;
439         char **res;
440
441         /* if not setenv PATH variable, to search cur dir "." */
442         if (flags != FIND_EXE_ONLY)
443                 return 1;
444
445         if (state->flags & WITH_PATH_LOOKUP)
446                 pth = state->path_lookup;
447         else
448                 pth = getenv("PATH");
449         /* PATH=<empty> or PATH=:<empty> */
450         if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
451                 return 1;
452
453         tmp = (char*)pth;
454         npth = 1; /* path component count */
455         while (1) {
456                 tmp = strchr(tmp, ':');
457                 if (!tmp)
458                         break;
459                 if (*++tmp == '\0')
460                         break;  /* :<empty> */
461                 npth++;
462         }
463
464         res = xmalloc(npth * sizeof(char*));
465         res[0] = tmp = xstrdup(pth);
466         npth = 1;
467         while (1) {
468                 tmp = strchr(tmp, ':');
469                 if (!tmp)
470                         break;
471                 *tmp++ = '\0'; /* ':' -> '\0' */
472                 if (*tmp == '\0')
473                         break; /* :<empty> */
474                 res[npth++] = tmp;
475         }
476         *p = res;
477         return npth;
478 }
479
480 static void exe_n_cwd_tab_completion(char *command, int type)
481 {
482         DIR *dir;
483         struct dirent *next;
484         struct stat st;
485         char *path1[1];
486         char **paths = path1;
487         int npaths;
488         int i;
489         char *found;
490         char *pfind = strrchr(command, '/');
491 /*      char dirbuf[MAX_LINELEN]; */
492 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
493
494         npaths = 1;
495         path1[0] = (char*)".";
496
497         if (pfind == NULL) {
498                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
499                 npaths = path_parse(&paths, type);
500                 pfind = command;
501         } else {
502                 /* dirbuf = ".../.../.../" */
503                 safe_strncpy(dirbuf, command, (pfind - command) + 2);
504 #if ENABLE_FEATURE_USERNAME_COMPLETION
505                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
506                         username_tab_completion(dirbuf, dirbuf);
507 #endif
508                 paths[0] = dirbuf;
509                 /* point to 'l' in "..../last_component" */
510                 pfind++;
511         }
512
513         for (i = 0; i < npaths; i++) {
514                 dir = opendir(paths[i]);
515                 if (!dir)                       /* Don't print an error */
516                         continue;
517
518                 while ((next = readdir(dir)) != NULL) {
519                         int len1;
520                         const char *str_found = next->d_name;
521
522                         /* matched? */
523                         if (strncmp(str_found, pfind, strlen(pfind)))
524                                 continue;
525                         /* not see .name without .match */
526                         if (*str_found == '.' && *pfind == 0) {
527                                 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
528                                         continue;
529                                 str_found = ""; /* only "/" */
530                         }
531                         found = concat_path_file(paths[i], str_found);
532                         /* hmm, remover in progress? */
533                         if (lstat(found, &st) < 0)
534                                 goto cont;
535                         /* find with dirs? */
536                         if (paths[i] != dirbuf)
537                                 strcpy(found, next->d_name);    /* only name */
538
539                         len1 = strlen(found);
540                         found = xrealloc(found, len1 + 2);
541                         found[len1] = '\0';
542                         found[len1+1] = '\0';
543
544                         if (S_ISDIR(st.st_mode)) {
545                                 /* name is directory      */
546                                 if (found[len1-1] != '/') {
547                                         found[len1] = '/';
548                                 }
549                         } else {
550                                 /* not put found file if search only dirs for cd */
551                                 if (type == FIND_DIR_ONLY)
552                                         goto cont;
553                         }
554                         /* Add it to the list */
555                         add_match(found);
556                         continue;
557  cont:
558                         free(found);
559                 }
560                 closedir(dir);
561         }
562         if (paths != path1) {
563                 free(paths[0]);                 /* allocated memory only in first member */
564                 free(paths);
565         }
566 #undef dirbuf
567 }
568
569 #define QUOT (UCHAR_MAX+1)
570
571 #define collapse_pos(is, in) do { \
572         memmove(int_buf+(is), int_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
573         memmove(pos_buf+(is), pos_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
574 } while (0)
575
576 static int find_match(char *matchBuf, int *len_with_quotes)
577 {
578         int i, j;
579         int command_mode;
580         int c, c2;
581 /*      int16_t int_buf[MAX_LINELEN + 1]; */
582 /*      int16_t pos_buf[MAX_LINELEN + 1]; */
583 #define int_buf (S.find_match__int_buf)
584 #define pos_buf (S.find_match__pos_buf)
585
586         /* set to integer dimension characters and own positions */
587         for (i = 0;; i++) {
588                 int_buf[i] = (unsigned char)matchBuf[i];
589                 if (int_buf[i] == 0) {
590                         pos_buf[i] = -1;        /* indicator end line */
591                         break;
592                 }
593                 pos_buf[i] = i;
594         }
595
596         /* mask \+symbol and convert '\t' to ' ' */
597         for (i = j = 0; matchBuf[i]; i++, j++)
598                 if (matchBuf[i] == '\\') {
599                         collapse_pos(j, j + 1);
600                         int_buf[j] |= QUOT;
601                         i++;
602 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
603                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
604                                 int_buf[j] = ' ' | QUOT;
605 #endif
606                 }
607 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
608                 else if (matchBuf[i] == '\t')
609                         int_buf[j] = ' ';
610 #endif
611
612         /* mask "symbols" or 'symbols' */
613         c2 = 0;
614         for (i = 0; int_buf[i]; i++) {
615                 c = int_buf[i];
616                 if (c == '\'' || c == '"') {
617                         if (c2 == 0)
618                                 c2 = c;
619                         else {
620                                 if (c == c2)
621                                         c2 = 0;
622                                 else
623                                         int_buf[i] |= QUOT;
624                         }
625                 } else if (c2 != 0 && c != '$')
626                         int_buf[i] |= QUOT;
627         }
628
629         /* skip commands with arguments if line has commands delimiters */
630         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
631         for (i = 0; int_buf[i]; i++) {
632                 c = int_buf[i];
633                 c2 = int_buf[i + 1];
634                 j = i ? int_buf[i - 1] : -1;
635                 command_mode = 0;
636                 if (c == ';' || c == '&' || c == '|') {
637                         command_mode = 1 + (c == c2);
638                         if (c == '&') {
639                                 if (j == '>' || j == '<')
640                                         command_mode = 0;
641                         } else if (c == '|' && j == '>')
642                                 command_mode = 0;
643                 }
644                 if (command_mode) {
645                         collapse_pos(0, i + command_mode);
646                         i = -1;                         /* hack incremet */
647                 }
648         }
649         /* collapse `command...` */
650         for (i = 0; int_buf[i]; i++)
651                 if (int_buf[i] == '`') {
652                         for (j = i + 1; int_buf[j]; j++)
653                                 if (int_buf[j] == '`') {
654                                         collapse_pos(i, j + 1);
655                                         j = 0;
656                                         break;
657                                 }
658                         if (j) {
659                                 /* not found close ` - command mode, collapse all previous */
660                                 collapse_pos(0, i + 1);
661                                 break;
662                         } else
663                                 i--;                    /* hack incremet */
664                 }
665
666         /* collapse (command...(command...)...) or {command...{command...}...} */
667         c = 0;                                          /* "recursive" level */
668         c2 = 0;
669         for (i = 0; int_buf[i]; i++)
670                 if (int_buf[i] == '(' || int_buf[i] == '{') {
671                         if (int_buf[i] == '(')
672                                 c++;
673                         else
674                                 c2++;
675                         collapse_pos(0, i + 1);
676                         i = -1;                         /* hack incremet */
677                 }
678         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
679                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
680                         if (int_buf[i] == ')')
681                                 c--;
682                         else
683                                 c2--;
684                         collapse_pos(0, i + 1);
685                         i = -1;                         /* hack incremet */
686                 }
687
688         /* skip first not quote space */
689         for (i = 0; int_buf[i]; i++)
690                 if (int_buf[i] != ' ')
691                         break;
692         if (i)
693                 collapse_pos(0, i);
694
695         /* set find mode for completion */
696         command_mode = FIND_EXE_ONLY;
697         for (i = 0; int_buf[i]; i++)
698                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
699                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
700                          && matchBuf[pos_buf[0]] == 'c'
701                          && matchBuf[pos_buf[1]] == 'd'
702                         ) {
703                                 command_mode = FIND_DIR_ONLY;
704                         } else {
705                                 command_mode = FIND_FILE_ONLY;
706                                 break;
707                         }
708                 }
709         for (i = 0; int_buf[i]; i++)
710                 /* "strlen" */;
711         /* find last word */
712         for (--i; i >= 0; i--) {
713                 c = int_buf[i];
714                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
715                         collapse_pos(0, i + 1);
716                         break;
717                 }
718         }
719         /* skip first not quoted '\'' or '"' */
720         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
721                 /*skip*/;
722         /* collapse quote or unquote // or /~ */
723         while ((int_buf[i] & ~QUOT) == '/'
724          && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
725         ) {
726                 i++;
727         }
728
729         /* set only match and destroy quotes */
730         j = 0;
731         for (c = 0; pos_buf[i] >= 0; i++) {
732                 matchBuf[c++] = matchBuf[pos_buf[i]];
733                 j = pos_buf[i] + 1;
734         }
735         matchBuf[c] = '\0';
736         /* old length matchBuf with quotes symbols */
737         *len_with_quotes = j ? j - pos_buf[0] : 0;
738
739         return command_mode;
740 #undef int_buf
741 #undef pos_buf
742 }
743
744 /*
745  * display by column (original idea from ls applet,
746  * very optimized by me :)
747  */
748 static void showfiles(void)
749 {
750         int ncols, row;
751         int column_width = 0;
752         int nfiles = num_matches;
753         int nrows = nfiles;
754         int l;
755
756         /* find the longest file name-  use that as the column width */
757         for (row = 0; row < nrows; row++) {
758                 l = strlen(matches[row]);
759                 if (column_width < l)
760                         column_width = l;
761         }
762         column_width += 2;              /* min space for columns */
763         ncols = cmdedit_termw / column_width;
764
765         if (ncols > 1) {
766                 nrows /= ncols;
767                 if (nfiles % ncols)
768                         nrows++;        /* round up fractionals */
769         } else {
770                 ncols = 1;
771         }
772         for (row = 0; row < nrows; row++) {
773                 int n = row;
774                 int nc;
775
776                 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
777                         printf("%s%-*s", matches[n],
778                                 (int)(column_width - strlen(matches[n])), "");
779                 }
780                 puts(matches[n]);
781         }
782 }
783
784 static char *add_quote_for_spec_chars(char *found)
785 {
786         int l = 0;
787         char *s = xmalloc((strlen(found) + 1) * 2);
788
789         while (*found) {
790                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
791                         s[l++] = '\\';
792                 s[l++] = *found++;
793         }
794         s[l] = 0;
795         return s;
796 }
797
798 static int match_compare(const void *a, const void *b)
799 {
800         return strcmp(*(char**)a, *(char**)b);
801 }
802
803 /* Do TAB completion */
804 static void input_tab(smallint *lastWasTab)
805 {
806         if (!(state->flags & TAB_COMPLETION))
807                 return;
808
809         if (!*lastWasTab) {
810                 char *tmp, *tmp1;
811                 int len_found;
812 /*              char matchBuf[MAX_LINELEN]; */
813 #define matchBuf (S.input_tab__matchBuf)
814                 int find_type;
815                 int recalc_pos;
816
817                 *lastWasTab = TRUE;             /* flop trigger */
818
819                 /* Make a local copy of the string -- up
820                  * to the position of the cursor */
821                 tmp = strncpy(matchBuf, command_ps, cursor);
822                 tmp[cursor] = '\0';
823
824                 find_type = find_match(matchBuf, &recalc_pos);
825
826                 /* Free up any memory already allocated */
827                 free_tab_completion_data();
828
829 #if ENABLE_FEATURE_USERNAME_COMPLETION
830                 /* If the word starts with `~' and there is no slash in the word,
831                  * then try completing this word as a username. */
832                 if (state->flags & USERNAME_COMPLETION)
833                         if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
834                                 username_tab_completion(matchBuf, NULL);
835 #endif
836                 /* Try to match any executable in our path and everything
837                  * in the current working directory */
838                 if (!matches)
839                         exe_n_cwd_tab_completion(matchBuf, find_type);
840                 /* Sort, then remove any duplicates found */
841                 if (matches) {
842                         int i, n = 0;
843                         qsort(matches, num_matches, sizeof(char*), match_compare);
844                         for (i = 0; i < num_matches - 1; ++i) {
845                                 if (matches[i] && matches[i+1]) { /* paranoia */
846                                         if (strcmp(matches[i], matches[i+1]) == 0) {
847                                                 free(matches[i]);
848                                                 matches[i] = NULL; /* paranoia */
849                                         } else {
850                                                 matches[n++] = matches[i];
851                                         }
852                                 }
853                         }
854                         matches[n] = matches[i];
855                         num_matches = n + 1;
856                 }
857                 /* Did we find exactly one match? */
858                 if (!matches || num_matches > 1) {
859                         beep();
860                         if (!matches)
861                                 return;         /* not found */
862                         /* find minimal match */
863                         tmp1 = xstrdup(matches[0]);
864                         for (tmp = tmp1; *tmp; tmp++)
865                                 for (len_found = 1; len_found < num_matches; len_found++)
866                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
867                                                 *tmp = '\0';
868                                                 break;
869                                         }
870                         if (*tmp1 == '\0') {        /* have unique */
871                                 free(tmp1);
872                                 return;
873                         }
874                         tmp = add_quote_for_spec_chars(tmp1);
875                         free(tmp1);
876                 } else {                        /* one match */
877                         tmp = add_quote_for_spec_chars(matches[0]);
878                         /* for next completion current found */
879                         *lastWasTab = FALSE;
880
881                         len_found = strlen(tmp);
882                         if (tmp[len_found-1] != '/') {
883                                 tmp[len_found] = ' ';
884                                 tmp[len_found+1] = '\0';
885                         }
886                 }
887                 len_found = strlen(tmp);
888                 /* have space to placed match? */
889                 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
890                         /* before word for match   */
891                         command_ps[cursor - recalc_pos] = '\0';
892                         /* save   tail line        */
893                         strcpy(matchBuf, command_ps + cursor);
894                         /* add    match            */
895                         strcat(command_ps, tmp);
896                         /* add    tail             */
897                         strcat(command_ps, matchBuf);
898                         /* back to begin word for match    */
899                         input_backward(recalc_pos);
900                         /* new pos                         */
901                         recalc_pos = cursor + len_found;
902                         /* new len                         */
903                         command_len = strlen(command_ps);
904                         /* write out the matched command   */
905                         redraw(cmdedit_y, command_len - recalc_pos);
906                 }
907                 free(tmp);
908 #undef matchBuf
909         } else {
910                 /* Ok -- the last char was a TAB.  Since they
911                  * just hit TAB again, print a list of all the
912                  * available choices... */
913                 if (matches && num_matches > 0) {
914                         int sav_cursor = cursor;        /* change goto_new_line() */
915
916                         /* Go to the next line */
917                         goto_new_line();
918                         showfiles();
919                         redraw(0, command_len - sav_cursor);
920                 }
921         }
922 }
923
924 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
925
926
927 #if MAX_HISTORY > 0
928
929 /* state->flags is already checked to be nonzero */
930 static void get_previous_history(void)
931 {
932         if (command_ps[0] != '\0' || state->history[state->cur_history] == NULL) {
933                 free(state->history[state->cur_history]);
934                 state->history[state->cur_history] = xstrdup(command_ps);
935         }
936         state->cur_history--;
937 }
938
939 static int get_next_history(void)
940 {
941         if (state->flags & DO_HISTORY) {
942                 int ch = state->cur_history;
943                 if (ch < state->cnt_history) {
944                         get_previous_history(); /* save the current history line */
945                         state->cur_history = ch + 1;
946                         return state->cur_history;
947                 }
948         }
949         beep();
950         return 0;
951 }
952
953 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
954 /* state->flags is already checked to be nonzero */
955 static void load_history(const char *fromfile)
956 {
957         FILE *fp;
958         int hi;
959
960         /* cleanup old */
961         for (hi = state->cnt_history; hi > 0;) {
962                 hi--;
963                 free(state->history[hi]);
964         }
965
966         fp = fopen(fromfile, "r");
967         if (fp) {
968                 for (hi = 0; hi < MAX_HISTORY;) {
969                         char *hl = xmalloc_getline(fp);
970                         int l;
971
972                         if (!hl)
973                                 break;
974                         l = strlen(hl);
975                         if (l >= MAX_LINELEN)
976                                 hl[MAX_LINELEN-1] = '\0';
977                         if (l == 0 || hl[0] == ' ') {
978                                 free(hl);
979                                 continue;
980                         }
981                         state->history[hi++] = hl;
982                 }
983                 fclose(fp);
984         }
985         state->cur_history = state->cnt_history = hi;
986 }
987
988 /* state->flags is already checked to be nonzero */
989 static void save_history(const char *tofile)
990 {
991         FILE *fp;
992
993         fp = fopen(tofile, "w");
994         if (fp) {
995                 int i;
996
997                 for (i = 0; i < state->cnt_history; i++) {
998                         fprintf(fp, "%s\n", state->history[i]);
999                 }
1000                 fclose(fp);
1001         }
1002 }
1003 #else
1004 #define load_history(a) ((void)0)
1005 #define save_history(a) ((void)0)
1006 #endif /* FEATURE_COMMAND_SAVEHISTORY */
1007
1008 static void remember_in_history(const char *str)
1009 {
1010         int i;
1011
1012         if (!(state->flags & DO_HISTORY))
1013                 return;
1014
1015         i = state->cnt_history;
1016         free(state->history[MAX_HISTORY]);
1017         state->history[MAX_HISTORY] = NULL;
1018         /* After max history, remove the oldest command */
1019         if (i >= MAX_HISTORY) {
1020                 free(state->history[0]);
1021                 for (i = 0; i < MAX_HISTORY-1; i++)
1022                         state->history[i] = state->history[i+1];
1023         }
1024 // Maybe "if (!i || strcmp(history[i-1], command) != 0) ..."
1025 // (i.e. do not save dups?)
1026         state->history[i++] = xstrdup(str);
1027         state->cur_history = i;
1028         state->cnt_history = i;
1029 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1030         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1031                 save_history(state->hist_file);
1032 #endif
1033         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1034 }
1035
1036 #else /* MAX_HISTORY == 0 */
1037 #define remember_in_history(a) ((void)0)
1038 #endif /* MAX_HISTORY */
1039
1040
1041 /*
1042  * This function is used to grab a character buffer
1043  * from the input file descriptor and allows you to
1044  * a string with full command editing (sort of like
1045  * a mini readline).
1046  *
1047  * The following standard commands are not implemented:
1048  * ESC-b -- Move back one word
1049  * ESC-f -- Move forward one word
1050  * ESC-d -- Delete back one word
1051  * ESC-h -- Delete forward one word
1052  * CTL-t -- Transpose two characters
1053  *
1054  * Minimalist vi-style command line editing available if configured.
1055  * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1056  */
1057
1058 #if ENABLE_FEATURE_EDITING_VI
1059 static void
1060 vi_Word_motion(char *command, int eat)
1061 {
1062         while (cursor < command_len && !isspace(command[cursor]))
1063                 input_forward();
1064         if (eat) while (cursor < command_len && isspace(command[cursor]))
1065                 input_forward();
1066 }
1067
1068 static void
1069 vi_word_motion(char *command, int eat)
1070 {
1071         if (isalnum(command[cursor]) || command[cursor] == '_') {
1072                 while (cursor < command_len
1073                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1074                         input_forward();
1075         } else if (ispunct(command[cursor])) {
1076                 while (cursor < command_len && ispunct(command[cursor+1]))
1077                         input_forward();
1078         }
1079
1080         if (cursor < command_len)
1081                 input_forward();
1082
1083         if (eat && cursor < command_len && isspace(command[cursor]))
1084                 while (cursor < command_len && isspace(command[cursor]))
1085                         input_forward();
1086 }
1087
1088 static void
1089 vi_End_motion(char *command)
1090 {
1091         input_forward();
1092         while (cursor < command_len && isspace(command[cursor]))
1093                 input_forward();
1094         while (cursor < command_len-1 && !isspace(command[cursor+1]))
1095                 input_forward();
1096 }
1097
1098 static void
1099 vi_end_motion(char *command)
1100 {
1101         if (cursor >= command_len-1)
1102                 return;
1103         input_forward();
1104         while (cursor < command_len-1 && isspace(command[cursor]))
1105                 input_forward();
1106         if (cursor >= command_len-1)
1107                 return;
1108         if (isalnum(command[cursor]) || command[cursor] == '_') {
1109                 while (cursor < command_len-1
1110                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_')
1111                 ) {
1112                         input_forward();
1113                 }
1114         } else if (ispunct(command[cursor])) {
1115                 while (cursor < command_len-1 && ispunct(command[cursor+1]))
1116                         input_forward();
1117         }
1118 }
1119
1120 static void
1121 vi_Back_motion(char *command)
1122 {
1123         while (cursor > 0 && isspace(command[cursor-1]))
1124                 input_backward(1);
1125         while (cursor > 0 && !isspace(command[cursor-1]))
1126                 input_backward(1);
1127 }
1128
1129 static void
1130 vi_back_motion(char *command)
1131 {
1132         if (cursor <= 0)
1133                 return;
1134         input_backward(1);
1135         while (cursor > 0 && isspace(command[cursor]))
1136                 input_backward(1);
1137         if (cursor <= 0)
1138                 return;
1139         if (isalnum(command[cursor]) || command[cursor] == '_') {
1140                 while (cursor > 0
1141                  && (isalnum(command[cursor-1]) || command[cursor-1] == '_')
1142                 ) {
1143                         input_backward(1);
1144                 }
1145         } else if (ispunct(command[cursor])) {
1146                 while (cursor > 0 && ispunct(command[cursor-1]))
1147                         input_backward(1);
1148         }
1149 }
1150 #endif
1151
1152
1153 /*
1154  * read_line_input and its helpers
1155  */
1156
1157 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1158 static void parse_and_put_prompt(const char *prmt_ptr)
1159 {
1160         cmdedit_prompt = prmt_ptr;
1161         cmdedit_prmt_len = strlen(prmt_ptr);
1162         put_prompt();
1163 }
1164 #else
1165 static void parse_and_put_prompt(const char *prmt_ptr)
1166 {
1167         int prmt_len = 0;
1168         size_t cur_prmt_len = 0;
1169         char flg_not_length = '[';
1170         char *prmt_mem_ptr = xzalloc(1);
1171         char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1172         char cbuf[2];
1173         char c;
1174         char *pbuf;
1175
1176         cmdedit_prmt_len = 0;
1177
1178         if (!cwd_buf) {
1179                 cwd_buf = (char *)bb_msg_unknown;
1180         }
1181
1182         cbuf[1] = '\0'; /* never changes */
1183
1184         while (*prmt_ptr) {
1185                 char *free_me = NULL;
1186
1187                 pbuf = cbuf;
1188                 c = *prmt_ptr++;
1189                 if (c == '\\') {
1190                         const char *cp = prmt_ptr;
1191                         int l;
1192
1193                         c = bb_process_escape_sequence(&prmt_ptr);
1194                         if (prmt_ptr == cp) {
1195                                 if (*cp == '\0')
1196                                         break;
1197                                 c = *prmt_ptr++;
1198
1199                                 switch (c) {
1200 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1201                                 case 'u':
1202                                         pbuf = user_buf ? user_buf : (char*)"";
1203                                         break;
1204 #endif
1205                                 case 'h':
1206                                         pbuf = free_me = xzalloc(256);
1207                                         if (gethostname(pbuf, 255) < 0) {
1208                                                 pbuf[0] = '?';
1209                                                 pbuf[1] = '\0';
1210                                         }
1211                                         *strchrnul(pbuf, '.') = '\0';
1212                                         break;
1213                                 case '$':
1214                                         c = (geteuid() == 0 ? '#' : '$');
1215                                         break;
1216 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1217                                 case 'w':
1218                                         /* /home/user[/something] -> ~[/something] */
1219                                         pbuf = cwd_buf;
1220                                         l = strlen(home_pwd_buf);
1221                                         if (l != 0
1222                                          && strncmp(home_pwd_buf, cwd_buf, l) == 0
1223                                          && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1224                                          && strlen(cwd_buf + l) < PATH_MAX
1225                                         ) {
1226                                                 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1227                                         }
1228                                         break;
1229 #endif
1230                                 case 'W':
1231                                         pbuf = cwd_buf;
1232                                         cp = strrchr(pbuf, '/');
1233                                         if (cp != NULL && cp != pbuf)
1234                                                 pbuf += (cp-pbuf) + 1;
1235                                         break;
1236                                 case '!':
1237                                         pbuf = free_me = xasprintf("%d", num_ok_lines);
1238                                         break;
1239                                 case 'e': case 'E':     /* \e \E = \033 */
1240                                         c = '\033';
1241                                         break;
1242                                 case 'x': case 'X': {
1243                                         char buf2[4];
1244                                         for (l = 0; l < 3;) {
1245                                                 unsigned h;
1246                                                 buf2[l++] = *prmt_ptr;
1247                                                 buf2[l] = '\0';
1248                                                 h = strtoul(buf2, &pbuf, 16);
1249                                                 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1250                                                         buf2[--l] = '\0';
1251                                                         break;
1252                                                 }
1253                                                 prmt_ptr++;
1254                                         }
1255                                         c = (char)strtoul(buf2, NULL, 16);
1256                                         if (c == 0)
1257                                                 c = '?';
1258                                         pbuf = cbuf;
1259                                         break;
1260                                 }
1261                                 case '[': case ']':
1262                                         if (c == flg_not_length) {
1263                                                 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1264                                                 continue;
1265                                         }
1266                                         break;
1267                                 } /* switch */
1268                         } /* if */
1269                 } /* if */
1270                 cbuf[0] = c;
1271                 cur_prmt_len = strlen(pbuf);
1272                 prmt_len += cur_prmt_len;
1273                 if (flg_not_length != ']')
1274                         cmdedit_prmt_len += cur_prmt_len;
1275                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1276                 free(free_me);
1277         } /* while */
1278
1279         if (cwd_buf != (char *)bb_msg_unknown)
1280                 free(cwd_buf);
1281         cmdedit_prompt = prmt_mem_ptr;
1282         put_prompt();
1283 }
1284 #endif
1285
1286 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1287 {
1288         cmdedit_termw = w;
1289         if (redraw_flg) {
1290                 /* new y for current cursor */
1291                 int new_y = (cursor + cmdedit_prmt_len) / w;
1292                 /* redraw */
1293                 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1294                 fflush(stdout);
1295         }
1296 }
1297
1298 static void win_changed(int nsig)
1299 {
1300         int width;
1301         get_terminal_width_height(0, &width, NULL);
1302         cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1303         if (nsig == SIGWINCH)
1304                 signal(SIGWINCH, win_changed); /* rearm ourself */
1305 }
1306
1307 /*
1308  * The emacs and vi modes share much of the code in the big
1309  * command loop.  Commands entered when in vi's command mode (aka
1310  * "escape mode") get an extra bit added to distinguish them --
1311  * this keeps them from being self-inserted.  This clutters the
1312  * big switch a bit, but keeps all the code in one place.
1313  */
1314
1315 #define vbit 0x100
1316
1317 /* leave out the "vi-mode"-only case labels if vi editing isn't
1318  * configured. */
1319 #define vi_case(caselabel) USE_FEATURE_EDITING(case caselabel)
1320
1321 /* convert uppercase ascii to equivalent control char, for readability */
1322 #undef CTRL
1323 #define CTRL(a) ((a) & ~0x40)
1324
1325 /* Returns:
1326  * -1 on read errors or EOF, or on bare Ctrl-D,
1327  * 0  on ctrl-C (the line entered is still returned in 'command'),
1328  * >0 length of input string, including terminating '\n'
1329  */
1330 int read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1331 {
1332 #if ENABLE_FEATURE_TAB_COMPLETION
1333         smallint lastWasTab = FALSE;
1334 #endif
1335         unsigned int ic;
1336         unsigned char c;
1337         smallint break_out = 0;
1338 #if ENABLE_FEATURE_EDITING_VI
1339         smallint vi_cmdmode = 0;
1340         smalluint prevc;
1341 #endif
1342         struct termios initial_settings;
1343         struct termios new_settings;
1344
1345         INIT_S();
1346
1347         if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1348          || !(initial_settings.c_lflag & ECHO)
1349         ) {
1350                 /* Happens when e.g. stty -echo was run before */
1351                 int len;
1352                 parse_and_put_prompt(prompt);
1353                 fflush(stdout);
1354                 if (fgets(command, maxsize, stdin) == NULL)
1355                         len = -1; /* EOF or error */
1356                 else
1357                         len = strlen(command);
1358                 DEINIT_S();
1359                 return len;
1360         }
1361
1362 // FIXME: audit & improve this
1363         if (maxsize > MAX_LINELEN)
1364                 maxsize = MAX_LINELEN;
1365
1366         /* With null flags, no other fields are ever used */
1367         state = st ? st : (line_input_t*) &const_int_0;
1368 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1369         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1370                 load_history(state->hist_file);
1371 #endif
1372
1373         /* prepare before init handlers */
1374         cmdedit_y = 0;  /* quasireal y, not true if line > xt*yt */
1375         command_len = 0;
1376         command_ps = command;
1377         command[0] = '\0';
1378
1379         new_settings = initial_settings;
1380         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1381         /* Turn off echoing and CTRL-C, so we can trap it */
1382         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1383         /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1384         new_settings.c_cc[VMIN] = 1;
1385         new_settings.c_cc[VTIME] = 0;
1386         /* Turn off CTRL-C, so we can trap it */
1387 #ifndef _POSIX_VDISABLE
1388 #define _POSIX_VDISABLE '\0'
1389 #endif
1390         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1391         tcsetattr(STDIN_FILENO, TCSANOW, &new_settings);
1392
1393         /* Now initialize things */
1394         previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1395         win_changed(0); /* do initial resizing */
1396 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1397         {
1398                 struct passwd *entry;
1399
1400                 entry = getpwuid(geteuid());
1401                 if (entry) {
1402                         user_buf = xstrdup(entry->pw_name);
1403                         home_pwd_buf = xstrdup(entry->pw_dir);
1404                 }
1405         }
1406 #endif
1407         /* Print out the command prompt */
1408         parse_and_put_prompt(prompt);
1409
1410         while (1) {
1411                 fflush(NULL);
1412
1413                 if (nonblock_safe_read(STDIN_FILENO, &c, 1) < 1) {
1414                         /* if we can't read input then exit */
1415                         goto prepare_to_die;
1416                 }
1417
1418                 ic = c;
1419
1420 #if ENABLE_FEATURE_EDITING_VI
1421                 newdelflag = 1;
1422                 if (vi_cmdmode)
1423                         ic |= vbit;
1424 #endif
1425                 switch (ic) {
1426                 case '\n':
1427                 case '\r':
1428                 vi_case('\n'|vbit:)
1429                 vi_case('\r'|vbit:)
1430                         /* Enter */
1431                         goto_new_line();
1432                         break_out = 1;
1433                         break;
1434                 case CTRL('A'):
1435                 vi_case('0'|vbit:)
1436                         /* Control-a -- Beginning of line */
1437                         input_backward(cursor);
1438                         break;
1439                 case CTRL('B'):
1440                 vi_case('h'|vbit:)
1441                 vi_case('\b'|vbit:)
1442                 vi_case('\x7f'|vbit:) /* DEL */
1443                         /* Control-b -- Move back one character */
1444                         input_backward(1);
1445                         break;
1446                 case CTRL('C'):
1447                 vi_case(CTRL('C')|vbit:)
1448                         /* Control-c -- stop gathering input */
1449                         goto_new_line();
1450                         command_len = 0;
1451                         break_out = -1; /* "do not append '\n'" */
1452                         break;
1453                 case CTRL('D'):
1454                         /* Control-d -- Delete one character, or exit
1455                          * if the len=0 and no chars to delete */
1456                         if (command_len == 0) {
1457                                 errno = 0;
1458  prepare_to_die:
1459                                 /* to control stopped jobs */
1460                                 break_out = command_len = -1;
1461                                 break;
1462                         }
1463                         input_delete(0);
1464                         break;
1465
1466                 case CTRL('E'):
1467                 vi_case('$'|vbit:)
1468                         /* Control-e -- End of line */
1469                         input_end();
1470                         break;
1471                 case CTRL('F'):
1472                 vi_case('l'|vbit:)
1473                 vi_case(' '|vbit:)
1474                         /* Control-f -- Move forward one character */
1475                         input_forward();
1476                         break;
1477
1478                 case '\b':
1479                 case '\x7f': /* DEL */
1480                         /* Control-h and DEL */
1481                         input_backspace();
1482                         break;
1483
1484 #if ENABLE_FEATURE_TAB_COMPLETION
1485                 case '\t':
1486                         input_tab(&lastWasTab);
1487                         break;
1488 #endif
1489
1490                 case CTRL('K'):
1491                         /* Control-k -- clear to end of line */
1492                         command[cursor] = 0;
1493                         command_len = cursor;
1494                         printf("\033[J");
1495                         break;
1496                 case CTRL('L'):
1497                 vi_case(CTRL('L')|vbit:)
1498                         /* Control-l -- clear screen */
1499                         printf("\033[H");
1500                         redraw(0, command_len - cursor);
1501                         break;
1502
1503 #if MAX_HISTORY > 0
1504                 case CTRL('N'):
1505                 vi_case(CTRL('N')|vbit:)
1506                 vi_case('j'|vbit:)
1507                         /* Control-n -- Get next command in history */
1508                         if (get_next_history())
1509                                 goto rewrite_line;
1510                         break;
1511                 case CTRL('P'):
1512                 vi_case(CTRL('P')|vbit:)
1513                 vi_case('k'|vbit:)
1514                         /* Control-p -- Get previous command from history */
1515                         if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1516                                 get_previous_history();
1517                                 goto rewrite_line;
1518                         }
1519                         beep();
1520                         break;
1521 #endif
1522
1523                 case CTRL('U'):
1524                 vi_case(CTRL('U')|vbit:)
1525                         /* Control-U -- Clear line before cursor */
1526                         if (cursor) {
1527                                 strcpy(command, command + cursor);
1528                                 command_len -= cursor;
1529                                 redraw(cmdedit_y, command_len);
1530                         }
1531                         break;
1532                 case CTRL('W'):
1533                 vi_case(CTRL('W')|vbit:)
1534                         /* Control-W -- Remove the last word */
1535                         while (cursor > 0 && isspace(command[cursor-1]))
1536                                 input_backspace();
1537                         while (cursor > 0 && !isspace(command[cursor-1]))
1538                                 input_backspace();
1539                         break;
1540
1541 #if ENABLE_FEATURE_EDITING_VI
1542                 case 'i'|vbit:
1543                         vi_cmdmode = 0;
1544                         break;
1545                 case 'I'|vbit:
1546                         input_backward(cursor);
1547                         vi_cmdmode = 0;
1548                         break;
1549                 case 'a'|vbit:
1550                         input_forward();
1551                         vi_cmdmode = 0;
1552                         break;
1553                 case 'A'|vbit:
1554                         input_end();
1555                         vi_cmdmode = 0;
1556                         break;
1557                 case 'x'|vbit:
1558                         input_delete(1);
1559                         break;
1560                 case 'X'|vbit:
1561                         if (cursor > 0) {
1562                                 input_backward(1);
1563                                 input_delete(1);
1564                         }
1565                         break;
1566                 case 'W'|vbit:
1567                         vi_Word_motion(command, 1);
1568                         break;
1569                 case 'w'|vbit:
1570                         vi_word_motion(command, 1);
1571                         break;
1572                 case 'E'|vbit:
1573                         vi_End_motion(command);
1574                         break;
1575                 case 'e'|vbit:
1576                         vi_end_motion(command);
1577                         break;
1578                 case 'B'|vbit:
1579                         vi_Back_motion(command);
1580                         break;
1581                 case 'b'|vbit:
1582                         vi_back_motion(command);
1583                         break;
1584                 case 'C'|vbit:
1585                         vi_cmdmode = 0;
1586                         /* fall through */
1587                 case 'D'|vbit:
1588                         goto clear_to_eol;
1589
1590                 case 'c'|vbit:
1591                         vi_cmdmode = 0;
1592                         /* fall through */
1593                 case 'd'|vbit: {
1594                         int nc, sc;
1595                         sc = cursor;
1596                         prevc = ic;
1597                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1598                                 goto prepare_to_die;
1599                         if (c == (prevc & 0xff)) {
1600                                 /* "cc", "dd" */
1601                                 input_backward(cursor);
1602                                 goto clear_to_eol;
1603                                 break;
1604                         }
1605                         switch (c) {
1606                         case 'w':
1607                         case 'W':
1608                         case 'e':
1609                         case 'E':
1610                                 switch (c) {
1611                                 case 'w':   /* "dw", "cw" */
1612                                         vi_word_motion(command, vi_cmdmode);
1613                                         break;
1614                                 case 'W':   /* 'dW', 'cW' */
1615                                         vi_Word_motion(command, vi_cmdmode);
1616                                         break;
1617                                 case 'e':   /* 'de', 'ce' */
1618                                         vi_end_motion(command);
1619                                         input_forward();
1620                                         break;
1621                                 case 'E':   /* 'dE', 'cE' */
1622                                         vi_End_motion(command);
1623                                         input_forward();
1624                                         break;
1625                                 }
1626                                 nc = cursor;
1627                                 input_backward(cursor - sc);
1628                                 while (nc-- > cursor)
1629                                         input_delete(1);
1630                                 break;
1631                         case 'b':  /* "db", "cb" */
1632                         case 'B':  /* implemented as B */
1633                                 if (c == 'b')
1634                                         vi_back_motion(command);
1635                                 else
1636                                         vi_Back_motion(command);
1637                                 while (sc-- > cursor)
1638                                         input_delete(1);
1639                                 break;
1640                         case ' ':  /* "d ", "c " */
1641                                 input_delete(1);
1642                                 break;
1643                         case '$':  /* "d$", "c$" */
1644                         clear_to_eol:
1645                                 while (cursor < command_len)
1646                                         input_delete(1);
1647                                 break;
1648                         }
1649                         break;
1650                 }
1651                 case 'p'|vbit:
1652                         input_forward();
1653                         /* fallthrough */
1654                 case 'P'|vbit:
1655                         put();
1656                         break;
1657                 case 'r'|vbit:
1658                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1659                                 goto prepare_to_die;
1660                         if (c == 0)
1661                                 beep();
1662                         else {
1663                                 *(command + cursor) = c;
1664                                 bb_putchar(c);
1665                                 bb_putchar('\b');
1666                         }
1667                         break;
1668 #endif /* FEATURE_COMMAND_EDITING_VI */
1669
1670                 case '\x1b': /* ESC */
1671
1672 #if ENABLE_FEATURE_EDITING_VI
1673                         if (state->flags & VI_MODE) {
1674                                 /* ESC: insert mode --> command mode */
1675                                 vi_cmdmode = 1;
1676                                 input_backward(1);
1677                                 break;
1678                         }
1679 #endif
1680                         /* escape sequence follows */
1681                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1682                                 goto prepare_to_die;
1683                         /* different vt100 emulations */
1684                         if (c == '[' || c == 'O') {
1685                 vi_case('['|vbit:)
1686                 vi_case('O'|vbit:)
1687                                 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1688                                         goto prepare_to_die;
1689                         }
1690                         if (c >= '1' && c <= '9') {
1691                                 unsigned char dummy;
1692
1693                                 if (safe_read(STDIN_FILENO, &dummy, 1) < 1)
1694                                         goto prepare_to_die;
1695                                 if (dummy != '~')
1696                                         c = '\0';
1697                         }
1698
1699                         switch (c) {
1700 #if ENABLE_FEATURE_TAB_COMPLETION
1701                         case '\t':                      /* Alt-Tab */
1702                                 input_tab(&lastWasTab);
1703                                 break;
1704 #endif
1705 #if MAX_HISTORY > 0
1706                         case 'A':
1707                                 /* Up Arrow -- Get previous command from history */
1708                                 if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1709                                         get_previous_history();
1710                                         goto rewrite_line;
1711                                 }
1712                                 beep();
1713                                 break;
1714                         case 'B':
1715                                 /* Down Arrow -- Get next command in history */
1716                                 if (!get_next_history())
1717                                         break;
1718  rewrite_line:
1719                                 /* Rewrite the line with the selected history item */
1720                                 /* change command */
1721                                 command_len = strlen(strcpy(command, state->history[state->cur_history]));
1722                                 /* redraw and go to eol (bol, in vi */
1723                                 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
1724                                 break;
1725 #endif
1726                         case 'C':
1727                                 /* Right Arrow -- Move forward one character */
1728                                 input_forward();
1729                                 break;
1730                         case 'D':
1731                                 /* Left Arrow -- Move back one character */
1732                                 input_backward(1);
1733                                 break;
1734                         case '3':
1735                                 /* Delete */
1736                                 input_delete(0);
1737                                 break;
1738                         case '1': // vt100? linux vt? or what?
1739                         case '7': // vt100? linux vt? or what?
1740                         case 'H': /* xterm's <Home> */
1741                                 input_backward(cursor);
1742                                 break;
1743                         case '4': // vt100? linux vt? or what?
1744                         case '8': // vt100? linux vt? or what?
1745                         case 'F': /* xterm's <End> */
1746                                 input_end();
1747                                 break;
1748                         default:
1749                                 c = '\0';
1750                                 beep();
1751                         }
1752                         break;
1753
1754                 default:        /* If it's regular input, do the normal thing */
1755
1756                         /* Control-V -- force insert of next char */
1757                         if (c == CTRL('V')) {
1758                                 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1759                                         goto prepare_to_die;
1760                                 if (c == 0) {
1761                                         beep();
1762                                         break;
1763                                 }
1764                         }
1765
1766 #if ENABLE_FEATURE_EDITING_VI
1767                         if (vi_cmdmode)  /* Don't self-insert */
1768                                 break;
1769 #endif
1770                         if (command_len >= (maxsize - 2))        /* Need to leave space for enter */
1771                                 break;
1772
1773                         command_len++;
1774                         if (cursor == (command_len - 1)) {      /* Append if at the end of the line */
1775                                 command[cursor] = c;
1776                                 command[cursor+1] = '\0';
1777                                 cmdedit_set_out_char(' ');
1778                         } else {                        /* Insert otherwise */
1779                                 int sc = cursor;
1780
1781                                 memmove(command + sc + 1, command + sc, command_len - sc);
1782                                 command[sc] = c;
1783                                 sc++;
1784                                 /* rewrite from cursor */
1785                                 input_end();
1786                                 /* to prev x pos + 1 */
1787                                 input_backward(cursor - sc);
1788                         }
1789                         break;
1790                 }
1791                 if (break_out)                  /* Enter is the command terminator, no more input. */
1792                         break;
1793
1794 #if ENABLE_FEATURE_TAB_COMPLETION
1795                 if (c != '\t')
1796                         lastWasTab = FALSE;
1797 #endif
1798         }
1799
1800         if (command_len > 0)
1801                 remember_in_history(command);
1802
1803         if (break_out > 0) {
1804                 command[command_len++] = '\n';
1805                 command[command_len] = '\0';
1806         }
1807
1808 #if ENABLE_FEATURE_TAB_COMPLETION
1809         free_tab_completion_data();
1810 #endif
1811
1812         /* restore initial_settings */
1813         tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);
1814         /* restore SIGWINCH handler */
1815         signal(SIGWINCH, previous_SIGWINCH_handler);
1816         fflush(stdout);
1817
1818         DEINIT_S();
1819
1820         return command_len;
1821 }
1822
1823 line_input_t *new_line_input_t(int flags)
1824 {
1825         line_input_t *n = xzalloc(sizeof(*n));
1826         n->flags = flags;
1827         return n;
1828 }
1829
1830 #else
1831
1832 #undef read_line_input
1833 int read_line_input(const char* prompt, char* command, int maxsize)
1834 {
1835         fputs(prompt, stdout);
1836         fflush(stdout);
1837         fgets(command, maxsize, stdin);
1838         return strlen(command);
1839 }
1840
1841 #endif  /* FEATURE_COMMAND_EDITING */
1842
1843
1844 /*
1845  * Testing
1846  */
1847
1848 #ifdef TEST
1849
1850 #include <locale.h>
1851
1852 const char *applet_name = "debug stuff usage";
1853
1854 int main(int argc, char **argv)
1855 {
1856         char buff[MAX_LINELEN];
1857         char *prompt =
1858 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
1859                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
1860                 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
1861                 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1862 #else
1863                 "% ";
1864 #endif
1865
1866 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1867         setlocale(LC_ALL, "");
1868 #endif
1869         while (1) {
1870                 int l;
1871                 l = read_line_input(prompt, buff);
1872                 if (l <= 0 || buff[l-1] != '\n')
1873                         break;
1874                 buff[l-1] = 0;
1875                 printf("*** read_line_input() returned line =%s=\n", buff);
1876         }
1877         printf("*** read_line_input() detect ^D\n");
1878         return 0;
1879 }
1880
1881 #endif  /* TEST */