conspy.c 14 KB

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