1 /* vi: set sw=4 ts=4: */
3 * A text-mode VNC like program for Linux virtual terminals.
5 * pascal.bellard@ads-lu.com
7 * Based on Russell Stuart's conspy.c
8 * http://ace-host.stuart.id.au/russell/files/conspy.c
10 * Licensed under GPLv2 or later, see file License in this tarball for details.
13 //applet:IF_CONSPY(APPLET(conspy, _BB_DIR_BIN, _BB_SUID_DROP))
15 //kbuild:lib-$(CONFIG_CONSPY) += conspy.o
17 //config:config CONSPY
18 //config: bool "conspy"
21 //config: A text-mode VNC like program for Linux virtual terminals.
22 //config: example: conspy NUM shared access to console num
23 //config: or conspy -nd NUM screenshot of console num
24 //config: or conspy -cs NUM poor man's GNU screen like
26 //usage:#define conspy_trivial_usage
27 //usage: "[-vcsndf] [-x COL] [-y LINE] [CONSOLE_NO]"
28 //usage:#define conspy_full_usage "\n\n"
29 //usage: "A text-mode VNC like program for Linux virtual consoles."
30 //usage: "\nTo exit, quickly press ESC 3 times."
33 //usage: "\n -v Don't send keystrokes to the console"
34 //usage: "\n -c Create missing devices in /dev"
35 //usage: "\n -s Open a SHELL session"
36 //usage: "\n -n Black & white"
37 //usage: "\n -d Dump console to stdout"
38 //usage: "\n -f Follow cursor"
39 //usage: "\n -x COL Starting column"
40 //usage: "\n -y LINE Starting line"
46 unsigned char lines, cols, cursor_x, cursor_y;
49 #define CHAR(x) ((uint8_t)((x)[0]))
50 #define ATTR(x) ((uint8_t)((x)[1]))
51 #define NEXT(x) ((x)+=2)
52 #define DATA(x) (*(uint16_t*)(x))
65 // cached local tty parameters
72 uint8_t force_attr_change;
73 char attrbuf[sizeof("\033[0;1;5;30;40m")];
75 struct screen_info remote;
76 // saved local tty terminfo
77 struct termios term_orig;
80 #define G (*ptr_to_globals)
81 #define INIT_G() do { \
82 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
83 G.attrbuf[0] = '\033'; \
85 G.force_attr_change = 0xff; \
90 FLAG_c, // create device if need
93 FLAG_d, // dump screen
94 FLAG_f, // follow cursor
96 #define FLAG(x) (1 << FLAG_##x)
97 #define BW (option_mask32 & FLAG(n))
99 static void screen_read_close(void)
102 char *data = G.data + G.current;
104 xread(G.vcsa_fd, data, G.size);
105 for (i = 0; i < G.remote.lines; i++) {
106 for (j = 0; j < G.remote.cols; j++, NEXT(data)) {
107 unsigned x = j - G.x; // if will catch j < G.x too
108 unsigned y = i - G.y; // if will catch i < G.y too
110 if (CHAR(data) < ' ')
111 *data = ' '; // CHAR(data) = ' ';
112 if (y >= G.height || x >= G.width)
119 static void screen_char(char *data)
122 uint8_t attr = ATTR(data);
123 //uint8_t attr = ATTR(data) >> 1; // for framebuffer console
124 uint8_t attr_diff = (G.last_attr ^ attr) | G.force_attr_change;
127 // Attribute layout for VGA compatible text videobuffer:
133 // 00000000 <- lsb bit on the right
134 // bold text / text 8th bit
138 // TODO: apparently framebuffer-based console uses different layout
139 // (bug? attempt to get 8th text bit in better position?)
144 // 00000000 <- lsb bit on the right
150 // converting RGB color bit triad to BGR:
151 static const char color[8] = "04261537";
152 const uint8_t fg_mask = 0x07, bold_mask = 0x08;
153 const uint8_t bg_mask = 0x70, blink_mask = 0x80;
156 ptr = G.attrbuf + 2; /* skip "ESC [" */
158 // (G.last_attr & ~attr) has 1 only where
159 // G.last_attr has 1 but attr has 0.
160 // Here we check whether we have transition
161 // bold->non-bold or blink->non-blink:
162 if ((G.last_attr & ~attr) & (bold_mask | blink_mask)) {
163 *ptr++ = '0'; // "reset all attrs"
165 // must set fg & bg, maybe need to set bold or blink:
166 attr_diff = attr | ~(bold_mask | blink_mask);
168 G.force_attr_change = 0;
170 if (attr_diff & bold_mask) {
174 if (attr_diff & blink_mask) {
178 if (attr_diff & fg_mask) {
180 *ptr++ = color[attr & fg_mask];
183 if (attr_diff & bg_mask) {
185 *ptr++ = color[(attr & bg_mask) >> 4];
188 if (ptr != G.attrbuf + 2) {
191 fputs(G.attrbuf, stdout);
199 static void clrscr(void)
201 // Home, clear till end of src, cursor on
202 fputs("\033[1;1H" "\033[J" "\033[?25h", stdout);
203 G.curoff = G.col = G.line = 0;
206 static void curoff(void)
210 fputs("\033[?25l", stdout);
214 static void curon(void)
218 fputs("\033[?25h", stdout);
222 static void gotoxy(int col, int line)
224 if (G.col != col || G.line != line) {
227 printf("\033[%u;%uH", line + 1, col + 1);
231 static void screen_dump(void)
235 int linecnt = G.remote.lines - G.y;
236 char *data = G.data + G.current + (2 * G.y * G.remote.cols);
239 for (line = 0; line < linecnt && line < G.height; line++) {
241 for (col = 0; col < G.remote.cols; col++, NEXT(data)) {
242 unsigned tty_col = col - G.x; // if will catch col < G.x too
244 if (tty_col >= G.width)
247 if (BW && CHAR(data) == ' ')
249 while (linefeed_cnt != 0) {
250 //bb_putchar('\r'); - tty driver does it for us
262 static void curmove(void)
264 unsigned cx = G.remote.cursor_x - G.x;
265 unsigned cy = G.remote.cursor_y - G.y;
267 if (cx >= G.width || cy >= G.height) {
276 static void cleanup(int code)
280 tcsetattr(G.kbd_fd, TCSANOW, &G.term_orig);
281 if (ENABLE_FEATURE_CLEAN_UP) {
286 fputs("\033[0m", stdout);
289 kill_myself_with_sig(code); // does not return
293 static void get_initial_data(const char* vcsa_name)
295 G.vcsa_fd = xopen(vcsa_name, O_RDONLY);
296 xread(G.vcsa_fd, &G.remote, 4);
297 G.size = G.remote.cols * G.remote.lines * 2;
298 G.width = G.height = UINT_MAX;
299 G.data = xzalloc(2 * G.size);
303 static void create_cdev_if_doesnt_exist(const char* name, dev_t dev)
305 int fd = open(name, O_RDONLY);
308 else if (errno == ENOENT)
309 mknod(name, S_IFCHR | 0660, dev);
312 static NOINLINE void start_shell_in_child(const char* tty_name)
316 bb_perror_msg_and_die("vfork");
319 struct termios termchild;
320 char *shell = getenv("SHELL");
323 shell = (char *) DEFAULT_SHELL;
324 signal(SIGHUP, SIG_IGN);
325 // set tty as a controlling tty
327 // make tty to be input, output, error
329 xopen(tty_name, O_RDWR); // uses fd 0
332 ioctl(0, TIOCSCTTY, 1);
333 tcsetpgrp(0, getpid());
334 tcgetattr(0, &termchild);
335 termchild.c_lflag |= ECHO;
336 termchild.c_oflag |= ONLCR | XTABS;
337 termchild.c_iflag |= ICRNL;
338 termchild.c_iflag &= ~IXOFF;
339 tcsetattr_stdin_TCSANOW(&termchild);
340 execl(shell, shell, "-i", (char *) NULL);
341 bb_simple_perror_msg_and_die(shell);
345 int conspy_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
346 int conspy_main(int argc UNUSED_PARAM, char **argv)
348 char vcsa_name[sizeof("/dev/vcsaNN")];
349 char tty_name[sizeof("/dev/ttyNN")];
350 #define keybuf bb_common_bufsiz1
351 struct termios termbuf;
356 static const char getopt_longopts[] ALIGN1 =
357 "viewonly\0" No_argument "v"
358 "createdevice\0" No_argument "c"
359 "session\0" No_argument "s"
360 "nocolors\0" No_argument "n"
361 "dump\0" No_argument "d"
362 "follow\0" No_argument "f"
365 applet_long_options = getopt_longopts;
368 strcpy(vcsa_name, "/dev/vcsa");
370 opt_complementary = "x+:y+"; // numeric params
371 opts = getopt32(argv, "vcsndfx:y:", &G.x, &G.y);
375 ttynum = xatou_range(argv[0], 0, 63);
376 sprintf(vcsa_name + sizeof("/dev/vcsa")-1, "%u", ttynum);
378 sprintf(tty_name, "%s%u", "/dev/tty", ttynum);
379 if (opts & FLAG(c)) {
380 if ((opts & (FLAG(s)|FLAG(v))) != FLAG(v))
381 create_cdev_if_doesnt_exist(tty_name, makedev(4, ttynum));
382 create_cdev_if_doesnt_exist(vcsa_name, makedev(7, 128 + ttynum));
384 if ((opts & FLAG(s)) && ttynum) {
385 start_shell_in_child(tty_name);
388 get_initial_data(vcsa_name);
389 if (opts & FLAG(d)) {
395 bb_signals(BB_FATAL_SIGS, cleanup);
397 // All characters must be passed through to us unaltered
398 G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
399 tcgetattr(G.kbd_fd, &G.term_orig);
400 termbuf = G.term_orig;
401 termbuf.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
402 //termbuf.c_oflag &= ~(OPOST); - no, we still want \n -> \r\n
403 termbuf.c_lflag &= ~(ISIG|ICANON|ECHO);
404 termbuf.c_cc[VMIN] = 1;
405 termbuf.c_cc[VTIME] = 0;
406 tcsetattr(G.kbd_fd, TCSANOW, &termbuf);
408 poll_timeout_ms = 250;
415 // Close & re-open vcsa in case they have
416 // swapped virtual consoles
417 G.vcsa_fd = xopen(vcsa_name, O_RDONLY);
418 xread(G.vcsa_fd, &G.remote, 4);
419 if (G.size != (G.remote.cols * G.remote.lines * 2)) {
424 get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
425 if ((option_mask32 & FLAG(f))) {
426 int nx = G.remote.cursor_x - G.width + 1;
427 int ny = G.remote.cursor_y - G.height + 1;
429 if (G.remote.cursor_x < G.x) {
430 G.x = G.remote.cursor_x;
431 i = 0; // force refresh
435 i = 0; // force refresh
437 if (G.remote.cursor_y < G.y) {
438 G.y = G.remote.cursor_y;
439 i = 0; // force refresh
443 i = 0; // force refresh
447 // Scan console data and redraw our tty where needed
448 old = G.data + G.current;
449 G.current = G.size - G.current;
450 data = G.data + G.current;
452 if (i != G.width || j != G.height) {
456 // For each remote line
457 old += G.y * G.remote.cols * 2;
458 data += G.y * G.remote.cols * 2;
459 for (i = G.y; i < G.remote.lines; i++) {
460 char *first = NULL; // first char which needs updating
461 char *last = last; // last char which needs updating
462 unsigned iy = i - G.y;
468 for (j = G.x; j < G.remote.cols; j++, NEXT(old), NEXT(data)) {
469 unsigned jx = j - G.x;
471 if (jx < G.width && DATA(data) != DATA(old)) {
480 // Rewrite updated data on the local screen
481 for (; first <= last; NEXT(first))
488 // Wait for local user keypresses
492 switch (poll(&pfd, 1, poll_timeout_ms)) {
500 G.nokeys = G.escape_count = 0;
503 // Read the keys pressed
504 k = keybuf + G.key_count;
505 bytes_read = read(G.kbd_fd, k, sizeof(keybuf) - G.key_count);
509 // Do exit processing
510 for (i = 0; i < bytes_read; i++) {
513 else if (++G.escape_count >= 3)
517 poll_timeout_ms = 250;
519 // Insert all keys pressed into the virtual console's input
520 // buffer. Don't do this if the virtual console is in scan
521 // code mode - giving ASCII characters to a program expecting
522 // scan codes will confuse it.
523 if (!(option_mask32 & FLAG(v)) && G.escape_count == 0) {
527 G.key_count += bytes_read;
528 handle = xopen(tty_name, O_WRONLY);
529 result = ioctl(handle, KDGKBMODE, &kbd_mode);
532 else if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE)
533 G.key_count = 0; // scan code mode
535 for (i = 0; i < G.key_count && result != -1; i++)
536 result = ioctl(handle, TIOCSTI, keybuf + i);
539 memmove(keybuf, keybuf + i, G.key_count);
540 // If there is an application on console which reacts
541 // to keypresses, we need to make our first sleep
542 // shorter to quickly redraw whatever it printed there.
543 poll_timeout_ms = 20;
545 // Close & re-open tty in case they have
546 // swapped virtual consoles
549 // We sometimes get spurious IO errors on the TTY
550 // as programs close and re-open it
553 else if (errno != EIO || ++G.ioerror_count > 4)