3
0

conspy.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 (10 kb)"
  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 conspy_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. #endif
  349. #define keybuf bb_common_bufsiz1
  350. setup_common_bufsiz();
  351. INIT_G();
  352. strcpy(G.vcsa_name, DEV_VCSA);
  353. // numeric params
  354. opts = getopt32long(argv, "vcQsndfFx:+y:+", conspy_longopts, &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. G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
  378. // All characters must be passed through to us unaltered
  379. set_termios_to_raw(G.kbd_fd, &G.term_orig, 0
  380. | TERMIOS_CLEAR_ISIG // no signals on ^C ^Z etc
  381. | TERMIOS_RAW_INPUT // turn off all input conversions
  382. );
  383. //Note: termios.c_oflag &= ~(OPOST); - no, we still want \n -> \r\n
  384. poll_timeout_ms = 250;
  385. while (1) {
  386. struct pollfd pfd;
  387. int bytes_read;
  388. int i, j;
  389. char *data, *old;
  390. // in the first loop G.width = G.height = 0: refresh
  391. i = G.width;
  392. j = G.height;
  393. get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
  394. if (option_mask32 & FLAG(f)) {
  395. int nx = G.remote.cursor_x - G.width + 1;
  396. int ny = G.remote.cursor_y - G.height + 1;
  397. if (G.remote.cursor_x < G.x) {
  398. G.x = G.remote.cursor_x;
  399. i = 0; // force refresh
  400. }
  401. if (nx > G.x) {
  402. G.x = nx;
  403. i = 0; // force refresh
  404. }
  405. if (G.remote.cursor_y < G.y) {
  406. G.y = G.remote.cursor_y;
  407. i = 0; // force refresh
  408. }
  409. if (ny > G.y) {
  410. G.y = ny;
  411. i = 0; // force refresh
  412. }
  413. }
  414. // Scan console data and redraw our tty where needed
  415. old = G.data + G.current;
  416. G.current = G.size - G.current;
  417. data = G.data + G.current;
  418. screen_read_close();
  419. if (i != G.width || j != G.height) {
  420. clrscr();
  421. screen_dump();
  422. } else {
  423. // For each remote line
  424. old += G.first_line_offset;
  425. data += G.first_line_offset;
  426. for (i = G.y; i < G.remote.lines; i++) {
  427. char *first = NULL; // first char which needs updating
  428. char *last = last; // last char which needs updating
  429. unsigned iy = i - G.y;
  430. if (iy >= G.height)
  431. break;
  432. for (j = 0; j < G.remote.cols; j++, NEXT(old), NEXT(data)) {
  433. unsigned jx = j - G.x; // if will catch j >= G.x too
  434. if (jx < G.width && DATA(data) != DATA(old)) {
  435. last = data;
  436. if (!first) {
  437. first = data;
  438. gotoxy(jx, iy);
  439. }
  440. }
  441. }
  442. if (first) {
  443. // Rewrite updated data on the local screen
  444. for (; first <= last; NEXT(first))
  445. screen_char(first);
  446. }
  447. }
  448. }
  449. curmove();
  450. // Wait for local user keypresses
  451. fflush_all();
  452. pfd.fd = G.kbd_fd;
  453. pfd.events = POLLIN;
  454. bytes_read = 0;
  455. switch (poll(&pfd, 1, poll_timeout_ms)) {
  456. char *k;
  457. case -1:
  458. if (errno != EINTR)
  459. goto abort;
  460. break;
  461. case 0:
  462. if (++G.nokeys >= 4)
  463. G.nokeys = G.escape_count = 0;
  464. break;
  465. default:
  466. // Read the keys pressed
  467. k = keybuf + G.key_count;
  468. bytes_read = read(G.kbd_fd, k, COMMON_BUFSIZE - G.key_count);
  469. if (bytes_read < 0)
  470. goto abort;
  471. // Do exit processing
  472. if (!(option_mask32 & FLAG(Q))) {
  473. for (i = 0; i < bytes_read; i++) {
  474. if (k[i] != '\033')
  475. G.escape_count = -1;
  476. if (++G.escape_count >= 3)
  477. cleanup(EXIT_SUCCESS);
  478. }
  479. }
  480. }
  481. poll_timeout_ms = 250;
  482. if (option_mask32 & FLAG(v)) continue;
  483. // Insert all keys pressed into the virtual console's input
  484. // buffer. Don't do this if the virtual console is in scan
  485. // code mode - giving ASCII characters to a program expecting
  486. // scan codes will confuse it.
  487. G.key_count += bytes_read;
  488. if (G.escape_count == 0) {
  489. int handle, result;
  490. long kbd_mode;
  491. handle = xopen(tty_name, O_WRONLY);
  492. result = ioctl(handle, KDGKBMODE, &kbd_mode);
  493. if (result >= 0) {
  494. char *p = keybuf;
  495. G.ioerror_count = 0;
  496. if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE) {
  497. G.key_count = 0; // scan code mode
  498. }
  499. for (; G.key_count != 0; p++, G.key_count--) {
  500. result = ioctl(handle, TIOCSTI, p);
  501. if (result < 0) {
  502. memmove(keybuf, p, G.key_count);
  503. break;
  504. }
  505. // If there is an application on console which reacts
  506. // to keypresses, we need to make our first sleep
  507. // shorter to quickly redraw whatever it printed there.
  508. poll_timeout_ms = 20;
  509. }
  510. }
  511. // We sometimes get spurious IO errors on the TTY
  512. // as programs close and re-open it
  513. else if (errno != EIO || ++G.ioerror_count > 4) {
  514. if (ENABLE_FEATURE_CLEAN_UP)
  515. close(handle);
  516. goto abort;
  517. }
  518. // Close & re-open tty in case they have
  519. // swapped virtual consoles
  520. close(handle);
  521. }
  522. } /* while (1) */
  523. abort:
  524. cleanup(EXIT_FAILURE);
  525. }