vi_utils.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /*
  2. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  3. */
  4. #include "vi_utils.h"
  5. #include <mem_sandbox.h>
  6. #define DBG_TAG "vi"
  7. #define DBG_LVL DBG_INFO
  8. #include <rtdbg.h>
  9. #ifndef VI_SANDBOX_SIZE_KB
  10. #define VI_SANDBOX_SIZE_KB 20 /* KB */
  11. #endif
  12. static const char *vi_outof_momory_warning = "vi sandbox runs out of memory, please enlarge VI_SANDBOX_SIZE_KB";
  13. int index_in_strings(const char *strings, const char *key)
  14. {
  15. int j, idx = 0;
  16. while (*strings) {
  17. /* Do we see "key\0" at current position in strings? */
  18. for (j = 0; *strings == key[j]; ++j) {
  19. if (*strings++ == '\0') {
  20. //bb_error_msg("found:'%s' i:%u", key, idx);
  21. return idx; /* yes */
  22. }
  23. }
  24. /* No. Move to the start of the next string. */
  25. while (*strings++ != '\0')
  26. continue;
  27. idx++;
  28. }
  29. return -1;
  30. }
  31. #ifdef VI_ENABLE_COLON
  32. /* Find out if the last character of a string matches the one given */
  33. char* last_char_is(const char *s, int c)
  34. {
  35. if (!s[0])
  36. return NULL;
  37. while (s[1])
  38. s++;
  39. return (*s == (char)c) ? (char *) s : NULL;
  40. }
  41. #endif
  42. #ifdef VI_ENABLE_SETOPTS
  43. char* skip_whitespace(const char *s)
  44. {
  45. /* In POSIX/C locale (the only locale we care about: do we REALLY want
  46. * to allow Unicode whitespace in, say, .conf files? nuts!)
  47. * isspace is only these chars: "\t\n\v\f\r" and space.
  48. * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
  49. * Use that.
  50. */
  51. while (*s == ' ' || (unsigned char)(*s - 9) <= (13 - 9))
  52. s++;
  53. return (char *) s;
  54. }
  55. char* skip_non_whitespace(const char *s)
  56. {
  57. while (*s != '\0' && *s != ' ' && (unsigned char)(*s - 9) > (13 - 9))
  58. s++;
  59. return (char *) s;
  60. }
  61. #endif
  62. ssize_t safe_read(int fd, void *buf, size_t count)
  63. {
  64. ssize_t n;
  65. for (;;) {
  66. n = read(fd, buf, count);
  67. if (n >= 0 || errno != EINTR)
  68. break;
  69. /* Some callers set errno=0, are upset when they see EINTR.
  70. * Returning EINTR is wrong since we retry read(),
  71. * the "error" was transient.
  72. */
  73. errno = 0;
  74. /* repeat the read() */
  75. }
  76. return n;
  77. }
  78. /*
  79. * Read all of the supplied buffer from a file.
  80. * This does multiple reads as necessary.
  81. * Returns the amount read, or -1 on an error.
  82. * A short read is returned on an end of file.
  83. */
  84. ssize_t full_read(int fd, void *buf, size_t len)
  85. {
  86. ssize_t cc;
  87. ssize_t total;
  88. total = 0;
  89. while (len) {
  90. cc = safe_read(fd, buf, len);
  91. if (cc < 0) {
  92. if (total) {
  93. /* we already have some! */
  94. /* user can do another read to know the error code */
  95. return total;
  96. }
  97. return cc; /* read() returns -1 on failure. */
  98. }
  99. if (cc == 0)
  100. break;
  101. buf = ((char *)buf) + cc;
  102. total += cc;
  103. len -= cc;
  104. }
  105. return total;
  106. }
  107. ssize_t safe_write(int fd, const void *buf, size_t count)
  108. {
  109. ssize_t n;
  110. for (;;) {
  111. n = write(fd, buf, count);
  112. if (n >= 0 || errno != EINTR)
  113. break;
  114. /* Some callers set errno=0, are upset when they see EINTR.
  115. * Returning EINTR is wrong since we retry write(),
  116. * the "error" was transient.
  117. */
  118. errno = 0;
  119. /* repeat the write() */
  120. }
  121. return n;
  122. }
  123. /*
  124. * Write all of the supplied buffer out to a file.
  125. * This does multiple writes as necessary.
  126. * Returns the amount written, or -1 if error was seen
  127. * on the very first write.
  128. */
  129. ssize_t full_write(int fd, const void *buf, size_t len)
  130. {
  131. ssize_t cc;
  132. ssize_t total;
  133. total = 0;
  134. while (len) {
  135. cc = safe_write(fd, buf, len);
  136. if (cc < 0) {
  137. if (total) {
  138. /* we already wrote some! */
  139. /* user can do another write to know the error code */
  140. return total;
  141. }
  142. return cc; /* write() returns -1 on failure. */
  143. }
  144. total += cc;
  145. buf = ((const char *)buf) + cc;
  146. len -= cc;
  147. }
  148. return total;
  149. }
  150. /* Wrapper which restarts poll on EINTR or ENOMEM.
  151. * On other errors does perror("poll") and returns.
  152. * Warning! May take longer than timeout_ms to return! */
  153. int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout)
  154. {
  155. while (1) {
  156. int n = poll(ufds, nfds, timeout);
  157. if (n >= 0)
  158. return n;
  159. /* Make sure we inch towards completion */
  160. if (timeout > 0)
  161. timeout--;
  162. /* E.g. strace causes poll to return this */
  163. if (errno == EINTR)
  164. continue;
  165. /* Kernel is very low on memory. Retry. */
  166. /* I doubt many callers would handle this correctly! */
  167. if (errno == ENOMEM)
  168. continue;
  169. rt_kprintf("poll");
  170. return n;
  171. }
  172. }
  173. static mem_sandbox_t vi_sandbox = RT_NULL;
  174. unsigned char vi_mem_init(void)
  175. {
  176. vi_sandbox = mem_sandbox_create(VI_SANDBOX_SIZE_KB * 1024);
  177. if(vi_sandbox == RT_NULL)
  178. {
  179. LOG_E("vi sandbox create error");
  180. return 0;
  181. }
  182. else
  183. {
  184. return 1;
  185. }
  186. }
  187. void vi_mem_release(void)
  188. {
  189. mem_sandbox_delete(vi_sandbox);
  190. }
  191. void *vi_malloc(rt_size_t size)
  192. {
  193. void * p;
  194. p = mem_sandbox_malloc(vi_sandbox, size);
  195. if(p == RT_NULL)
  196. {
  197. LOG_E(vi_outof_momory_warning);
  198. RT_ASSERT(p != RT_NULL);
  199. return RT_NULL;
  200. }
  201. return p;
  202. }
  203. void *vi_realloc(void *rmem, rt_size_t newsize)
  204. {
  205. void *p;
  206. p = mem_sandbox_realloc(vi_sandbox, rmem, newsize);
  207. if(p == RT_NULL && newsize != 0)
  208. {
  209. LOG_E(vi_outof_momory_warning);
  210. RT_ASSERT(p != RT_NULL);
  211. return RT_NULL;
  212. }
  213. return p;
  214. }
  215. void vi_free(void *ptr)
  216. {
  217. mem_sandbox_free(vi_sandbox, ptr);
  218. }
  219. void* vi_zalloc(size_t size)
  220. {
  221. void *ptr = vi_malloc(size);
  222. rt_memset(ptr, 0, size);
  223. return ptr;
  224. }
  225. char *vi_strdup(const char *s)
  226. {
  227. void *p;
  228. p = mem_sandbox_strdup(vi_sandbox, s);
  229. if(p == RT_NULL)
  230. {
  231. LOG_E(vi_outof_momory_warning);
  232. RT_ASSERT(p != RT_NULL);
  233. return RT_NULL;
  234. }
  235. return p;
  236. }
  237. char *vi_strndup(const char *s, size_t n)
  238. {
  239. void *p;
  240. p = mem_sandbox_strndup(vi_sandbox, s, n);
  241. if(p == RT_NULL)
  242. {
  243. LOG_E(vi_outof_momory_warning);
  244. RT_ASSERT(p != RT_NULL);
  245. return RT_NULL;
  246. }
  247. return p;
  248. }
  249. int vi_putchar(int c)
  250. {
  251. rt_kprintf("%c", c);
  252. return (int)c;
  253. }
  254. int64_t read_key(int fd, char *buffer, int timeout)
  255. {
  256. struct pollfd pfd;
  257. const char *seq;
  258. int n;
  259. /* Known escape sequences for cursor and function keys.
  260. * See "Xterm Control Sequences"
  261. * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  262. */
  263. static const char esccmds[] ALIGN1 = {
  264. 'O','A' |0x80, (char) KEYCODE_UP ,
  265. 'O','B' |0x80, (char) KEYCODE_DOWN ,
  266. 'O','C' |0x80, (char) KEYCODE_RIGHT ,
  267. 'O','D' |0x80, (char) KEYCODE_LEFT ,
  268. 'O','H' |0x80, (char) KEYCODE_HOME ,
  269. 'O','F' |0x80, (char) KEYCODE_END ,
  270. #if 0
  271. 'O','P' |0x80, (char) KEYCODE_FUN1 ,
  272. /* [ESC] ESC O [2] P - [Alt-][Shift-]F1 */
  273. /* ESC [ O 1 ; 2 P - Shift-F1 */
  274. /* ESC [ O 1 ; 3 P - Alt-F1 */
  275. /* ESC [ O 1 ; 4 P - Alt-Shift-F1 */
  276. /* ESC [ O 1 ; 5 P - Ctrl-F1 */
  277. /* ESC [ O 1 ; 6 P - Ctrl-Shift-F1 */
  278. 'O','Q' |0x80, (char) KEYCODE_FUN2 ,
  279. 'O','R' |0x80, (char) KEYCODE_FUN3 ,
  280. 'O','S' |0x80, (char) KEYCODE_FUN4 ,
  281. #endif
  282. '[','A' |0x80, (char) KEYCODE_UP ,
  283. '[','B' |0x80, (char) KEYCODE_DOWN ,
  284. '[','C' |0x80, (char) KEYCODE_RIGHT ,
  285. '[','D' |0x80, (char) KEYCODE_LEFT ,
  286. /* ESC [ 1 ; 2 x, where x = A/B/C/D: Shift-<arrow> */
  287. /* ESC [ 1 ; 3 x, where x = A/B/C/D: Alt-<arrow> - implemented below */
  288. /* ESC [ 1 ; 4 x, where x = A/B/C/D: Alt-Shift-<arrow> */
  289. /* ESC [ 1 ; 5 x, where x = A/B/C/D: Ctrl-<arrow> - implemented below */
  290. /* ESC [ 1 ; 6 x, where x = A/B/C/D: Ctrl-Shift-<arrow> */
  291. /* ESC [ 1 ; 7 x, where x = A/B/C/D: Ctrl-Alt-<arrow> */
  292. /* ESC [ 1 ; 8 x, where x = A/B/C/D: Ctrl-Alt-Shift-<arrow> */
  293. '[','H' |0x80, (char) KEYCODE_HOME , /* xterm */
  294. '[','F' |0x80, (char) KEYCODE_END , /* xterm */
  295. /* [ESC] ESC [ [2] H - [Alt-][Shift-]Home (End similarly?) */
  296. /* '[','Z' |0x80, (char) KEYCODE_SHIFT_TAB, */
  297. '[','1','~' |0x80, (char) KEYCODE_HOME , /* vt100? linux vt? or what? */
  298. '[','2','~' |0x80, (char) KEYCODE_INSERT ,
  299. /* ESC [ 2 ; 3 ~ - Alt-Insert */
  300. '[','3','~' |0x80, (char) KEYCODE_DELETE ,
  301. /* [ESC] ESC [ 3 [;2] ~ - [Alt-][Shift-]Delete */
  302. /* ESC [ 3 ; 3 ~ - Alt-Delete */
  303. /* ESC [ 3 ; 5 ~ - Ctrl-Delete */
  304. '[','4','~' |0x80, (char) KEYCODE_END , /* vt100? linux vt? or what? */
  305. '[','5','~' |0x80, (char) KEYCODE_PAGEUP ,
  306. /* ESC [ 5 ; 3 ~ - Alt-PgUp */
  307. /* ESC [ 5 ; 5 ~ - Ctrl-PgUp */
  308. /* ESC [ 5 ; 7 ~ - Ctrl-Alt-PgUp */
  309. '[','6','~' |0x80, (char) KEYCODE_PAGEDOWN,
  310. '[','7','~' |0x80, (char) KEYCODE_HOME , /* vt100? linux vt? or what? */
  311. '[','8','~' |0x80, (char) KEYCODE_END , /* vt100? linux vt? or what? */
  312. #if 0
  313. '[','1','1','~'|0x80, (char) KEYCODE_FUN1 , /* old xterm, deprecated by ESC O P */
  314. '[','1','2','~'|0x80, (char) KEYCODE_FUN2 , /* old xterm... */
  315. '[','1','3','~'|0x80, (char) KEYCODE_FUN3 , /* old xterm... */
  316. '[','1','4','~'|0x80, (char) KEYCODE_FUN4 , /* old xterm... */
  317. '[','1','5','~'|0x80, (char) KEYCODE_FUN5 ,
  318. /* [ESC] ESC [ 1 5 [;2] ~ - [Alt-][Shift-]F5 */
  319. '[','1','7','~'|0x80, (char) KEYCODE_FUN6 ,
  320. '[','1','8','~'|0x80, (char) KEYCODE_FUN7 ,
  321. '[','1','9','~'|0x80, (char) KEYCODE_FUN8 ,
  322. '[','2','0','~'|0x80, (char) KEYCODE_FUN9 ,
  323. '[','2','1','~'|0x80, (char) KEYCODE_FUN10 ,
  324. '[','2','3','~'|0x80, (char) KEYCODE_FUN11 ,
  325. '[','2','4','~'|0x80, (char) KEYCODE_FUN12 ,
  326. /* ESC [ 2 4 ; 2 ~ - Shift-F12 */
  327. /* ESC [ 2 4 ; 3 ~ - Alt-F12 */
  328. /* ESC [ 2 4 ; 4 ~ - Alt-Shift-F12 */
  329. /* ESC [ 2 4 ; 5 ~ - Ctrl-F12 */
  330. /* ESC [ 2 4 ; 6 ~ - Ctrl-Shift-F12 */
  331. #endif
  332. /* '[','1',';','5','A' |0x80, (char) KEYCODE_CTRL_UP , - unused */
  333. /* '[','1',';','5','B' |0x80, (char) KEYCODE_CTRL_DOWN , - unused */
  334. '[','1',';','5','C' |0x80, (char) KEYCODE_CTRL_RIGHT,
  335. '[','1',';','5','D' |0x80, (char) KEYCODE_CTRL_LEFT ,
  336. /* '[','1',';','3','A' |0x80, (char) KEYCODE_ALT_UP , - unused */
  337. /* '[','1',';','3','B' |0x80, (char) KEYCODE_ALT_DOWN , - unused */
  338. '[','1',';','3','C' |0x80, (char) KEYCODE_ALT_RIGHT,
  339. '[','1',';','3','D' |0x80, (char) KEYCODE_ALT_LEFT ,
  340. /* '[','3',';','3','~' |0x80, (char) KEYCODE_ALT_DELETE, - unused */
  341. 0
  342. };
  343. pfd.fd = fd;
  344. pfd.events = POLLIN;
  345. buffer++; /* saved chars counter is in buffer[-1] now */
  346. start_over:
  347. errno = 0;
  348. n = (unsigned char)buffer[-1];
  349. if (n == 0) {
  350. /* If no data, wait for input.
  351. * If requested, wait TIMEOUT ms. TIMEOUT = -1 is useful
  352. * if fd can be in non-blocking mode.
  353. */
  354. if (timeout >= -1) {
  355. if (safe_poll(&pfd, 1, timeout) == 0) {
  356. /* Timed out */
  357. errno = EAGAIN;
  358. return -1;
  359. }
  360. }
  361. /* It is tempting to read more than one byte here,
  362. * but it breaks pasting. Example: at shell prompt,
  363. * user presses "c","a","t" and then pastes "\nline\n".
  364. * When we were reading 3 bytes here, we were eating
  365. * "li" too, and cat was getting wrong input.
  366. */
  367. n = safe_read(fd, buffer, 1);
  368. if (n <= 0)
  369. return -1;
  370. }
  371. {
  372. unsigned char c = buffer[0];
  373. n--;
  374. if (n)
  375. memmove(buffer, buffer + 1, n);
  376. /* Only ESC starts ESC sequences */
  377. if (c != 27) {
  378. buffer[-1] = n;
  379. return c;
  380. }
  381. }
  382. /* Loop through known ESC sequences */
  383. seq = esccmds;
  384. while (*seq != '\0') {
  385. /* n - position in sequence we did not read yet */
  386. int i = 0; /* position in sequence to compare */
  387. /* Loop through chars in this sequence */
  388. while (1) {
  389. /* So far escape sequence matched up to [i-1] */
  390. if (n <= i) {
  391. int read_num;
  392. /* Need more chars, read another one if it wouldn't block.
  393. * Note that escape sequences come in as a unit,
  394. * so if we block for long it's not really an escape sequence.
  395. * Timeout is needed to reconnect escape sequences
  396. * split up by transmission over a serial console. */
  397. if (safe_poll(&pfd, 1, 50) == 0) {
  398. /* No more data!
  399. * Array is sorted from shortest to longest,
  400. * we can't match anything later in array -
  401. * anything later is longer than this seq.
  402. * Break out of both loops. */
  403. goto got_all;
  404. }
  405. errno = 0;
  406. read_num = safe_read(fd, buffer + n, 1);
  407. if (read_num <= 0) {
  408. /* If EAGAIN, then fd is O_NONBLOCK and poll lied:
  409. * in fact, there is no data. */
  410. if (errno != EAGAIN) {
  411. /* otherwise: it's EOF/error */
  412. buffer[-1] = 0;
  413. return -1;
  414. }
  415. goto got_all;
  416. }
  417. n++;
  418. }
  419. if (buffer[i] != (seq[i] & 0x7f)) {
  420. /* This seq doesn't match, go to next */
  421. seq += i;
  422. /* Forward to last char */
  423. while (!(*seq & 0x80))
  424. seq++;
  425. /* Skip it and the keycode which follows */
  426. seq += 2;
  427. break;
  428. }
  429. if (seq[i] & 0x80) {
  430. /* Entire seq matched */
  431. n = 0;
  432. /* n -= i; memmove(...);
  433. * would be more correct,
  434. * but we never read ahead that much,
  435. * and n == i here. */
  436. buffer[-1] = 0;
  437. return (signed char)seq[i+1];
  438. }
  439. i++;
  440. }
  441. }
  442. /* We did not find matching sequence.
  443. * We possibly read and stored more input in buffer[] by now.
  444. * n = bytes read. Try to read more until we time out.
  445. */
  446. while (n < KEYCODE_BUFFER_SIZE-1) { /* 1 for count byte at buffer[-1] */
  447. int read_num;
  448. if (safe_poll(&pfd, 1, 50) == 0) {
  449. /* No more data! */
  450. break;
  451. }
  452. errno = 0;
  453. read_num = safe_read(fd, buffer + n, 1);
  454. if (read_num <= 0) {
  455. /* If EAGAIN, then fd is O_NONBLOCK and poll lied:
  456. * in fact, there is no data. */
  457. if (errno != EAGAIN) {
  458. /* otherwise: it's EOF/error */
  459. buffer[-1] = 0;
  460. return -1;
  461. }
  462. break;
  463. }
  464. n++;
  465. /* Try to decipher "ESC [ NNN ; NNN R" sequence */
  466. if ((ENABLE_FEATURE_VI_ASK_TERMINAL)
  467. && n >= 5
  468. && buffer[0] == '['
  469. && buffer[n-1] == 'R'
  470. && isdigit((unsigned char)buffer[1])
  471. ) {
  472. char *end;
  473. unsigned long row, col;
  474. row = strtoul(buffer + 1, &end, 10);
  475. if (*end != ';' || !isdigit((unsigned char)end[1]))
  476. continue;
  477. col = strtoul(end + 1, &end, 10);
  478. if (*end != 'R')
  479. continue;
  480. if (row < 1 || col < 1 || (row | col) > 0x7fff)
  481. continue;
  482. buffer[-1] = 0;
  483. /* Pack into "1 <row15bits> <col16bits>" 32-bit sequence */
  484. row |= ((unsigned)(-1) << 15);
  485. col |= (row << 16);
  486. /* Return it in high-order word */
  487. return ((int64_t) col << 32) | (uint32_t)KEYCODE_CURSOR_POS;
  488. }
  489. }
  490. got_all:
  491. if (n <= 1) {
  492. /* Alt-x is usually returned as ESC x.
  493. * Report ESC, x is remembered for the next call.
  494. */
  495. buffer[-1] = n;
  496. return 27;
  497. }
  498. /* We were doing "buffer[-1] = n; return c;" here, but this results
  499. * in unknown key sequences being interpreted as ESC + garbage.
  500. * This was not useful. Pretend there was no key pressed,
  501. * go and wait for a new keypress:
  502. */
  503. buffer[-1] = 0;
  504. goto start_over;
  505. }
  506. static int vasprintf(char **string_ptr, const char *format, va_list p)
  507. {
  508. int r;
  509. va_list p2;
  510. char buf[128];
  511. va_copy(p2, p);
  512. r = rt_vsnprintf(buf, 128, format, p);
  513. va_end(p);
  514. /* Note: can't use xstrdup/xmalloc, they call vasprintf (us) on failure! */
  515. if (r < 128) {
  516. va_end(p2);
  517. *string_ptr = vi_strdup(buf);
  518. return (*string_ptr ? r : -1);
  519. }
  520. *string_ptr = vi_malloc(r+1);
  521. r = (*string_ptr ? rt_vsnprintf(*string_ptr, r+1, format, p2) : -1);
  522. va_end(p2);
  523. return r;
  524. }
  525. // Die with an error message if we can't malloc() enough space and do an
  526. // sprintf() into that space.
  527. char* xasprintf(const char *format, ...)
  528. {
  529. va_list p;
  530. int r;
  531. char *string_ptr;
  532. va_start(p, format);
  533. r = vasprintf(&string_ptr, format, p);
  534. va_end(p);
  535. if (r < 0)
  536. rt_kprintf("die_memory_exhausted"); //bb_die_memory_exhausted();
  537. return string_ptr;
  538. }
  539. #ifdef RT_USING_POSIX_TERMIOS
  540. static int wh_helper(int value, int def_val, const char *env_name, int *err)
  541. {
  542. /* Envvars override even if "value" from ioctl is valid (>0).
  543. * Rationale: it's impossible to guess what user wants.
  544. * For example: "man CMD | ...": should "man" format output
  545. * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
  546. * We _cant_ know it. If "..." saves text for e.g. email,
  547. * then it's probably 80 chars.
  548. * If "..." is, say, "grep -v DISCARD | $PAGER", then user
  549. * would prefer his tty's width to be used!
  550. *
  551. * Since we don't know, at least allow user to do this:
  552. * "COLUMNS=80 man CMD | ..."
  553. */
  554. char *s = getenv(env_name);
  555. if (s) {
  556. value = atoi(s);
  557. /* If LINES/COLUMNS are set, pretend that there is
  558. * no error getting w/h, this prevents some ugly
  559. * cursor tricks by our callers */
  560. *err = 0;
  561. }
  562. if (value <= 1 || value >= 30000)
  563. value = def_val;
  564. return value;
  565. }
  566. int get_terminal_width_height(int fd, unsigned *width, unsigned *height)
  567. {
  568. struct winsize win;
  569. int err;
  570. if (fd == -1) {
  571. fd = STDOUT_FILENO;
  572. }
  573. win.ws_row = 0;
  574. win.ws_col = 0;
  575. /* I've seen ioctl returning 0, but row/col is (still?) 0.
  576. * We treat that as an error too. */
  577. err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
  578. if (height)
  579. *height = wh_helper(win.ws_row, 24, "LINES", &err);
  580. if (width)
  581. *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
  582. return err;
  583. }
  584. int tcsetattr_stdin_TCSANOW(const struct termios *tp)
  585. {
  586. return tcsetattr(STDIN_FILENO, TCSANOW, tp);
  587. }
  588. static int get_termios_and_make_raw(int fd, struct termios *newterm, struct termios *oldterm, int flags)
  589. {
  590. //TODO: slattach, shell read might be adapted to use this too: grep for "tcsetattr", "[VTIME] = 0"
  591. int r;
  592. rt_memset(oldterm, 0, sizeof(*oldterm)); /* paranoia */
  593. r = tcgetattr(fd, oldterm);
  594. *newterm = *oldterm;
  595. /* Turn off buffered input (ICANON)
  596. * Turn off echoing (ECHO)
  597. * and separate echoing of newline (ECHONL, normally off anyway)
  598. */
  599. newterm->c_lflag &= ~(ICANON | ECHO | ECHONL);
  600. if (flags & TERMIOS_CLEAR_ISIG) {
  601. /* dont recognize INT/QUIT/SUSP chars */
  602. newterm->c_lflag &= ~ISIG;
  603. }
  604. /* reads will block only if < 1 char is available */
  605. newterm->c_cc[VMIN] = 1;
  606. /* no timeout (reads block forever) */
  607. newterm->c_cc[VTIME] = 0;
  608. /* IXON, IXOFF, and IXANY:
  609. * IXOFF=1: sw flow control is enabled on input queue:
  610. * tty transmits a STOP char when input queue is close to full
  611. * and transmits a START char when input queue is nearly empty.
  612. * IXON=1: sw flow control is enabled on output queue:
  613. * tty will stop sending if STOP char is received,
  614. * and resume sending if START is received, or if any char
  615. * is received and IXANY=1.
  616. */
  617. if (flags & TERMIOS_RAW_CRNL_INPUT) {
  618. /* IXON=0: XON/XOFF chars are treated as normal chars (why we do this?) */
  619. /* dont convert CR to NL on input */
  620. newterm->c_iflag &= ~(IXON | ICRNL);
  621. }
  622. if (flags & TERMIOS_RAW_CRNL_OUTPUT) {
  623. /* dont convert NL to CR+NL on output */
  624. newterm->c_oflag &= ~(ONLCR);
  625. /* Maybe clear more c_oflag bits? Usually, only OPOST and ONLCR are set.
  626. * OPOST Enable output processing (reqd for OLCUC and *NL* bits to work)
  627. * OLCUC Map lowercase characters to uppercase on output.
  628. * OCRNL Map CR to NL on output.
  629. * ONOCR Don't output CR at column 0.
  630. * ONLRET Don't output CR.
  631. */
  632. }
  633. if (flags & TERMIOS_RAW_INPUT) {
  634. #ifndef IMAXBEL
  635. # define IMAXBEL 0
  636. #endif
  637. #ifndef IUCLC
  638. # define IUCLC 0
  639. #endif
  640. #ifndef IXANY
  641. # define IXANY 0
  642. #endif
  643. /* IXOFF=0: disable sending XON/XOFF if input buf is full
  644. * IXON=0: input XON/XOFF chars are not special
  645. * BRKINT=0: dont send SIGINT on break
  646. * IMAXBEL=0: dont echo BEL on input line too long
  647. * INLCR,ICRNL,IUCLC: dont convert anything on input
  648. */
  649. newterm->c_iflag &= ~(IXOFF|IXON|IXANY|BRKINT|INLCR|ICRNL|IUCLC|IMAXBEL);
  650. }
  651. return r;
  652. }
  653. int set_termios_to_raw(int fd, struct termios *oldterm, int flags)
  654. {
  655. struct termios newterm;
  656. get_termios_and_make_raw(fd, &newterm, oldterm, flags);
  657. return tcsetattr(fd, TCSANOW, &newterm);
  658. }
  659. #endif /* RT_USING_POSIX_TERMIOS */