conspy.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A text-mode VNC like program for Linux virtual terminals.
  4. *
  5. * pascal.bellard@ads-lu.com
  6. *
  7. * Based on Russell Stuart's conspy.c
  8. * http://ace-host.stuart.id.au/russell/files/conspy.c
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  11. */
  12. //applet:IF_CONSPY(APPLET(conspy, BB_DIR_BIN, BB_SUID_DROP))
  13. //kbuild:lib-$(CONFIG_CONSPY) += conspy.o
  14. //config:config CONSPY
  15. //config: bool "conspy"
  16. //config: default y
  17. //config: select PLATFORM_LINUX
  18. //config: help
  19. //config: A text-mode VNC like program for Linux virtual terminals.
  20. //config: example: conspy NUM shared access to console num
  21. //config: or conspy -nd NUM screenshot of console num
  22. //config: or conspy -cs NUM poor man's GNU screen like
  23. //usage:#define conspy_trivial_usage
  24. //usage: "[-vcsndfFQ] [-x COL] [-y LINE] [CONSOLE_NO]"
  25. //usage:#define conspy_full_usage "\n\n"
  26. //usage: "A text-mode VNC like program for Linux virtual consoles."
  27. //usage: "\nTo exit, quickly press ESC 3 times."
  28. //usage: "\n"
  29. //usage: "\n -v Don't send keystrokes to the console"
  30. //usage: "\n -c Create missing /dev/{tty,vcsa}N"
  31. //usage: "\n -s Open a SHELL session"
  32. //usage: "\n -n Black & white"
  33. //usage: "\n -d Dump console to stdout"
  34. //usage: "\n -f Follow cursor"
  35. //usage: "\n -F Assume console is on a framebuffer device"
  36. //usage: "\n -Q Disable exit on ESC-ESC-ESC"
  37. //usage: "\n -x COL Starting column"
  38. //usage: "\n -y LINE Starting line"
  39. #include "libbb.h"
  40. #include <sys/kd.h>
  41. #define ESC "\033"
  42. #define CURSOR_ON -1
  43. #define CURSOR_OFF 1
  44. #define DEV_TTY "/dev/tty"
  45. #define DEV_VCSA "/dev/vcsa"
  46. struct screen_info {
  47. unsigned char lines, cols, cursor_x, cursor_y;
  48. };
  49. #define CHAR(x) (*(uint8_t*)(x))
  50. #define ATTR(x) (((uint8_t*)(x))[1])
  51. #define NEXT(x) ((x) += 2)
  52. #define DATA(x) (*(uint16_t*)(x))
  53. struct globals {
  54. char* data;
  55. int size;
  56. int x, y;
  57. int kbd_fd;
  58. int ioerror_count;
  59. int key_count;
  60. int escape_count;
  61. int nokeys;
  62. int current;
  63. int first_line_offset;
  64. int last_attr;
  65. // cached local tty parameters
  66. unsigned width;
  67. unsigned height;
  68. unsigned col;
  69. unsigned line;
  70. smallint curoff; // unknown:0 cursor on:-1 cursor off:1
  71. char attrbuf[sizeof("0;1;5;30;40m")];
  72. // remote console
  73. struct screen_info remote;
  74. // saved local tty terminfo
  75. struct termios term_orig;
  76. char vcsa_name[sizeof(DEV_VCSA "NN")];
  77. };
  78. #define G (*ptr_to_globals)
  79. #define INIT_G() do { \
  80. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  81. G.width = G.height = UINT_MAX; \
  82. G.last_attr--; \
  83. } while (0)
  84. enum {
  85. FLAG_v, // view only
  86. FLAG_c, // create device if need
  87. FLAG_Q, // never exit
  88. FLAG_s, // session
  89. FLAG_n, // no colors
  90. FLAG_d, // dump screen
  91. FLAG_f, // follow cursor
  92. FLAG_F, // framebuffer
  93. };
  94. #define FLAG(x) (1 << FLAG_##x)
  95. #define BW (option_mask32 & FLAG(n))
  96. static void putcsi(const char *s)
  97. {
  98. fputs(ESC"[", stdout);
  99. fputs(s, stdout);
  100. }
  101. static void clrscr(void)
  102. {
  103. // Home, clear till end of screen
  104. putcsi("1;1H" ESC"[J");
  105. G.col = G.line = 0;
  106. }
  107. static void set_cursor(int state)
  108. {
  109. if (G.curoff != state) {
  110. G.curoff = state;
  111. putcsi("?25");
  112. bb_putchar("h?l"[1 + state]);
  113. }
  114. }
  115. static void gotoxy(int col, int line)
  116. {
  117. if (G.col != col || G.line != line) {
  118. G.col = col;
  119. G.line = line;
  120. printf(ESC"[%u;%uH", line + 1, col + 1);
  121. }
  122. }
  123. static void cleanup(int code) NORETURN;
  124. static void cleanup(int code)
  125. {
  126. set_cursor(CURSOR_ON);
  127. tcsetattr(G.kbd_fd, TCSANOW, &G.term_orig);
  128. if (ENABLE_FEATURE_CLEAN_UP) {
  129. close(G.kbd_fd);
  130. }
  131. // Reset attributes
  132. if (!BW)
  133. putcsi("0m");
  134. bb_putchar('\n');
  135. if (code > EXIT_FAILURE)
  136. kill_myself_with_sig(code);
  137. exit(code);
  138. }
  139. static void screen_read_close(void)
  140. {
  141. unsigned i, j;
  142. int vcsa_fd;
  143. char *data;
  144. // Close & re-open vcsa in case they have swapped virtual consoles
  145. vcsa_fd = xopen(G.vcsa_name, O_RDONLY);
  146. xread(vcsa_fd, &G.remote, 4);
  147. i = G.remote.cols * 2;
  148. G.first_line_offset = G.y * i;
  149. i *= G.remote.lines;
  150. if (G.data == NULL) {
  151. G.size = i;
  152. G.data = xzalloc(2 * i);
  153. }
  154. if (G.size != i) {
  155. cleanup(EXIT_FAILURE);
  156. }
  157. data = G.data + G.current;
  158. xread(vcsa_fd, data, G.size);
  159. close(vcsa_fd);
  160. for (i = 0; i < G.remote.lines; i++) {
  161. for (j = 0; j < G.remote.cols; j++, NEXT(data)) {
  162. unsigned x = j - G.x; // if will catch j < G.x too
  163. unsigned y = i - G.y; // if will catch i < G.y too
  164. if (y >= G.height || x >= G.width)
  165. DATA(data) = 0;
  166. else {
  167. uint8_t ch = CHAR(data);
  168. if (ch < ' ')
  169. CHAR(data) = ch | 0x40;
  170. else if (ch > 0x7e)
  171. CHAR(data) = '?';
  172. }
  173. }
  174. }
  175. }
  176. static void screen_char(char *data)
  177. {
  178. if (!BW) {
  179. uint8_t attr_diff;
  180. uint8_t attr = ATTR(data);
  181. if (option_mask32 & FLAG(F)) {
  182. attr >>= 1;
  183. }
  184. attr_diff = G.last_attr ^ attr;
  185. if (attr_diff) {
  186. // Attribute layout for VGA compatible text videobuffer:
  187. // blinking text
  188. // |red bkgd
  189. // ||green bkgd
  190. // |||blue bkgd
  191. // vvvv
  192. // 00000000 <- lsb bit on the right
  193. // bold text / text 8th bit
  194. // red text
  195. // green text
  196. // blue text
  197. // TODO: apparently framebuffer-based console uses different layout
  198. // (bug? attempt to get 8th text bit in better position?)
  199. // red bkgd
  200. // |green bkgd
  201. // ||blue bkgd
  202. // vvv
  203. // 00000000 <- lsb bit on the right
  204. // bold text
  205. // red text
  206. // green text
  207. // blue text
  208. // text 8th bit
  209. // converting RGB color bit triad to BGR:
  210. static const char color[8] = "04261537";
  211. const uint8_t fg_mask = 0x07, bold_mask = 0x08;
  212. const uint8_t bg_mask = 0x70, blink_mask = 0x80;
  213. char *ptr;
  214. ptr = G.attrbuf;
  215. // (G.last_attr & ~attr) has 1 only where
  216. // G.last_attr has 1 but attr has 0.
  217. // Here we check whether we have transition
  218. // bold->non-bold or blink->non-blink:
  219. if (G.last_attr < 0 // initial value
  220. || ((G.last_attr & ~attr) & (bold_mask | blink_mask)) != 0
  221. ) {
  222. *ptr++ = '0'; // "reset all attrs"
  223. *ptr++ = ';';
  224. // must set fg & bg, maybe need to set bold or blink:
  225. attr_diff = attr | ~(bold_mask | blink_mask);
  226. }
  227. G.last_attr = attr;
  228. if (attr_diff & bold_mask) {
  229. *ptr++ = '1';
  230. *ptr++ = ';';
  231. }
  232. if (attr_diff & blink_mask) {
  233. *ptr++ = '5';
  234. *ptr++ = ';';
  235. }
  236. if (attr_diff & fg_mask) {
  237. *ptr++ = '3';
  238. *ptr++ = color[attr & fg_mask];
  239. *ptr++ = ';';
  240. }
  241. if (attr_diff & bg_mask) {
  242. *ptr++ = '4';
  243. *ptr++ = color[(attr & bg_mask) >> 4];
  244. ptr++; // last attribute
  245. }
  246. if (ptr != G.attrbuf) {
  247. ptr[-1] = 'm';
  248. *ptr = '\0';
  249. putcsi(G.attrbuf);
  250. }
  251. }
  252. }
  253. putchar(CHAR(data));
  254. G.col++;
  255. }
  256. static void screen_dump(void)
  257. {
  258. int linefeed_cnt;
  259. int line, col;
  260. int linecnt = G.remote.lines - G.y;
  261. char *data = G.data + G.current + G.first_line_offset;
  262. linefeed_cnt = 0;
  263. for (line = 0; line < linecnt && line < G.height; line++) {
  264. int space_cnt = 0;
  265. for (col = 0; col < G.remote.cols; col++, NEXT(data)) {
  266. unsigned tty_col = col - G.x; // if will catch col < G.x too
  267. if (tty_col >= G.width)
  268. continue;
  269. space_cnt++;
  270. if (BW && CHAR(data) == ' ')
  271. continue;
  272. while (linefeed_cnt != 0) {
  273. //bb_putchar('\r'); - tty driver does it for us
  274. bb_putchar('\n');
  275. linefeed_cnt--;
  276. }
  277. while (--space_cnt)
  278. bb_putchar(' ');
  279. screen_char(data);
  280. }
  281. linefeed_cnt++;
  282. }
  283. }
  284. static void curmove(void)
  285. {
  286. unsigned cx = G.remote.cursor_x - G.x;
  287. unsigned cy = G.remote.cursor_y - G.y;
  288. int cursor = CURSOR_OFF;
  289. if (cx < G.width && cy < G.height) {
  290. gotoxy(cx, cy);
  291. cursor = CURSOR_ON;
  292. }
  293. set_cursor(cursor);
  294. }
  295. static void create_cdev_if_doesnt_exist(const char* name, dev_t dev)
  296. {
  297. int fd = open(name, O_RDONLY);
  298. if (fd != -1)
  299. close(fd);
  300. else if (errno == ENOENT)
  301. mknod(name, S_IFCHR | 0660, dev);
  302. }
  303. static NOINLINE void start_shell_in_child(const char* tty_name)
  304. {
  305. int pid = xvfork();
  306. if (pid == 0) {
  307. struct termios termchild;
  308. const char *shell = get_shell_name();
  309. signal(SIGHUP, SIG_IGN);
  310. // set tty as a controlling tty
  311. setsid();
  312. // make tty to be input, output, error
  313. close(0);
  314. xopen(tty_name, O_RDWR); // uses fd 0
  315. xdup2(0, 1);
  316. xdup2(0, 2);
  317. ioctl(0, TIOCSCTTY, 1);
  318. tcsetpgrp(0, getpid());
  319. tcgetattr(0, &termchild);
  320. termchild.c_lflag |= ECHO;
  321. termchild.c_oflag |= ONLCR | XTABS;
  322. termchild.c_iflag |= ICRNL;
  323. termchild.c_iflag &= ~IXOFF;
  324. tcsetattr_stdin_TCSANOW(&termchild);
  325. execl(shell, shell, "-i", (char *) NULL);
  326. bb_simple_perror_msg_and_die(shell);
  327. }
  328. }
  329. int conspy_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  330. int conspy_main(int argc UNUSED_PARAM, char **argv)
  331. {
  332. char tty_name[sizeof(DEV_TTY "NN")];
  333. #define keybuf bb_common_bufsiz1
  334. struct termios termbuf;
  335. unsigned opts;
  336. unsigned ttynum;
  337. int poll_timeout_ms;
  338. #if ENABLE_LONG_OPTS
  339. static const char getopt_longopts[] ALIGN1 =
  340. "viewonly\0" No_argument "v"
  341. "createdevice\0" No_argument "c"
  342. "neverquit\0" No_argument "Q"
  343. "session\0" No_argument "s"
  344. "nocolors\0" No_argument "n"
  345. "dump\0" No_argument "d"
  346. "follow\0" No_argument "f"
  347. "framebuffer\0" No_argument "F"
  348. ;
  349. applet_long_options = getopt_longopts;
  350. #endif
  351. INIT_G();
  352. strcpy(G.vcsa_name, DEV_VCSA);
  353. opt_complementary = "x+:y+"; // numeric params
  354. opts = getopt32(argv, "vcQsndfFx:y:", &G.x, &G.y);
  355. argv += optind;
  356. ttynum = 0;
  357. if (argv[0]) {
  358. ttynum = xatou_range(argv[0], 0, 63);
  359. sprintf(G.vcsa_name + sizeof(DEV_VCSA)-1, "%u", ttynum);
  360. }
  361. sprintf(tty_name, "%s%u", DEV_TTY, ttynum);
  362. if (opts & FLAG(c)) {
  363. if ((opts & (FLAG(s)|FLAG(v))) != FLAG(v))
  364. create_cdev_if_doesnt_exist(tty_name, makedev(4, ttynum));
  365. create_cdev_if_doesnt_exist(G.vcsa_name, makedev(7, 128 + ttynum));
  366. }
  367. if ((opts & FLAG(s)) && ttynum) {
  368. start_shell_in_child(tty_name);
  369. }
  370. screen_read_close();
  371. if (opts & FLAG(d)) {
  372. screen_dump();
  373. bb_putchar('\n');
  374. return 0;
  375. }
  376. bb_signals(BB_FATAL_SIGS, cleanup);
  377. // All characters must be passed through to us unaltered
  378. G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
  379. tcgetattr(G.kbd_fd, &G.term_orig);
  380. termbuf = G.term_orig;
  381. termbuf.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
  382. //termbuf.c_oflag &= ~(OPOST); - no, we still want \n -> \r\n
  383. termbuf.c_lflag &= ~(ISIG|ICANON|ECHO);
  384. termbuf.c_cc[VMIN] = 1;
  385. termbuf.c_cc[VTIME] = 0;
  386. tcsetattr(G.kbd_fd, TCSANOW, &termbuf);
  387. poll_timeout_ms = 250;
  388. while (1) {
  389. struct pollfd pfd;
  390. int bytes_read;
  391. int i, j;
  392. char *data, *old;
  393. // in the first loop G.width = G.height = 0: refresh
  394. i = G.width;
  395. j = G.height;
  396. get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
  397. if (option_mask32 & FLAG(f)) {
  398. int nx = G.remote.cursor_x - G.width + 1;
  399. int ny = G.remote.cursor_y - G.height + 1;
  400. if (G.remote.cursor_x < G.x) {
  401. G.x = G.remote.cursor_x;
  402. i = 0; // force refresh
  403. }
  404. if (nx > G.x) {
  405. G.x = nx;
  406. i = 0; // force refresh
  407. }
  408. if (G.remote.cursor_y < G.y) {
  409. G.y = G.remote.cursor_y;
  410. i = 0; // force refresh
  411. }
  412. if (ny > G.y) {
  413. G.y = ny;
  414. i = 0; // force refresh
  415. }
  416. }
  417. // Scan console data and redraw our tty where needed
  418. old = G.data + G.current;
  419. G.current = G.size - G.current;
  420. data = G.data + G.current;
  421. screen_read_close();
  422. if (i != G.width || j != G.height) {
  423. clrscr();
  424. screen_dump();
  425. } else {
  426. // For each remote line
  427. old += G.first_line_offset;
  428. data += G.first_line_offset;
  429. for (i = G.y; i < G.remote.lines; i++) {
  430. char *first = NULL; // first char which needs updating
  431. char *last = last; // last char which needs updating
  432. unsigned iy = i - G.y;
  433. if (iy >= G.height)
  434. break;
  435. for (j = 0; j < G.remote.cols; j++, NEXT(old), NEXT(data)) {
  436. unsigned jx = j - G.x; // if will catch j >= G.x too
  437. if (jx < G.width && DATA(data) != DATA(old)) {
  438. last = data;
  439. if (!first) {
  440. first = data;
  441. gotoxy(jx, iy);
  442. }
  443. }
  444. }
  445. if (first) {
  446. // Rewrite updated data on the local screen
  447. for (; first <= last; NEXT(first))
  448. screen_char(first);
  449. }
  450. }
  451. }
  452. curmove();
  453. // Wait for local user keypresses
  454. fflush_all();
  455. pfd.fd = G.kbd_fd;
  456. pfd.events = POLLIN;
  457. bytes_read = 0;
  458. switch (poll(&pfd, 1, poll_timeout_ms)) {
  459. char *k;
  460. case -1:
  461. if (errno != EINTR)
  462. goto abort;
  463. break;
  464. case 0:
  465. if (++G.nokeys >= 4)
  466. G.nokeys = G.escape_count = 0;
  467. break;
  468. default:
  469. // Read the keys pressed
  470. k = keybuf + G.key_count;
  471. bytes_read = read(G.kbd_fd, k, sizeof(keybuf) - G.key_count);
  472. if (bytes_read < 0)
  473. goto abort;
  474. // Do exit processing
  475. if (!(option_mask32 & FLAG(Q))) {
  476. for (i = 0; i < bytes_read; i++) {
  477. if (k[i] != '\033')
  478. G.escape_count = -1;
  479. if (++G.escape_count >= 3)
  480. cleanup(EXIT_SUCCESS);
  481. }
  482. }
  483. }
  484. poll_timeout_ms = 250;
  485. if (option_mask32 & FLAG(v)) continue;
  486. // Insert all keys pressed into the virtual console's input
  487. // buffer. Don't do this if the virtual console is in scan
  488. // code mode - giving ASCII characters to a program expecting
  489. // scan codes will confuse it.
  490. G.key_count += bytes_read;
  491. if (G.escape_count == 0) {
  492. int handle, result;
  493. long kbd_mode;
  494. handle = xopen(tty_name, O_WRONLY);
  495. result = ioctl(handle, KDGKBMODE, &kbd_mode);
  496. if (result >= 0) {
  497. char *p = keybuf;
  498. G.ioerror_count = 0;
  499. if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE) {
  500. G.key_count = 0; // scan code mode
  501. }
  502. for (; G.key_count != 0; p++, G.key_count--) {
  503. result = ioctl(handle, TIOCSTI, p);
  504. if (result < 0) {
  505. memmove(keybuf, p, G.key_count);
  506. break;
  507. }
  508. // If there is an application on console which reacts
  509. // to keypresses, we need to make our first sleep
  510. // shorter to quickly redraw whatever it printed there.
  511. poll_timeout_ms = 20;
  512. }
  513. }
  514. // We sometimes get spurious IO errors on the TTY
  515. // as programs close and re-open it
  516. else if (errno != EIO || ++G.ioerror_count > 4) {
  517. if (ENABLE_FEATURE_CLEAN_UP)
  518. close(handle);
  519. goto abort;
  520. }
  521. // Close & re-open tty in case they have
  522. // swapped virtual consoles
  523. close(handle);
  524. }
  525. } /* while (1) */
  526. abort:
  527. cleanup(EXIT_FAILURE);
  528. }