lineedit.c 45 KB

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