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