conspy.c 14 KB

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