vi_utils.c 22 KB

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