6a53c12f648ce20b9049a41983ebdc42cde2a18d
[oweals/busybox.git] / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editting.
4  *
5  * Copyright (c) 1986-2001 may safely be consumed by a BSD or GPL license.
6  * Written by:   Vladimir Oleynik <vodz@usa.net>
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    <andersee@debian.org> (Majorly adjusted for busybox)
13  *
14  * This code is 'as is' with no warranty.
15  *
16  *
17  */
18
19 /*
20    Usage and Known bugs:
21    Terminal key codes are not extensive, and more will probably
22    need to be added. This version was created on Debian GNU/Linux 2.x.
23    Delete, Backspace, Home, End, and the arrow keys were tested
24    to work in an Xterm and console. Ctrl-A also works as Home.
25    Ctrl-E also works as End.
26
27    Small bugs (simple effect):
28    - not true viewing if terminal size (x*y symbols) less
29      size (prompt + editor`s line + 2 symbols)
30  */
31
32
33 #define TEST
34
35
36 #ifndef TEST
37
38 #include "busybox.h"
39
40 #define D(x)
41
42 #else
43
44 #define BB_FEATURE_SH_COMMAND_EDITING
45 #define BB_FEATURE_SH_TAB_COMPLETION
46 #define BB_FEATURE_USERNAME_COMPLETION
47 #define BB_FEATURE_NONPRINTABLE_INVERSE_PUT
48 #define BB_FEATURE_BASH_STYLE_PROMT
49 #define BB_FEATURE_CLEAN_UP
50
51 #define TRUE  1
52 #define FALSE 0
53 #define D(x)  x
54
55 #endif                                                  /* TEST */
56
57 #ifdef BB_FEATURE_SH_COMMAND_EDITING
58
59 #ifndef BB_FEATURE_SH_TAB_COMPLETION
60 #undef  BB_FEATURE_USERNAME_COMPLETION
61 #endif
62
63 #if defined(BB_FEATURE_USERNAME_COMPLETION) || defined(BB_FEATURE_BASH_STYLE_PROMT)
64 #define BB_FEATURE_GETUSERNAME_AND_HOMEDIR
65 #endif
66
67 #include <stdio.h>
68 #include <errno.h>
69 #include <unistd.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <sys/ioctl.h>
73 #include <ctype.h>
74 #include <signal.h>
75 #include <limits.h>
76
77 #ifdef BB_FEATURE_SH_TAB_COMPLETION
78 #include <dirent.h>
79 #include <sys/stat.h>
80 #endif
81
82 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
83 #ifndef TEST
84 #include "pwd_grp/pwd.h"
85 #else
86 #include <pwd.h>
87 #endif                                                  /* TEST */
88 #endif                                                  /* advanced FEATURES */
89
90
91 #ifdef TEST
92 void *xrealloc(void *old, size_t size)
93 {
94         return realloc(old, size);
95 }
96
97 void *xmalloc(size_t size)
98 {
99         return malloc(size);
100 }
101 char *xstrdup(const char *s)
102 {
103         return strdup(s);
104 }
105
106 void *xcalloc(size_t size, size_t se)
107 {
108         return calloc(size, se);
109 }
110
111 #define error_msg(s, d)                   fprintf(stderr, s, d)
112 #endif
113
114
115 struct history {
116         char *s;
117         struct history *p;
118         struct history *n;
119 };
120
121 /* Maximum length of the linked list for the command line history */
122 static const int MAX_HISTORY = 15;
123
124 /* First element in command line list */
125 static struct history *his_front = NULL;
126
127 /* Last element in command line list */
128 static struct history *his_end = NULL;
129
130
131 /* ED: sparc termios is broken: revert back to old termio handling. */
132
133 #if #cpu(sparc)
134 #      include <termio.h>
135 #      define termios termio
136 #      define setTermSettings(fd,argp) ioctl(fd,TCSETAF,argp)
137 #      define getTermSettings(fd,argp) ioctl(fd,TCGETA,argp)
138 #else
139 #      include <termios.h>
140 #      define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
141 #      define getTermSettings(fd,argp) tcgetattr(fd, argp);
142 #endif
143
144 /* Current termio and the previous termio before starting sh */
145 static struct termios initial_settings, new_settings;
146
147
148 #ifndef _POSIX_VDISABLE
149 #define _POSIX_VDISABLE '\0'
150 #endif
151
152
153 static
154 volatile int cmdedit_termw = 80;        /* actual terminal width */
155 static int history_counter = 0; /* Number of commands in history list */
156 static
157 volatile int handlers_sets = 0; /* Set next bites: */
158
159 enum {
160         SET_ATEXIT = 1,                         /* when atexit() has been called and
161                                                                    get euid,uid,gid to fast compare  */
162         SET_TERM_HANDLERS = 2,          /* set many terminates signal handlers */
163         SET_WCHG_HANDLERS = 4,          /* winchg signal handler */
164         SET_RESET_TERM = 8,                     /* if the terminal needs to be reset upon exit */
165 };
166
167
168 static int cmdedit_x;                   /* real x terminal position */
169 static int cmdedit_y;                   /* pseudoreal y terminal position */
170 static int cmdedit_prmt_len;    /* lenght prompt without colores string */
171
172 static int cursor;                              /* required global for signal handler */
173 static int len;                                 /* --- "" - - "" - -"- --""-- --""--- */
174 static char *command_ps;                /* --- "" - - "" - -"- --""-- --""--- */
175 static
176 #ifndef BB_FEATURE_BASH_STYLE_PROMT
177         const
178 #endif
179 char *cmdedit_prompt;                   /* --- "" - - "" - -"- --""-- --""--- */
180
181 /* Link into lash to reset context to 0 on ^C and such */
182 extern unsigned int shell_context;
183
184
185 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
186 static char *user_buf = "";
187 static char *home_pwd_buf = "";
188 static int my_euid;
189 #endif
190
191 #ifdef BB_FEATURE_BASH_STYLE_PROMT
192 static char *hostname_buf = "";
193 static int num_ok_lines = 1;
194 #endif
195
196
197 #ifdef  BB_FEATURE_SH_TAB_COMPLETION
198
199 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
200 static int my_euid;
201 #endif
202
203 static int my_uid;
204 static int my_gid;
205
206 #endif                                                  /* BB_FEATURE_SH_TAB_COMPLETION */
207
208
209 static void cmdedit_setwidth(int w, int redraw_flg);
210
211 static void win_changed(int nsig)
212 {
213         struct winsize win = { 0, 0, 0, 0 };
214         static __sighandler_t previous_SIGWINCH_handler;        /* for reset */
215
216         /*   emulate      || signal call */
217         if (nsig == -SIGWINCH || nsig == SIGWINCH) {
218                 ioctl(0, TIOCGWINSZ, &win);
219                 if (win.ws_col > 0) {
220                         cmdedit_setwidth(win.ws_col, nsig == SIGWINCH);
221                 } 
222         }
223         /* Unix not all standart in recall signal */
224
225         if (nsig == -SIGWINCH)          /* save previous handler   */
226                 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
227         else if (nsig == SIGWINCH)      /* signaled called handler */
228                 signal(SIGWINCH, win_changed);  /* set for next call       */
229         else                                            /* nsig == 0 */
230                 /* set previous handler    */
231                 signal(SIGWINCH, previous_SIGWINCH_handler);    /* reset    */
232 }
233
234 static void cmdedit_reset_term(void)
235 {
236         if ((handlers_sets & SET_RESET_TERM) != 0) {
237                 /* sparc and other have broken termios support: use old termio handling. */
238                 setTermSettings(fileno(stdin), (void *) &initial_settings);
239                 handlers_sets &= ~SET_RESET_TERM;
240         }
241         if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
242                 /* reset SIGWINCH handler to previous (default) */
243                 win_changed(0);
244                 handlers_sets &= ~SET_WCHG_HANDLERS;
245         }
246         fflush(stdout);
247 #ifdef BB_FEATURE_CLEAN_UP
248         if (his_front) {
249                 struct history *n;
250
251                 //while(his_front!=his_end) {
252                 while (his_front != his_end) {
253                         n = his_front->n;
254                         free(his_front->s);
255                         free(his_front);
256                         his_front = n;
257                 }
258         }
259 #endif
260 }
261
262
263 /* special for recount position for scroll and remove terminal margin effect */
264 static void cmdedit_set_out_char(int next_char)
265 {
266
267         int c = command_ps[cursor];
268
269         if (c == 0)
270                 c = ' ';                                /* destroy end char? */
271 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
272         if (!isprint(c)) {                      /* Inverse put non-printable characters */
273                 if (((unsigned char) c) >= 128)
274                         c -= 128;
275                 if (((unsigned char) c) < ' ')
276                         c += '@';
277                 if (c == 127)
278                         c = '?';
279                 printf("\033[7m%c\033[0m", c);
280         } else
281 #endif
282                 putchar(c);
283         if (++cmdedit_x >= cmdedit_termw) {
284                 /* terminal is scrolled down */
285                 cmdedit_y++;
286                 cmdedit_x = 0;
287
288                 if (!next_char)
289                         next_char = ' ';
290                 /* destroy "(auto)margin" */
291                 putchar(next_char);
292                 putchar('\b');
293         }
294         cursor++;
295 }
296
297 /* Move to end line. Bonus: rewrite line from cursor */
298 static void input_end(void)
299 {
300         while (cursor < len)
301                 cmdedit_set_out_char(0);
302 }
303
304 /* Go to the next line */
305 static void goto_new_line(void)
306 {
307         input_end();
308         if (cmdedit_x)
309                 putchar('\n');
310 }
311
312
313 static inline void out1str(const char *s)
314 {
315         fputs(s, stdout);
316 }
317 static inline void beep(void)
318 {
319         putchar('\007');
320 }
321
322 /* Move back one charactor */
323 /* special for slow terminal */
324 static void input_backward(int num)
325 {
326         if (num > cursor)
327                 num = cursor;
328         cursor -= num;                          /* new cursor (in command, not terminal) */
329
330         if (cmdedit_x >= num) {         /* no to up line */
331                 cmdedit_x -= num;
332                 if (num < 4)
333                         while (num-- > 0)
334                                 putchar('\b');
335
336                 else
337                         printf("\033[%dD", num);
338         } else {
339                 int count_y;
340
341                 if (cmdedit_x) {
342                         putchar('\r');          /* back to first terminal pos.  */
343                         num -= cmdedit_x;       /* set previous backward        */
344                 }
345                 count_y = 1 + num / cmdedit_termw;
346                 printf("\033[%dA", count_y);
347                 cmdedit_y -= count_y;
348                 /*  require  forward  after  uping   */
349                 cmdedit_x = cmdedit_termw * count_y - num;
350                 printf("\033[%dC", cmdedit_x);  /* set term cursor   */
351         }
352 }
353
354 static void put_prompt(void)
355 {
356         out1str(cmdedit_prompt);
357         cmdedit_x = cmdedit_prmt_len;   /* count real x terminal position */
358         cursor = 0;
359 }
360
361 #ifdef BB_FEATURE_BASH_STYLE_PROMT
362 static void
363 add_to_prompt(char **prmt_mem_ptr, int *alm, int *prmt_len,
364                           const char *addb)
365 {
366         int l = strlen(addb);
367
368         *prmt_len += l;
369         if (*alm < (*prmt_len) + 1) {
370                 *alm = (*prmt_len) + 1;
371                 *prmt_mem_ptr = xrealloc(*prmt_mem_ptr, *alm);
372         }
373         strcat(*prmt_mem_ptr, addb);
374 }
375 #endif
376
377 static void parse_prompt(const char *prmt_ptr)
378 {
379 #ifdef BB_FEATURE_BASH_STYLE_PROMT
380         int alm = strlen(prmt_ptr) + 1; /* supposedly require memory */
381         int prmt_len = 0;
382         int sub_len = 0;
383         int flg_not_length = '[';
384         char *prmt_mem_ptr = xstrdup(prmt_ptr);
385         char pwd_buf[PATH_MAX + 1];
386         char buf[16];
387         int c;
388
389         pwd_buf[0] = 0;
390         *prmt_mem_ptr = 0;
391
392         while (*prmt_ptr) {
393                 c = *prmt_ptr++;
394                 if (c == '\\') {
395                         c = *prmt_ptr;
396                         if (c == 0)
397                                 break;
398                         prmt_ptr++;
399                         switch (c) {
400                         case 'u':
401                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, user_buf);
402                                 continue;
403                         case 'h':
404                                 if (hostname_buf[0] == 0) {
405                                         hostname_buf = xcalloc(256, 1);
406                                         if (gethostname(hostname_buf, 255) < 0) {
407                                                 strcpy(hostname_buf, "?");
408                                         } else {
409                                                 char *s = strchr(hostname_buf, '.');
410
411                                                 if (s)
412                                                         *s = 0;
413                                         }
414                                 }
415                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len,
416                                                           hostname_buf);
417                                 continue;
418                         case '$':
419                                 c = my_euid == 0 ? '#' : '$';
420                                 break;
421                         case 'w':
422                                 if (pwd_buf[0] == 0) {
423                                         int l;
424
425                                         getcwd(pwd_buf, PATH_MAX);
426                                         l = strlen(home_pwd_buf);
427                                         if (home_pwd_buf[0] != 0 &&
428                                                 strncmp(home_pwd_buf, pwd_buf, l) == 0) {
429                                                 strcpy(pwd_buf + 1, pwd_buf + l);
430                                                 pwd_buf[0] = '~';
431                                         }
432                                 }
433                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, pwd_buf);
434                                 continue;
435                         case '!':
436                                 snprintf(buf, sizeof(buf), "%d", num_ok_lines);
437                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, buf);
438                                 continue;
439                         case 'e':
440                         case 'E':                       /* \e \E = \033 */
441                                 c = '\033';
442                                 break;
443                         case 'x':
444                         case 'X':
445                         case '0':
446                         case '1':
447                         case '2':
448                         case '3':
449                         case '4':
450                         case '5':
451                         case '6':
452                         case '7':{
453                                 int l;
454                                 int ho = 0;
455                                 char *eho;
456
457                                 if (c == 'X')
458                                         c = 'x';
459
460                                 for (l = 0; l < 3;) {
461
462                                         buf[l++] = *prmt_ptr;
463                                         buf[l] = 0;
464                                         ho = strtol(buf, &eho, c == 'x' ? 16 : 8);
465                                         if (ho > UCHAR_MAX || (eho - buf) < l) {
466                                                 l--;
467                                                 break;
468                                         }
469                                         prmt_ptr++;
470                                 }
471                                 buf[l] = 0;
472                                 ho = strtol(buf, 0, c == 'x' ? 16 : 8);
473                                 c = ho == 0 ? '?' : (char) ho;
474                                 break;
475                         }
476                         case '[':
477                         case ']':
478                                 if (c == flg_not_length) {
479                                         flg_not_length = flg_not_length == '[' ? ']' : '[';
480                                         continue;
481                                 }
482                                 break;
483                         }
484                 }
485                 buf[0] = c;
486                 buf[1] = 0;
487                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, buf);
488                 if (flg_not_length == ']')
489                         sub_len++;
490         }
491         cmdedit_prmt_len = prmt_len - sub_len;
492         cmdedit_prompt = prmt_mem_ptr;
493 #else
494         cmdedit_prompt = prmt_ptr;
495         cmdedit_prmt_len = strlen(prmt_ptr);
496 #endif
497         put_prompt();
498 }
499
500
501 /* draw promt, editor line, and clear tail */
502 static void redraw(int y, int back_cursor)
503 {
504         if (y > 0)                                      /* up to start y */
505                 printf("\033[%dA", y);
506         cmdedit_y = 0;                          /* new quasireal y */
507         putchar('\r');
508         put_prompt();
509         input_end();                            /* rewrite */
510         printf("\033[J");                       /* destroy tail after cursor */
511         input_backward(back_cursor);
512 }
513
514 /* Delete the char in front of the cursor */
515 static void input_delete(void)
516 {
517         int j = cursor;
518
519         if (j == len)
520                 return;
521
522         strcpy(command_ps + j, command_ps + j + 1);
523         len--;
524         input_end();                            /* rewtite new line */
525         cmdedit_set_out_char(0);        /* destroy end char */
526         input_backward(cursor - j);     /* back to old pos cursor */
527 }
528
529 /* Delete the char in back of the cursor */
530 static void input_backspace(void)
531 {
532         if (cursor > 0) {
533                 input_backward(1);
534                 input_delete();
535         }
536 }
537
538
539 /* Move forward one charactor */
540 static void input_forward(void)
541 {
542         if (cursor < len)
543                 cmdedit_set_out_char(command_ps[cursor + 1]);
544 }
545
546
547 static void clean_up_and_die(int sig)
548 {
549         goto_new_line();
550         if (sig != SIGINT)
551                 exit(EXIT_SUCCESS);             /* cmdedit_reset_term() called in atexit */
552         cmdedit_reset_term();
553 }
554
555 static void cmdedit_setwidth(int w, int redraw_flg)
556 {
557         cmdedit_termw = cmdedit_prmt_len + 2;
558         if (w > cmdedit_termw) {
559
560                 cmdedit_termw = w;
561
562                 if (redraw_flg) {
563                         /* new y for current cursor */
564                         int new_y = (cursor + cmdedit_prmt_len) / w;
565
566                         /* redraw */
567                         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
568                         fflush(stdout);
569                 }
570         } else {
571                 error_msg("\n*** Error: minimum screen width is %d",
572                                   cmdedit_termw);
573         }
574 }
575
576 extern void cmdedit_init(void)
577 {
578         if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
579                 /* emulate usage handler to set handler and call yours work */
580                 win_changed(-SIGWINCH);
581                 handlers_sets |= SET_WCHG_HANDLERS;
582         }
583
584         if ((handlers_sets & SET_ATEXIT) == 0) {
585 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
586                 struct passwd *entry;
587
588                 my_euid = geteuid();
589                 entry = getpwuid(my_euid);
590                 if (entry) {
591                         user_buf = xstrdup(entry->pw_name);
592                         home_pwd_buf = xstrdup(entry->pw_dir);
593                 }
594 #endif
595
596 #ifdef  BB_FEATURE_SH_TAB_COMPLETION
597
598 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
599                 my_euid = geteuid();
600 #endif
601                 my_uid = getuid();
602                 my_gid = getgid();
603 #endif                                                  /* BB_FEATURE_SH_TAB_COMPLETION */
604                 handlers_sets |= SET_ATEXIT;
605                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
606         }
607
608         if ((handlers_sets & SET_TERM_HANDLERS) == 0) {
609                 signal(SIGKILL, clean_up_and_die);
610                 signal(SIGINT, clean_up_and_die);
611                 signal(SIGQUIT, clean_up_and_die);
612                 signal(SIGTERM, clean_up_and_die);
613                 handlers_sets |= SET_TERM_HANDLERS;
614         }
615
616 }
617
618 #ifdef BB_FEATURE_SH_TAB_COMPLETION
619
620 static int is_execute(const struct stat *st)
621 {
622         if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
623                 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
624                 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
625                 (st->st_mode & S_IXOTH)) return TRUE;
626         return FALSE;
627 }
628
629 #ifdef BB_FEATURE_USERNAME_COMPLETION
630
631 static char **username_tab_completion(char *ud, int *num_matches)
632 {
633         struct passwd *entry;
634         int userlen;
635         char *temp;
636
637
638         ud++;                                           /* ~user/... to user/... */
639         userlen = strlen(ud);
640
641         if (num_matches == 0) {         /* "~/..." or "~user/..." */
642                 char *sav_ud = ud - 1;
643                 char *home = 0;
644
645                 if (*ud == '/') {               /* "~/..."     */
646                         home = home_pwd_buf;
647                 } else {
648                         /* "~user/..." */
649                         temp = strchr(ud, '/');
650                         *temp = 0;                      /* ~user\0 */
651                         entry = getpwnam(ud);
652                         *temp = '/';            /* restore ~user/... */
653                         ud = temp;
654                         if (entry)
655                                 home = entry->pw_dir;
656                 }
657                 if (home) {
658                         if ((userlen + strlen(home) + 1) < BUFSIZ) {
659                                 char temp2[BUFSIZ];     /* argument size */
660
661                                 /* /home/user/... */
662                                 sprintf(temp2, "%s%s", home, ud);
663                                 strcpy(sav_ud, temp2);
664                         }
665                 }
666                 return 0;                               /* void, result save to argument :-) */
667         } else {
668                 /* "~[^/]*" */
669                 char **matches = (char **) NULL;
670                 int nm = 0;
671
672                 setpwent();
673
674                 while ((entry = getpwent()) != NULL) {
675                         /* Null usernames should result in all users as possible completions. */
676                         if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
677
678                                 temp = xmalloc(3 + strlen(entry->pw_name));
679                                 sprintf(temp, "~%s/", entry->pw_name);
680                                 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
681
682                                 matches[nm++] = temp;
683                         }
684                 }
685
686                 endpwent();
687                 (*num_matches) = nm;
688                 return (matches);
689         }
690 }
691 #endif                                                  /* BB_FEATURE_USERNAME_COMPLETION */
692
693 enum {
694         FIND_EXE_ONLY = 0,
695         FIND_DIR_ONLY = 1,
696         FIND_FILE_ONLY = 2,
697 };
698
699 static int path_parse(char ***p, int flags)
700 {
701         int npth;
702         char *tmp;
703         char *pth;
704
705         /* if not setenv PATH variable, to search cur dir "." */
706         if (flags != FIND_EXE_ONLY || (pth = getenv("PATH")) == 0 ||
707                 /* PATH=<empty> or PATH=:<empty> */
708                 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
709                 return 1;
710         }
711
712         tmp = pth;
713         npth = 0;
714
715         for (;;) {
716                 npth++;                                 /* count words is + 1 count ':' */
717                 tmp = strchr(tmp, ':');
718                 if (tmp) {
719                         if (*++tmp == 0)
720                                 break;                  /* :<empty> */
721                 } else
722                         break;
723         }
724
725         *p = xmalloc(npth * sizeof(char *));
726
727         tmp = pth;
728         (*p)[0] = xstrdup(tmp);
729         npth = 1;                                       /* count words is + 1 count ':' */
730
731         for (;;) {
732                 tmp = strchr(tmp, ':');
733                 if (tmp) {
734                         (*p)[0][(tmp - pth)] = 0;       /* ':' -> '\0' */
735                         if (*++tmp == 0)
736                                 break;                  /* :<empty> */
737                 } else
738                         break;
739                 (*p)[npth++] = &(*p)[0][(tmp - pth)];   /* p[next]=p[0][&'\0'+1] */
740         }
741
742         return npth;
743 }
744
745 static char *add_quote_for_spec_chars(char *found)
746 {
747         int l = 0;
748         char *s = xmalloc((strlen(found) + 1) * 2);
749
750         while (*found) {
751                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
752                         s[l++] = '\\';
753                 s[l++] = *found++;
754         }
755         s[l] = 0;
756         return s;
757 }
758
759 static char **exe_n_cwd_tab_completion(char *command, int *num_matches,
760                                                                            int type)
761 {
762
763         char **matches = 0;
764         DIR *dir;
765         struct dirent *next;
766         char dirbuf[BUFSIZ];
767         int nm = *num_matches;
768         struct stat st;
769         char *path1[1];
770         char **paths = path1;
771         int npaths;
772         int i;
773         char found[BUFSIZ + 4 + PATH_MAX];
774         char *pfind = strrchr(command, '/');
775
776         path1[0] = ".";
777
778         if (pfind == NULL) {
779                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
780                 npaths = path_parse(&paths, type);
781                 pfind = command;
782         } else {
783                 /* with dir */
784                 /* save for change */
785                 strcpy(dirbuf, command);
786                 /* set dir only */
787                 dirbuf[(pfind - command) + 1] = 0;
788 #ifdef BB_FEATURE_USERNAME_COMPLETION
789                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
790                         username_tab_completion(dirbuf, 0);
791 #endif
792                 /* "strip" dirname in command */
793                 pfind++;
794
795                 paths[0] = dirbuf;
796                 npaths = 1;                             /* only 1 dir */
797         }
798
799         for (i = 0; i < npaths; i++) {
800
801                 dir = opendir(paths[i]);
802                 if (!dir)                               /* Don't print an error */
803                         continue;
804
805                 while ((next = readdir(dir)) != NULL) {
806                         const char *str_merge = "%s/%s";
807                         char *str_found = next->d_name;
808
809                         /* matched ? */
810                         if (strncmp(str_found, pfind, strlen(pfind)))
811                                 continue;
812                         /* not see .name without .match */
813                         if (*str_found == '.' && *pfind == 0) {
814                                 if (*paths[i] == '/' && paths[i][1] == 0
815                                         && str_found[1] == 0) str_found = "";   /* only "/" */
816                                 else
817                                         continue;
818                         }
819                         if (paths[i][strlen(paths[i]) - 1] == '/')
820                                 str_merge = "%s%s";
821                         sprintf(found, str_merge, paths[i], str_found);
822                         /* hmm, remover in progress? */
823                         if (stat(found, &st) < 0)
824                                 continue;
825                         /* find with dirs ? */
826                         if (paths[i] != dirbuf)
827                                 strcpy(found, next->d_name);    /* only name */
828                         if (S_ISDIR(st.st_mode)) {
829                                 /* name is directory      */
830                                 /* algorithmic only "/" ? */
831                                 if (*str_found)
832                                         strcat(found, "/");
833                                 str_found = add_quote_for_spec_chars(found);
834                         } else {
835                                 /* not put found file if search only dirs for cd */
836                                 if (type == FIND_DIR_ONLY)
837                                         continue;
838                                 str_found = add_quote_for_spec_chars(found);
839                                 if (type == FIND_FILE_ONLY ||
840                                         (type == FIND_EXE_ONLY && is_execute(&st) == TRUE))
841                                         strcat(str_found, " ");
842                         }
843                         /* Add it to the list */
844                         matches = xrealloc(matches, (nm + 1) * sizeof(char *));
845
846                         matches[nm++] = str_found;
847                 }
848                 closedir(dir);
849         }
850         if (paths != path1) {
851                 free(paths[0]);                 /* allocated memory only in first member */
852                 free(paths);
853         }
854         *num_matches = nm;
855         return (matches);
856 }
857
858 static int match_compare(const void *a, const void *b)
859 {
860         return strcmp(*(char **) a, *(char **) b);
861 }
862
863
864
865 #define QUOT    (UCHAR_MAX+1)
866
867 #define collapse_pos(is, in) { \
868         memcpy(int_buf+is, int_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); \
869         memcpy(pos_buf+is, pos_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); }
870
871 static int find_match(char *matchBuf, int *len_with_quotes)
872 {
873         int i, j;
874         int command_mode;
875         int c, c2;
876         int int_buf[BUFSIZ + 1];
877         int pos_buf[BUFSIZ + 1];
878
879         /* set to integer dimension characters and own positions */
880         for (i = 0;; i++) {
881                 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
882                 if (int_buf[i] == 0) {
883                         pos_buf[i] = -1;        /* indicator end line */
884                         break;
885                 } else
886                         pos_buf[i] = i;
887         }
888
889         /* mask \+symbol and convert '\t' to ' ' */
890         for (i = j = 0; matchBuf[i]; i++, j++)
891                 if (matchBuf[i] == '\\') {
892                         collapse_pos(j, j + 1);
893                         int_buf[j] |= QUOT;
894                         i++;
895 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
896                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
897                                 int_buf[j] = ' ' | QUOT;
898 #endif
899                 }
900 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
901                 else if (matchBuf[i] == '\t')
902                         int_buf[j] = ' ';
903 #endif
904
905         /* mask "symbols" or 'symbols' */
906         c2 = 0;
907         for (i = 0; int_buf[i]; i++) {
908                 c = int_buf[i];
909                 if (c == '\'' || c == '"') {
910                         if (c2 == 0)
911                                 c2 = c;
912                         else {
913                                 if (c == c2)
914                                         c2 = 0;
915                                 else
916                                         int_buf[i] |= QUOT;
917                         }
918                 } else if (c2 != 0 && c != '$')
919                         int_buf[i] |= QUOT;
920         }
921
922         /* skip commands with arguments if line have commands delimiters */
923         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
924         for (i = 0; int_buf[i]; i++) {
925                 c = int_buf[i];
926                 c2 = int_buf[i + 1];
927                 j = i ? int_buf[i - 1] : -1;
928                 command_mode = 0;
929                 if (c == ';' || c == '&' || c == '|') {
930                         command_mode = 1 + (c == c2);
931                         if (c == '&') {
932                                 if (j == '>' || j == '<')
933                                         command_mode = 0;
934                         } else if (c == '|' && j == '>')
935                                 command_mode = 0;
936                 }
937                 if (command_mode) {
938                         collapse_pos(0, i + command_mode);
939                         i = -1;                         /* hack incremet */
940                 }
941         }
942         /* collapse `command...` */
943         for (i = 0; int_buf[i]; i++)
944                 if (int_buf[i] == '`') {
945                         for (j = i + 1; int_buf[j]; j++)
946                                 if (int_buf[j] == '`') {
947                                         collapse_pos(i, j + 1);
948                                         j = 0;
949                                         break;
950                                 }
951                         if (j) {
952                                 /* not found close ` - command mode, collapse all previous */
953                                 collapse_pos(0, i + 1);
954                                 break;
955                         } else
956                                 i--;                    /* hack incremet */
957                 }
958
959         /* collapse (command...(command...)...) or {command...{command...}...} */
960         c = 0;                                          /* "recursive" level */
961         c2 = 0;
962         for (i = 0; int_buf[i]; i++)
963                 if (int_buf[i] == '(' || int_buf[i] == '{') {
964                         if (int_buf[i] == '(')
965                                 c++;
966                         else
967                                 c2++;
968                         collapse_pos(0, i + 1);
969                         i = -1;                         /* hack incremet */
970                 }
971         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
972                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
973                         if (int_buf[i] == ')')
974                                 c--;
975                         else
976                                 c2--;
977                         collapse_pos(0, i + 1);
978                         i = -1;                         /* hack incremet */
979                 }
980
981         /* skip first not quote space */
982         for (i = 0; int_buf[i]; i++)
983                 if (int_buf[i] != ' ')
984                         break;
985         if (i)
986                 collapse_pos(0, i);
987
988         /* set find mode for completion */
989         command_mode = FIND_EXE_ONLY;
990         for (i = 0; int_buf[i]; i++)
991                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
992                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
993                                 && strncmp(&matchBuf[pos_buf[0]], "cd", 2) == 0)
994                                 command_mode = FIND_DIR_ONLY;
995                         else {
996                                 command_mode = FIND_FILE_ONLY;
997                                 break;
998                         }
999                 }
1000         /* "strlen" */
1001         for (i = 0; int_buf[i]; i++);
1002         /* find last word */
1003         for (--i; i >= 0; i--) {
1004                 c = int_buf[i];
1005                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
1006                         collapse_pos(0, i + 1);
1007                         break;
1008                 }
1009         }
1010         /* skip first not quoted '\'' or '"' */
1011         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
1012         /* collapse quote or unquote // or /~ */
1013         while ((int_buf[i] & ~QUOT) == '/' && (
1014                                                                                    (int_buf[i + 1] & ~QUOT) == '/'
1015                                                                                    || (int_buf[i + 1] & ~QUOT) ==
1016                                                                                    '~')) i++;
1017         if (i)
1018                 collapse_pos(0, i);
1019
1020         /* set only match and destroy quotes */
1021         j = 0;
1022         for (i = 0; pos_buf[i] >= 0; i++) {
1023                 matchBuf[i] = matchBuf[pos_buf[i]];
1024                 j = pos_buf[i] + 1;
1025         }
1026         matchBuf[i] = 0;
1027         /* old lenght matchBuf with quotes symbols */
1028         *len_with_quotes = j ? j - pos_buf[0] : 0;
1029
1030         return command_mode;
1031 }
1032
1033
1034 static void input_tab(int *lastWasTab)
1035 {
1036         /* Do TAB completion */
1037         static int num_matches;
1038         static char **matches;
1039
1040         if (lastWasTab == 0) {          /* free all memory */
1041                 if (matches) {
1042                         while (num_matches > 0)
1043                                 free(matches[--num_matches]);
1044                         free(matches);
1045                         matches = (char **) NULL;
1046                 }
1047                 return;
1048         }
1049         if (*lastWasTab == FALSE) {
1050
1051                 char *tmp;
1052                 int len_found;
1053                 char matchBuf[BUFSIZ];
1054                 int find_type;
1055                 int recalc_pos;
1056
1057                 *lastWasTab = TRUE;             /* flop trigger */
1058
1059                 /* Make a local copy of the string -- up
1060                  * to the position of the cursor */
1061                 tmp = strncpy(matchBuf, command_ps, cursor);
1062                 tmp[cursor] = 0;
1063
1064                 find_type = find_match(matchBuf, &recalc_pos);
1065
1066                 /* Free up any memory already allocated */
1067                 input_tab(0);
1068
1069 #ifdef BB_FEATURE_USERNAME_COMPLETION
1070                 /* If the word starts with `~' and there is no slash in the word,
1071                  * then try completing this word as a username. */
1072
1073                 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1074                         matches = username_tab_completion(matchBuf, &num_matches);
1075 #endif
1076                 /* Try to match any executable in our path and everything
1077                  * in the current working directory that matches.  */
1078                 if (!matches)
1079                         matches =
1080                                 exe_n_cwd_tab_completion(matchBuf, &num_matches,
1081                                                                                  find_type);
1082
1083                 /* Did we find exactly one match? */
1084                 if (!matches || num_matches > 1) {
1085                         char *tmp1;
1086
1087                         beep();
1088                         if (!matches)
1089                                 return;                 /* not found */
1090                         /* sort */
1091                         qsort(matches, num_matches, sizeof(char *), match_compare);
1092
1093                         /* find minimal match */
1094                         tmp = xstrdup(matches[0]);
1095                         for (tmp1 = tmp; *tmp1; tmp1++)
1096                                 for (len_found = 1; len_found < num_matches; len_found++)
1097                                         if (matches[len_found][(tmp1 - tmp)] != *tmp1) {
1098                                                 *tmp1 = 0;
1099                                                 break;
1100                                         }
1101                         if (*tmp == 0) {        /* have unique */
1102                                 free(tmp);
1103                                 return;
1104                         }
1105                 } else {                                /* one match */
1106                         tmp = matches[0];
1107                         /* for next completion current found */
1108                         *lastWasTab = FALSE;
1109                 }
1110
1111                 len_found = strlen(tmp);
1112                 /* have space to placed match? */
1113                 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1114
1115                         /* before word for match   */
1116                         command_ps[cursor - recalc_pos] = 0;
1117                         /* save   tail line        */
1118                         strcpy(matchBuf, command_ps + cursor);
1119                         /* add    match            */
1120                         strcat(command_ps, tmp);
1121                         /* add    tail             */
1122                         strcat(command_ps, matchBuf);
1123                         /* back to begin word for match    */
1124                         input_backward(recalc_pos);
1125                         /* new pos                         */
1126                         recalc_pos = cursor + len_found;
1127                         /* new len                         */
1128                         len = strlen(command_ps);
1129                         /* write out the matched command   */
1130                         input_end();
1131                         input_backward(cursor - recalc_pos);
1132                 }
1133                 if (tmp != matches[0])
1134                         free(tmp);
1135         } else {
1136                 /* Ok -- the last char was a TAB.  Since they
1137                  * just hit TAB again, print a list of all the
1138                  * available choices... */
1139                 if (matches && num_matches > 0) {
1140                         int i, col, l;
1141                         int sav_cursor = cursor;        /* change goto_new_line() */
1142
1143                         /* Go to the next line */
1144                         goto_new_line();
1145                         for (i = 0, col = 0; i < num_matches; i++) {
1146                                 l = strlen(matches[i]);
1147                                 if (l < 14)
1148                                         l = 14;
1149                                 printf("%-14s  ", matches[i]);
1150                                 if ((l += 2) > 16)
1151                                         while (l % 16) {
1152                                                 putchar(' ');
1153                                                 l++;
1154                                         }
1155                                 col += l;
1156                                 col -= (col / cmdedit_termw) * cmdedit_termw;
1157                                 if (col > 60 && matches[i + 1] != NULL) {
1158                                         putchar('\n');
1159                                         col = 0;
1160                                 }
1161                         }
1162                         /* Go to the next line and rewrite */
1163                         putchar('\n');
1164                         redraw(0, len - sav_cursor);
1165                 }
1166         }
1167 }
1168 #endif                                                  /* BB_FEATURE_SH_TAB_COMPLETION */
1169
1170 static void get_previous_history(struct history **hp, struct history *p)
1171 {
1172         if ((*hp)->s)
1173                 free((*hp)->s);
1174         (*hp)->s = xstrdup(command_ps);
1175         *hp = p;
1176 }
1177
1178 static inline void get_next_history(struct history **hp)
1179 {
1180         get_previous_history(hp, (*hp)->n);
1181 }
1182
1183 enum {
1184         ESC = 27,
1185         DEL = 127,
1186 };
1187
1188
1189 /*
1190  * This function is used to grab a character buffer
1191  * from the input file descriptor and allows you to
1192  * a string with full command editing (sortof like
1193  * a mini readline).
1194  *
1195  * The following standard commands are not implemented:
1196  * ESC-b -- Move back one word
1197  * ESC-f -- Move forward one word
1198  * ESC-d -- Delete back one word
1199  * ESC-h -- Delete forward one word
1200  * CTL-t -- Transpose two characters
1201  *
1202  * Furthermore, the "vi" command editing keys are not implemented.
1203  *
1204  */
1205 extern void cmdedit_read_input(char *prompt, char command[BUFSIZ])
1206 {
1207
1208         int inputFd = fileno(stdin);
1209
1210         int break_out = 0;
1211         int lastWasTab = FALSE;
1212         char c = 0;
1213         struct history *hp = his_end;
1214
1215         /* prepare before init handlers */
1216         cmdedit_y = 0;                          /* quasireal y, not true work if line > xt*yt */
1217         len = 0;
1218         command_ps = command;
1219
1220         if (new_settings.c_cc[VMIN] == 0) {     /* first call */
1221
1222                 getTermSettings(inputFd, (void *) &initial_settings);
1223                 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1224
1225                 new_settings.c_cc[VMIN] = 1;
1226                 new_settings.c_cc[VTIME] = 0;
1227                 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;     /* Turn off CTRL-C, so we can trap it */
1228                 new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1229                 new_settings.c_lflag &= ~(ECHO | ECHOCTL | ECHONL);     /* Turn off echoing */
1230         }
1231
1232         command[0] = 0;
1233
1234         setTermSettings(inputFd, (void *) &new_settings);
1235         handlers_sets |= SET_RESET_TERM;
1236
1237         cmdedit_init();
1238         /* Print out the command prompt */
1239         parse_prompt(prompt);
1240
1241         while (1) {
1242
1243                 fflush(stdout);                 /* buffered out to fast */
1244
1245                 if (read(inputFd, &c, 1) < 1)
1246                         return;
1247
1248                 switch (c) {
1249                 case '\n':
1250                 case '\r':
1251                         /* Enter */
1252                         goto_new_line();
1253                         break_out = 1;
1254                         break;
1255                 case 1:
1256                         /* Control-a -- Beginning of line */
1257                         input_backward(cursor);
1258                         break;
1259                 case 2:
1260                         /* Control-b -- Move back one character */
1261                         input_backward(1);
1262                         break;
1263                 case 3:
1264                         /* Control-c -- stop gathering input */
1265
1266                         /* Link into lash to reset context to 0 on ^C and such */
1267                         shell_context = 0;
1268
1269                         /* Go to the next line */
1270                         goto_new_line();
1271                         command[0] = 0;
1272
1273                         return;
1274                 case 4:
1275                         /* Control-d -- Delete one character, or exit
1276                          * if the len=0 and no chars to delete */
1277                         if (len == 0) {
1278                                 printf("exit");
1279                                 clean_up_and_die(0);
1280                         } else {
1281                                 input_delete();
1282                         }
1283                         break;
1284                 case 5:
1285                         /* Control-e -- End of line */
1286                         input_end();
1287                         break;
1288                 case 6:
1289                         /* Control-f -- Move forward one character */
1290                         input_forward();
1291                         break;
1292                 case '\b':
1293                 case DEL:
1294                         /* Control-h and DEL */
1295                         input_backspace();
1296                         break;
1297                 case '\t':
1298 #ifdef BB_FEATURE_SH_TAB_COMPLETION
1299                         input_tab(&lastWasTab);
1300 #endif
1301                         break;
1302                 case 14:
1303                         /* Control-n -- Get next command in history */
1304                         if (hp && hp->n && hp->n->s) {
1305                                 get_next_history(&hp);
1306                                 goto rewrite_line;
1307                         } else {
1308                                 beep();
1309                         }
1310                         break;
1311                 case 16:
1312                         /* Control-p -- Get previous command from history */
1313                         if (hp && hp->p) {
1314                                 get_previous_history(&hp, hp->p);
1315                                 goto rewrite_line;
1316                         } else {
1317                                 beep();
1318                         }
1319                         break;
1320                 case 21:
1321                         /* Control-U -- Clear line before cursor */
1322                         if (cursor) {
1323                                 strcpy(command, command + cursor);
1324                                 redraw(cmdedit_y, len -= cursor);
1325                         }
1326                         break;
1327
1328                 case ESC:{
1329                         /* escape sequence follows */
1330                         if (read(inputFd, &c, 1) < 1)
1331                                 return;
1332                         /* different vt100 emulations */
1333                         if (c == '[' || c == 'O') {
1334                                 if (read(inputFd, &c, 1) < 1)
1335                                         return;
1336                         }
1337                         switch (c) {
1338 #ifdef BB_FEATURE_SH_TAB_COMPLETION
1339                         case '\t':                      /* Alt-Tab */
1340
1341                                 input_tab(&lastWasTab);
1342                                 break;
1343 #endif
1344                         case 'A':
1345                                 /* Up Arrow -- Get previous command from history */
1346                                 if (hp && hp->p) {
1347                                         get_previous_history(&hp, hp->p);
1348                                         goto rewrite_line;
1349                                 } else {
1350                                         beep();
1351                                 }
1352                                 break;
1353                         case 'B':
1354                                 /* Down Arrow -- Get next command in history */
1355                                 if (hp && hp->n && hp->n->s) {
1356                                         get_next_history(&hp);
1357                                         goto rewrite_line;
1358                                 } else {
1359                                         beep();
1360                                 }
1361                                 break;
1362
1363                                 /* Rewrite the line with the selected history item */
1364                           rewrite_line:
1365                                 /* change command */
1366                                 len = strlen(strcpy(command, hp->s));
1367                                 /* redraw and go to end line */
1368                                 redraw(cmdedit_y, 0);
1369                                 break;
1370                         case 'C':
1371                                 /* Right Arrow -- Move forward one character */
1372                                 input_forward();
1373                                 break;
1374                         case 'D':
1375                                 /* Left Arrow -- Move back one character */
1376                                 input_backward(1);
1377                                 break;
1378                         case '3':
1379                                 /* Delete */
1380                                 input_delete();
1381                                 break;
1382                         case '1':
1383                         case 'H':
1384                                 /* Home (Ctrl-A) */
1385                                 input_backward(cursor);
1386                                 break;
1387                         case '4':
1388                         case 'F':
1389                                 /* End (Ctrl-E) */
1390                                 input_end();
1391                                 break;
1392                         default:
1393                                 if (!(c >= '1' && c <= '9'))
1394                                         c = 0;
1395                                 beep();
1396                         }
1397                         if (c >= '1' && c <= '9')
1398                                 do
1399                                         if (read(inputFd, &c, 1) < 1)
1400                                                 return;
1401                                 while (c != '~');
1402                         break;
1403                 }
1404
1405                 default:                                /* If it's regular input, do the normal thing */
1406 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1407                         /* Control-V -- Add non-printable symbol */
1408                         if (c == 22) {
1409                                 if (read(inputFd, &c, 1) < 1)
1410                                         return;
1411                                 if (c == 0) {
1412                                         beep();
1413                                         break;
1414                                 }
1415                         } else
1416 #endif
1417                         if (!isprint(c))        /* Skip non-printable characters */
1418                                 break;
1419
1420                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
1421                                 break;
1422
1423                         len++;
1424
1425                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
1426                                 *(command + cursor) = c;
1427                                 *(command + cursor + 1) = 0;
1428                                 cmdedit_set_out_char(0);
1429                         } else {                        /* Insert otherwise */
1430                                 int sc = cursor;
1431
1432                                 memmove(command + sc + 1, command + sc, len - sc);
1433                                 *(command + sc) = c;
1434                                 sc++;
1435                                 /* rewrite from cursor */
1436                                 input_end();
1437                                 /* to prev x pos + 1 */
1438                                 input_backward(cursor - sc);
1439                         }
1440
1441                         break;
1442                 }
1443                 if (break_out)                  /* Enter is the command terminator, no more input. */
1444                         break;
1445
1446                 if (c != '\t')
1447                         lastWasTab = FALSE;
1448         }
1449
1450         setTermSettings(inputFd, (void *) &initial_settings);
1451         handlers_sets &= ~SET_RESET_TERM;
1452
1453         /* Handle command history log */
1454         if (len) {                                      /* no put empty line */
1455
1456                 struct history *h = his_end;
1457                 char *ss;
1458
1459                 ss = xstrdup(command);  /* duplicate */
1460
1461                 if (h == 0) {
1462                         /* No previous history -- this memory is never freed */
1463                         h = his_front = xmalloc(sizeof(struct history));
1464                         h->n = xmalloc(sizeof(struct history));
1465
1466                         h->p = NULL;
1467                         h->s = ss;
1468                         h->n->p = h;
1469                         h->n->n = NULL;
1470                         h->n->s = NULL;
1471                         his_end = h->n;
1472                         history_counter++;
1473                 } else {
1474                         /* Add a new history command -- this memory is never freed */
1475                         h->n = xmalloc(sizeof(struct history));
1476
1477                         h->n->p = h;
1478                         h->n->n = NULL;
1479                         h->n->s = NULL;
1480                         h->s = ss;
1481                         his_end = h->n;
1482
1483                         /* After max history, remove the oldest command */
1484                         if (history_counter >= MAX_HISTORY) {
1485
1486                                 struct history *p = his_front->n;
1487
1488                                 p->p = NULL;
1489                                 free(his_front->s);
1490                                 free(his_front);
1491                                 his_front = p;
1492                         } else {
1493                                 history_counter++;
1494                         }
1495                 }
1496 #if defined(BB_FEATURE_BASH_STYLE_PROMT)
1497                 num_ok_lines++;
1498 #endif
1499         }
1500         command[len++] = '\n';          /* set '\n' */
1501         command[len] = 0;
1502 #if defined(BB_FEATURE_CLEAN_UP) && defined(BB_FEATURE_SH_TAB_COMPLETION)
1503         input_tab(0);                           /* strong free */
1504 #endif
1505 #if defined(BB_FEATURE_BASH_STYLE_PROMT)
1506         free(cmdedit_prompt);
1507 #endif
1508         return;
1509 }
1510
1511
1512 /* Undo the effects of cmdedit_init(). */
1513 extern void cmdedit_terminate(void)
1514 {
1515         cmdedit_reset_term();
1516         if ((handlers_sets & SET_TERM_HANDLERS) != 0) {
1517                 signal(SIGKILL, SIG_DFL);
1518                 signal(SIGINT, SIG_DFL);
1519                 signal(SIGQUIT, SIG_DFL);
1520                 signal(SIGTERM, SIG_DFL);
1521                 signal(SIGWINCH, SIG_DFL);
1522                 handlers_sets &= ~SET_TERM_HANDLERS;
1523         }
1524 }
1525
1526 #endif                                                  /* BB_FEATURE_SH_COMMAND_EDITING */
1527
1528
1529 #ifdef TEST
1530
1531 unsigned int shell_context;
1532
1533 int main(int argc, char **argv)
1534 {
1535         char buff[BUFSIZ];
1536         char *prompt =
1537 #if defined(BB_FEATURE_BASH_STYLE_PROMT)
1538                 "\\[\\033[32;1m\\]\\u@\\[\\033[33;1m\\]\\h:\
1539 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1540 \\!\\[\\033[36;1m\\]\\$ \\[\\033[0m\\]";
1541 #else
1542                 "% ";
1543 #endif
1544
1545         shell_context = 1;
1546         do {
1547                 cmdedit_read_input(prompt, buff);
1548                 printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1549         } while (shell_context);
1550         printf("*** cmdedit_read_input() detect ^C\n");
1551         return 0;
1552 }
1553
1554 #endif                                                  /* TEST */