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