3
0

conspy.c 13 KB

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