lineedit.c 45 KB

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