conspy.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. //config:config CONSPY
  13. //config: bool "conspy"
  14. //config: default y
  15. //config: select PLATFORM_LINUX
  16. //config: help
  17. //config: A text-mode VNC like program for Linux virtual terminals.
  18. //config: example: conspy NUM shared access to console num
  19. //config: or conspy -nd NUM screenshot of console num
  20. //config: or conspy -cs NUM poor man's GNU screen like
  21. //applet:IF_CONSPY(APPLET(conspy, BB_DIR_BIN, BB_SUID_DROP))
  22. //kbuild:lib-$(CONFIG_CONSPY) += conspy.o
  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. unsigned opts;
  335. unsigned ttynum;
  336. int poll_timeout_ms;
  337. #if ENABLE_LONG_OPTS
  338. static const char getopt_longopts[] ALIGN1 =
  339. "viewonly\0" No_argument "v"
  340. "createdevice\0" No_argument "c"
  341. "neverquit\0" No_argument "Q"
  342. "session\0" No_argument "s"
  343. "nocolors\0" No_argument "n"
  344. "dump\0" No_argument "d"
  345. "follow\0" No_argument "f"
  346. "framebuffer\0" No_argument "F"
  347. ;
  348. applet_long_options = getopt_longopts;
  349. #endif
  350. #define keybuf bb_common_bufsiz1
  351. setup_common_bufsiz();
  352. INIT_G();
  353. strcpy(G.vcsa_name, DEV_VCSA);
  354. // numeric params
  355. opts = getopt32(argv, "vcQsndfFx:+y:+", &G.x, &G.y);
  356. argv += optind;
  357. ttynum = 0;
  358. if (argv[0]) {
  359. ttynum = xatou_range(argv[0], 0, 63);
  360. sprintf(G.vcsa_name + sizeof(DEV_VCSA)-1, "%u", ttynum);
  361. }
  362. sprintf(tty_name, "%s%u", DEV_TTY, ttynum);
  363. if (opts & FLAG(c)) {
  364. if ((opts & (FLAG(s)|FLAG(v))) != FLAG(v))
  365. create_cdev_if_doesnt_exist(tty_name, makedev(4, ttynum));
  366. create_cdev_if_doesnt_exist(G.vcsa_name, makedev(7, 128 + ttynum));
  367. }
  368. if ((opts & FLAG(s)) && ttynum) {
  369. start_shell_in_child(tty_name);
  370. }
  371. screen_read_close();
  372. if (opts & FLAG(d)) {
  373. screen_dump();
  374. bb_putchar('\n');
  375. return 0;
  376. }
  377. bb_signals(BB_FATAL_SIGS, cleanup);
  378. G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
  379. // All characters must be passed through to us unaltered
  380. set_termios_to_raw(G.kbd_fd, &G.term_orig, 0
  381. | TERMIOS_CLEAR_ISIG // no signals on ^C ^Z etc
  382. | TERMIOS_RAW_INPUT // turn off all input conversions
  383. );
  384. //Note: termios.c_oflag &= ~(OPOST); - no, we still want \n -> \r\n
  385. poll_timeout_ms = 250;
  386. while (1) {
  387. struct pollfd pfd;
  388. int bytes_read;
  389. int i, j;
  390. char *data, *old;
  391. // in the first loop G.width = G.height = 0: refresh
  392. i = G.width;
  393. j = G.height;
  394. get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
  395. if (option_mask32 & FLAG(f)) {
  396. int nx = G.remote.cursor_x - G.width + 1;
  397. int ny = G.remote.cursor_y - G.height + 1;
  398. if (G.remote.cursor_x < G.x) {
  399. G.x = G.remote.cursor_x;
  400. i = 0; // force refresh
  401. }
  402. if (nx > G.x) {
  403. G.x = nx;
  404. i = 0; // force refresh
  405. }
  406. if (G.remote.cursor_y < G.y) {
  407. G.y = G.remote.cursor_y;
  408. i = 0; // force refresh
  409. }
  410. if (ny > G.y) {
  411. G.y = ny;
  412. i = 0; // force refresh
  413. }
  414. }
  415. // Scan console data and redraw our tty where needed
  416. old = G.data + G.current;
  417. G.current = G.size - G.current;
  418. data = G.data + G.current;
  419. screen_read_close();
  420. if (i != G.width || j != G.height) {
  421. clrscr();
  422. screen_dump();
  423. } else {
  424. // For each remote line
  425. old += G.first_line_offset;
  426. data += G.first_line_offset;
  427. for (i = G.y; i < G.remote.lines; i++) {
  428. char *first = NULL; // first char which needs updating
  429. char *last = last; // last char which needs updating
  430. unsigned iy = i - G.y;
  431. if (iy >= G.height)
  432. break;
  433. for (j = 0; j < G.remote.cols; j++, NEXT(old), NEXT(data)) {
  434. unsigned jx = j - G.x; // if will catch j >= G.x too
  435. if (jx < G.width && DATA(data) != DATA(old)) {
  436. last = data;
  437. if (!first) {
  438. first = data;
  439. gotoxy(jx, iy);
  440. }
  441. }
  442. }
  443. if (first) {
  444. // Rewrite updated data on the local screen
  445. for (; first <= last; NEXT(first))
  446. screen_char(first);
  447. }
  448. }
  449. }
  450. curmove();
  451. // Wait for local user keypresses
  452. fflush_all();
  453. pfd.fd = G.kbd_fd;
  454. pfd.events = POLLIN;
  455. bytes_read = 0;
  456. switch (poll(&pfd, 1, poll_timeout_ms)) {
  457. char *k;
  458. case -1:
  459. if (errno != EINTR)
  460. goto abort;
  461. break;
  462. case 0:
  463. if (++G.nokeys >= 4)
  464. G.nokeys = G.escape_count = 0;
  465. break;
  466. default:
  467. // Read the keys pressed
  468. k = keybuf + G.key_count;
  469. bytes_read = read(G.kbd_fd, k, COMMON_BUFSIZE - G.key_count);
  470. if (bytes_read < 0)
  471. goto abort;
  472. // Do exit processing
  473. if (!(option_mask32 & FLAG(Q))) {
  474. for (i = 0; i < bytes_read; i++) {
  475. if (k[i] != '\033')
  476. G.escape_count = -1;
  477. if (++G.escape_count >= 3)
  478. cleanup(EXIT_SUCCESS);
  479. }
  480. }
  481. }
  482. poll_timeout_ms = 250;
  483. if (option_mask32 & FLAG(v)) continue;
  484. // Insert all keys pressed into the virtual console's input
  485. // buffer. Don't do this if the virtual console is in scan
  486. // code mode - giving ASCII characters to a program expecting
  487. // scan codes will confuse it.
  488. G.key_count += bytes_read;
  489. if (G.escape_count == 0) {
  490. int handle, result;
  491. long kbd_mode;
  492. handle = xopen(tty_name, O_WRONLY);
  493. result = ioctl(handle, KDGKBMODE, &kbd_mode);
  494. if (result >= 0) {
  495. char *p = keybuf;
  496. G.ioerror_count = 0;
  497. if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE) {
  498. G.key_count = 0; // scan code mode
  499. }
  500. for (; G.key_count != 0; p++, G.key_count--) {
  501. result = ioctl(handle, TIOCSTI, p);
  502. if (result < 0) {
  503. memmove(keybuf, p, G.key_count);
  504. break;
  505. }
  506. // If there is an application on console which reacts
  507. // to keypresses, we need to make our first sleep
  508. // shorter to quickly redraw whatever it printed there.
  509. poll_timeout_ms = 20;
  510. }
  511. }
  512. // We sometimes get spurious IO errors on the TTY
  513. // as programs close and re-open it
  514. else if (errno != EIO || ++G.ioerror_count > 4) {
  515. if (ENABLE_FEATURE_CLEAN_UP)
  516. close(handle);
  517. goto abort;
  518. }
  519. // Close & re-open tty in case they have
  520. // swapped virtual consoles
  521. close(handle);
  522. }
  523. } /* while (1) */
  524. abort:
  525. cleanup(EXIT_FAILURE);
  526. }