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"
20 //config: depends on PLATFORM_LINUX
22 //config: A text-mode VNC like program for Linux virtual terminals.
23 //config: example: conspy NUM shared access to console num
24 //config: or conspy -nd NUM screenshot of console num
25 //config: or conspy -cs NUM poor man's GNU screen like
27 //usage:#define conspy_trivial_usage
28 //usage: "[-vcsndf] [-x COL] [-y LINE] [CONSOLE_NO]"
29 //usage:#define conspy_full_usage "\n\n"
30 //usage: "A text-mode VNC like program for Linux virtual consoles."
31 //usage: "\nTo exit, quickly press ESC 3 times."
34 //usage: "\n -v Don't send keystrokes to the console"
35 //usage: "\n -c Create missing devices in /dev"
36 //usage: "\n -s Open a SHELL session"
37 //usage: "\n -n Black & white"
38 //usage: "\n -d Dump console to stdout"
39 //usage: "\n -f Follow cursor"
40 //usage: "\n -x COL Starting column"
41 //usage: "\n -y LINE Starting line"
47 unsigned char lines, cols, cursor_x, cursor_y;
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))
65 int first_line_offset;
67 // cached local tty parameters
72 smallint curoff; // unknown:0 cursor on:-1 cursor off:1
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;
78 char vcsa_name[sizeof("/dev/vcsaNN")];
81 #define G (*ptr_to_globals)
82 #define INIT_G() do { \
83 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
84 G.attrbuf[0] = '\033'; \
86 G.width = G.height = UINT_MAX; \
92 FLAG_c, // create device if need
95 FLAG_d, // dump screen
96 FLAG_f, // follow cursor
98 #define FLAG(x) (1 << FLAG_##x)
99 #define BW (option_mask32 & FLAG(n))
101 static void clrscr(void)
103 // Home, clear till end of screen
104 fputs("\033[1;1H" "\033[J", stdout);
108 static void set_cursor(int state)
110 if (G.curoff != state) {
112 fputs("\033[?25", stdout);
113 bb_putchar("h?l"[1 + state]);
117 static void gotoxy(int col, int line)
119 if (G.col != col || G.line != line) {
122 printf("\033[%u;%uH", line + 1, col + 1);
126 static void cleanup(int code)
128 set_cursor(-1); // cursor on
129 tcsetattr(G.kbd_fd, TCSANOW, &G.term_orig);
130 if (ENABLE_FEATURE_CLEAN_UP) {
135 fputs("\033[0m", stdout);
138 kill_myself_with_sig(code);
142 static void screen_read_close(void)
148 // Close & re-open vcsa in case they have swapped virtual consoles
149 vcsa_fd = xopen(G.vcsa_name, O_RDONLY);
150 xread(vcsa_fd, &G.remote, 4);
151 i = G.remote.cols * 2;
152 G.first_line_offset = G.y * i;
154 if (G.data == NULL) {
156 G.data = xzalloc(2 * i);
158 else if (G.size != i) {
161 data = G.data + G.current;
162 xread(vcsa_fd, data, G.size);
164 for (i = 0; i < G.remote.lines; i++) {
165 for (j = 0; j < G.remote.cols; j++, NEXT(data)) {
166 unsigned x = j - G.x; // if will catch j < G.x too
167 unsigned y = i - G.y; // if will catch i < G.y too
169 if (CHAR(data) < ' ')
171 if (y >= G.height || x >= G.width)
177 static void screen_char(char *data)
180 uint8_t attr = ATTR(data);
181 //uint8_t attr = ATTR(data) >> 1; // for framebuffer console
182 uint8_t attr_diff = G.last_attr ^ attr;
185 // Attribute layout for VGA compatible text videobuffer:
191 // 00000000 <- lsb bit on the right
192 // bold text / text 8th bit
196 // TODO: apparently framebuffer-based console uses different layout
197 // (bug? attempt to get 8th text bit in better position?)
202 // 00000000 <- lsb bit on the right
208 // converting RGB color bit triad to BGR:
209 static const char color[8] = "04261537";
210 const uint8_t fg_mask = 0x07, bold_mask = 0x08;
211 const uint8_t bg_mask = 0x70, blink_mask = 0x80;
214 ptr = G.attrbuf + 2; // skip "ESC ["
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
223 *ptr++ = '0'; // "reset all attrs"
225 // must set fg & bg, maybe need to set bold or blink:
226 attr_diff = attr | ~(bold_mask | blink_mask);
229 if (attr_diff & bold_mask) {
233 if (attr_diff & blink_mask) {
237 if (attr_diff & fg_mask) {
239 *ptr++ = color[attr & fg_mask];
242 if (attr_diff & bg_mask) {
244 *ptr++ = color[(attr & bg_mask) >> 4];
247 if (ptr != G.attrbuf + 2) {
250 fputs(G.attrbuf, stdout);
258 static void screen_dump(void)
262 int linecnt = G.remote.lines - G.y;
263 char *data = G.data + G.current + G.first_line_offset;
266 for (line = 0; line < linecnt && line < G.height; line++) {
268 for (col = 0; col < G.remote.cols; col++, NEXT(data)) {
269 unsigned tty_col = col - G.x; // if will catch col < G.x too
271 if (tty_col >= G.width)
274 if (BW && CHAR(data) == ' ')
276 while (linefeed_cnt != 0) {
277 //bb_putchar('\r'); - tty driver does it for us
289 static void curmove(void)
291 unsigned cx = G.remote.cursor_x - G.x;
292 unsigned cy = G.remote.cursor_y - G.y;
295 if (cx < G.width && cy < G.height) {
302 static void create_cdev_if_doesnt_exist(const char* name, dev_t dev)
304 int fd = open(name, O_RDONLY);
307 else if (errno == ENOENT)
308 mknod(name, S_IFCHR | 0660, dev);
311 static NOINLINE void start_shell_in_child(const char* tty_name)
315 struct termios termchild;
316 char *shell = getenv("SHELL");
319 shell = (char *) DEFAULT_SHELL;
320 signal(SIGHUP, SIG_IGN);
321 // set tty as a controlling tty
323 // make tty to be input, output, error
325 xopen(tty_name, O_RDWR); // uses fd 0
328 ioctl(0, TIOCSCTTY, 1);
329 tcsetpgrp(0, getpid());
330 tcgetattr(0, &termchild);
331 termchild.c_lflag |= ECHO;
332 termchild.c_oflag |= ONLCR | XTABS;
333 termchild.c_iflag |= ICRNL;
334 termchild.c_iflag &= ~IXOFF;
335 tcsetattr_stdin_TCSANOW(&termchild);
336 execl(shell, shell, "-i", (char *) NULL);
337 bb_simple_perror_msg_and_die(shell);
341 int conspy_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
342 int conspy_main(int argc UNUSED_PARAM, char **argv)
344 char tty_name[sizeof("/dev/ttyNN")];
345 #define keybuf bb_common_bufsiz1
346 struct termios termbuf;
351 static const char getopt_longopts[] ALIGN1 =
352 "viewonly\0" No_argument "v"
353 "createdevice\0" No_argument "c"
354 "session\0" No_argument "s"
355 "nocolors\0" No_argument "n"
356 "dump\0" No_argument "d"
357 "follow\0" No_argument "f"
360 applet_long_options = getopt_longopts;
363 strcpy(G.vcsa_name, "/dev/vcsa");
365 opt_complementary = "x+:y+"; // numeric params
366 opts = getopt32(argv, "vcsndfx:y:", &G.x, &G.y);
370 ttynum = xatou_range(argv[0], 0, 63);
371 sprintf(G.vcsa_name + sizeof("/dev/vcsa")-1, "%u", ttynum);
373 sprintf(tty_name, "%s%u", "/dev/tty", ttynum);
374 if (opts & FLAG(c)) {
375 if ((opts & (FLAG(s)|FLAG(v))) != FLAG(v))
376 create_cdev_if_doesnt_exist(tty_name, makedev(4, ttynum));
377 create_cdev_if_doesnt_exist(G.vcsa_name, makedev(7, 128 + ttynum));
379 if ((opts & FLAG(s)) && ttynum) {
380 start_shell_in_child(tty_name);
384 if (opts & FLAG(d)) {
390 bb_signals(BB_FATAL_SIGS, cleanup);
392 // All characters must be passed through to us unaltered
393 G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
394 tcgetattr(G.kbd_fd, &G.term_orig);
395 termbuf = G.term_orig;
396 termbuf.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
397 //termbuf.c_oflag &= ~(OPOST); - no, we still want \n -> \r\n
398 termbuf.c_lflag &= ~(ISIG|ICANON|ECHO);
399 termbuf.c_cc[VMIN] = 1;
400 termbuf.c_cc[VTIME] = 0;
401 tcsetattr(G.kbd_fd, TCSANOW, &termbuf);
403 poll_timeout_ms = 250;
410 // in the first loop G.width = G.height = 0: refresh
413 get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
414 if (option_mask32 & FLAG(f)) {
415 int nx = G.remote.cursor_x - G.width + 1;
416 int ny = G.remote.cursor_y - G.height + 1;
418 if (G.remote.cursor_x < G.x) {
419 G.x = G.remote.cursor_x;
420 i = 0; // force refresh
424 i = 0; // force refresh
426 if (G.remote.cursor_y < G.y) {
427 G.y = G.remote.cursor_y;
428 i = 0; // force refresh
432 i = 0; // force refresh
436 // Scan console data and redraw our tty where needed
437 old = G.data + G.current;
438 G.current = G.size - G.current;
439 data = G.data + G.current;
441 if (i != G.width || j != G.height) {
445 // For each remote line
446 old += G.first_line_offset;
447 data += G.first_line_offset;
448 for (i = G.y; i < G.remote.lines; i++) {
449 char *first = NULL; // first char which needs updating
450 char *last = last; // last char which needs updating
451 unsigned iy = i - G.y;
455 for (j = 0; j < G.remote.cols; j++, NEXT(old), NEXT(data)) {
456 unsigned jx = j - G.x; // if will catch j >= G.x too
458 if (jx < G.width && DATA(data) != DATA(old)) {
467 // Rewrite updated data on the local screen
468 for (; first <= last; NEXT(first))
475 // Wait for local user keypresses
480 switch (poll(&pfd, 1, poll_timeout_ms)) {
488 G.nokeys = G.escape_count = 0;
491 // Read the keys pressed
492 k = keybuf + G.key_count;
493 bytes_read = read(G.kbd_fd, k, sizeof(keybuf) - G.key_count);
497 // Do exit processing
498 for (i = 0; i < bytes_read; i++) {
501 else if (++G.escape_count >= 3)
505 poll_timeout_ms = 250;
507 // Insert all keys pressed into the virtual console's input
508 // buffer. Don't do this if the virtual console is in scan
509 // code mode - giving ASCII characters to a program expecting
510 // scan codes will confuse it.
511 if (!(option_mask32 & FLAG(v)) && G.escape_count == 0) {
515 G.key_count += bytes_read;
516 handle = xopen(tty_name, O_WRONLY);
517 result = ioctl(handle, KDGKBMODE, &kbd_mode);
521 if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE) {
522 G.key_count = 0; // scan code mode
524 for (; G.key_count != 0; p++, G.key_count--) {
525 result = ioctl(handle, TIOCSTI, p);
527 memmove(keybuf, p, G.key_count);
530 // If there is an application on console which reacts
531 // to keypresses, we need to make our first sleep
532 // shorter to quickly redraw whatever it printed there.
533 poll_timeout_ms = 20;
536 // Close & re-open tty in case they have
537 // swapped virtual consoles
540 // We sometimes get spurious IO errors on the TTY
541 // as programs close and re-open it
544 else if (errno != EIO || ++G.ioerror_count > 4)