conspy: document attribute byte format
[oweals/busybox.git] / miscutils / conspy.c
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 tarball for details.
11  *
12  * example :    conspy num              shared access to console num
13  * or           conspy -d num           screenshot of console num
14  * or           conspy -cs num          poor man's GNU screen like
15  */
16
17 //applet:IF_CONSPY(APPLET(conspy, _BB_DIR_BIN, _BB_SUID_DROP))
18
19 //kbuild:lib-$(CONFIG_CONSPY) += conspy.o
20
21 //config:config CONSPY
22 //config:       bool "conspy"
23 //config:       default n
24 //config:       help
25 //config:         A text-mode VNC like program for Linux virtual terminals.
26 //config:         example : conspy num      shared access to console num
27 //config:         or        conspy -d num   screenshot of console num
28 //config:         or        conspy -cs num  poor man's GNU screen like
29
30 //usage:#define conspy_trivial_usage
31 //usage:     "[-vcsndf] [-x ROW] [-y LINE] [CONSOLE_NO]"
32 //usage:#define conspy_full_usage "\n\n"
33 //usage:     "A text-mode VNC like program for Linux virtual consoles."
34 //usage:     "\nTo exit, quickly press ESC 3 times."
35 //usage:     "\n"
36 //usage:     "\nOptions:"
37 //usage:     "\n        -v      Don't send keystrokes to the console"
38 //usage:     "\n        -c      Create missing devices in /dev"
39 //usage:     "\n        -s      Open a SHELL session"
40 //usage:     "\n        -n      Black & white"
41 //usage:     "\n        -d      Dump console to stdout"
42 //usage:     "\n        -f      Follow cursor"
43 //usage:     "\n        -x ROW  Starting row"
44 //usage:     "\n        -y LINE Starting line"
45
46 #include "libbb.h"
47 #include <sys/kd.h>
48
49 struct screen_info {
50         unsigned char lines, rows, cursor_x, cursor_y;
51 };
52
53 #define CHAR(x) ((x)[0])
54 #define ATTR(x) ((x)[1])
55 #define NEXT(x) ((x)+=2)
56 #define DATA(x) (* (short *) (x))
57
58 struct globals {
59         char* data;
60         int size;
61         int x, y;
62         int kbd_fd;
63         unsigned width;
64         unsigned height;
65         uint8_t last_attr;
66         int ioerror_count;
67         int key_count;
68         int escape_count;
69         int nokeys;
70         int current;
71         int vcsa_fd;
72         struct screen_info info;
73         struct termios term_orig;
74 };
75
76 #define G (*ptr_to_globals)
77 #define INIT_G() do { \
78         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
79 } while (0)
80
81 enum {
82         FLAG_v,  // view only
83         FLAG_c,  // create device if need
84         FLAG_s,  // session
85         FLAG_n,  // no colors
86         FLAG_d,  // dump screen
87         FLAG_f,  // follow cursor
88 };
89 #define FLAG(x) (1 << FLAG_##x)
90 #define BW (option_mask32 & FLAG(n))
91
92 static void screen_read_close(void)
93 {
94         unsigned i, j;
95         char *data = G.data + G.current;
96
97         xread(G.vcsa_fd, data, G.size);
98         G.last_attr = 0;
99         for (i = 0; i < G.info.lines; i++) {
100                 for (j = 0; j < G.info.rows; j++, NEXT(data)) {
101                         unsigned x = j - G.x; // if will catch j < G.x too
102                         unsigned y = i - G.y; // if will catch i < G.y too
103
104                         if (CHAR(data) < ' ')
105                                 CHAR(data) = ' ';
106                         if (y >= G.height || x >= G.width)
107                                 DATA(data) = 0;
108                 }
109         }
110         close(G.vcsa_fd);
111 }
112
113 static void screen_char(char *data)
114 {
115         uint8_t attr = ATTR(data);
116
117         if (!BW && G.last_attr != attr) {
118 // Attribute layout for VGA compatible text videobuffer:
119 // blinking text
120 // |red bkgd
121 // ||green bkgd
122 // |||blue bkgd
123 // vvvv
124 // 00000000 <- lsb bit on the right
125 //     bold text / text 8th bit
126 //      red text
127 //       green text
128 //        blue text
129 // TODO: apparently framebuffer-based console uses different layout
130 // (bug? attempt to get 8th text bit in better position?)
131 // red bkgd
132 // |green bkgd
133 // ||blue bkgd
134 // vvv
135 // 00000000 <- lsb bit on the right
136 //    bold text
137 //     red text
138 //      green text
139 //       blue text
140 //        text 8th bit
141                 // converting RGB color bit triad to BGR:
142                 static const char color[8] = "04261537";
143
144                 G.last_attr = attr;
145                 printf("\033[%c;4%c;3%cm",
146                         (attr & 8) ? '1' : '0', // bold text / reset all
147                         color[(attr >> 4) & 7], // bkgd color
148                         color[attr & 7] // text color
149                 );
150         }
151         putchar(CHAR(data));
152 }
153
154 #define clrscr()  printf("\033[1;1H" "\033[0J")
155 #define curoff()  printf("\033[?25l")
156
157 static void curon(void)
158 {
159         printf("\033[?25h");
160 }
161
162 static void gotoxy(int row, int line)
163 {
164         printf("\033[%u;%uH", line + 1, row + 1);
165 }
166
167 static void screen_dump(void)
168 {
169         int linefeed_cnt;
170         int line, row;
171         int linecnt = G.info.lines - G.y;
172         char *data = G.data + G.current + (2 * G.y * G.info.rows);
173
174         linefeed_cnt = 0;
175         for (line = 0; line < linecnt && line < G.height; line++) {
176                 int space_cnt = 0;
177                 for (row = 0; row < G.info.rows; row++, NEXT(data)) {
178                         unsigned tty_row = row - G.x; // if will catch row < G.x too
179
180                         if (tty_row >= G.width)
181                                 continue;
182                         space_cnt++;
183                         if (BW && (CHAR(data) | ' ') == ' ')
184                                 continue;
185                         while (linefeed_cnt != 0) {
186                                 bb_putchar('\r');
187                                 bb_putchar('\n');
188                                 linefeed_cnt--;
189                         }
190                         while (--space_cnt)
191                                 bb_putchar(' ');
192                         screen_char(data);
193                 }
194                 linefeed_cnt++;
195         }
196 }
197
198 static void curmove(void)
199 {
200         unsigned cx = G.info.cursor_x - G.x;
201         unsigned cy = G.info.cursor_y - G.y;
202
203         if (cx >= G.width || cy >= G.height) {
204                 curoff();
205         } else {
206                 curon();
207                 gotoxy(cx, cy);
208         }
209         fflush_all();
210 }
211
212 static void cleanup(int code)
213 {
214         curon();
215         fflush_all();
216         tcsetattr(G.kbd_fd, TCSANOW, &G.term_orig);
217         if (ENABLE_FEATURE_CLEAN_UP) {
218                 free(ptr_to_globals);
219                 close(G.kbd_fd);
220         }
221         // Reset attributes
222         if (!BW)
223                 printf("\033[0m");
224         bb_putchar('\n');
225         if (code > 1)
226                 kill_myself_with_sig(code); // does not return
227         exit(code);
228 }
229
230 static void get_initial_data(const char* vcsa_name)
231 {
232         int size;
233         G.vcsa_fd = xopen(vcsa_name, O_RDONLY);
234         xread(G.vcsa_fd, &G.info, 4);
235         G.size = size = G.info.rows * G.info.lines * 2;
236         G.width = G.height = UINT_MAX;
237         G.data = xzalloc(2 * size);
238         screen_read_close();
239 }
240
241 static void create_cdev_if_doesnt_exist(const char* name, dev_t dev)
242 {
243         int fd = open(name, O_RDONLY);
244         if (fd != -1)
245                 close(fd);
246         else if (errno == ENOENT)
247                 mknod(name, S_IFCHR | 0660, dev);
248 }
249
250 static NOINLINE void start_shell_in_child(const char* tty_name)
251 {
252         int pid = vfork();
253         if (pid < 0) {
254                 bb_perror_msg_and_die("vfork");
255         }
256         if (pid == 0) {
257                 struct termios termchild;
258                 char *shell = getenv("SHELL");
259
260                 if (!shell)
261                         shell = (char *) DEFAULT_SHELL;
262                 signal(SIGHUP, SIG_IGN);
263                 // set tty as a controlling tty
264                 setsid();
265                 // make tty to be input, output, error
266                 close(0);
267                 xopen(tty_name, O_RDWR); // uses fd 0
268                 xdup2(0, 1);
269                 xdup2(0, 2);
270                 ioctl(0, TIOCSCTTY, 1);
271                 tcsetpgrp(0, getpid());
272                 tcgetattr(0, &termchild);
273                 termchild.c_lflag |= ECHO;
274                 termchild.c_oflag |= ONLCR | XTABS;
275                 termchild.c_iflag |= ICRNL;
276                 termchild.c_iflag &= ~IXOFF;
277                 tcsetattr_stdin_TCSANOW(&termchild);
278                 execl(shell, shell, "-i", (char *) NULL);
279                 bb_simple_perror_msg_and_die(shell);
280         }
281 }
282
283 int conspy_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
284 int conspy_main(int argc UNUSED_PARAM, char **argv)
285 {
286         char vcsa_name[sizeof("/dev/vcsa") + 2];
287         char tty_name[sizeof("/dev/tty") + 2];
288 #define keybuf bb_common_bufsiz1
289         struct termios termbuf;
290         unsigned opts;
291         unsigned ttynum;
292         int poll_timeout_ms;
293 #if ENABLE_LONG_OPTS
294         static const char getopt_longopts[] ALIGN1 =
295                 "viewonly\0"     No_argument "v"
296                 "createdevice\0" No_argument "c"
297                 "session\0"      No_argument "s"
298                 "nocolors\0"     No_argument "n"
299                 "dump\0"         No_argument "d"
300                 "follow\0"       No_argument "f"
301                 ;
302
303         applet_long_options = getopt_longopts;
304 #endif
305         INIT_G();
306
307         opt_complementary = "x+:y+"; // numeric params
308         opts = getopt32(argv, "vcsndfx:y:", &G.x, &G.y);
309         argv += optind;
310         ttynum = 0;
311         if (argv[0]) {
312                 ttynum = xatou_range(argv[0], 0, 63);
313         }
314         sprintf(vcsa_name, "/dev/vcsa%u", ttynum);
315         sprintf(tty_name, "%s%u", "/dev/tty", ttynum);
316         if (opts & FLAG(c)) {
317                 if ((opts & (FLAG(s)|FLAG(v))) != FLAG(v))
318                         create_cdev_if_doesnt_exist(tty_name, makedev(4, ttynum));
319                 create_cdev_if_doesnt_exist(vcsa_name, makedev(7, 128 + ttynum));
320         }
321         if ((opts & FLAG(s)) && ttynum) {
322                 start_shell_in_child(tty_name);
323         }
324
325         get_initial_data(vcsa_name);
326         G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
327         if (opts & FLAG(d)) {
328                 screen_dump();
329                 bb_putchar('\n');
330                 if (ENABLE_FEATURE_CLEAN_UP) {
331                         free(ptr_to_globals);
332                         close(G.kbd_fd);
333                 }
334                 return 0;
335         }
336
337         bb_signals(BB_FATAL_SIGS, cleanup);
338         // All characters must be passed through to us unaltered
339         tcgetattr(G.kbd_fd, &G.term_orig);
340         termbuf = G.term_orig;
341         termbuf.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
342         termbuf.c_oflag &= ~(OPOST);
343         termbuf.c_lflag &= ~(ISIG|ICANON|ECHO);
344         termbuf.c_cc[VMIN] = 1;
345         termbuf.c_cc[VTIME] = 0;
346         tcsetattr(G.kbd_fd, TCSANOW, &termbuf);
347         poll_timeout_ms = 250;
348         while (1) {
349                 struct pollfd pfd;
350                 int bytes_read;
351                 int i, j;
352                 char *data, *old;
353
354                 old = G.data + G.current;
355                 G.current = G.size - G.current;
356                 data = G.data + G.current;
357                 
358                 // Close & re-open vcsa in case they have
359                 // swapped virtual consoles
360                 G.vcsa_fd = xopen(vcsa_name, O_RDONLY);
361                 xread(G.vcsa_fd, &G.info, 4);
362                 if (G.size != (G.info.rows * G.info.lines * 2)) {
363                         cleanup(1);
364                 }
365                 i = G.width;
366                 j = G.height;
367                 get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
368                 if ((option_mask32 & FLAG(f))) {
369                         int nx = G.info.cursor_x - G.width + 1;
370                         int ny = G.info.cursor_y - G.height + 1;
371
372                         if (G.info.cursor_x < G.x) {
373                                 G.x = G.info.cursor_x;
374                                 i = 0;  // force refresh
375                         }
376                         if (nx > G.x) {
377                                 G.x = nx;
378                                 i = 0;  // force refresh
379                         }
380                         if (G.info.cursor_y < G.y) {
381                                 G.y = G.info.cursor_y;
382                                 i = 0;  // force refresh
383                         }
384                         if (ny > G.y) {
385                                 G.y = ny;
386                                 i = 0;  // force refresh
387                         }
388                 }
389
390                 // Scan console data and redraw our tty where needed
391                 screen_read_close();
392                 if (i != G.width || j != G.height) {
393                         clrscr();
394                         screen_dump();
395                 }
396                 else for (i = 0; i < G.info.lines; i++) {
397                         char *last = last;
398                         char *first = NULL;
399                         int iy = i - G.y;
400
401                         if (iy >= (int) G.height)
402                                 break;
403                         for (j = 0; j < G.info.rows; j++) {
404                                 last = data;
405                                 if (DATA(data) != DATA(old) && iy >= 0) {
406                                         unsigned jx = j - G.x;
407
408                                         last = NULL;
409                                         if (first == NULL && jx < G.width) {
410                                                 first = data;
411                                                 gotoxy(jx, iy);
412                                         }
413                                 }
414                                 NEXT(old);
415                                 NEXT(data);
416                         }
417                         if (first == NULL)
418                                 continue;
419                         if (last == NULL)
420                                 last = data;
421
422                         // Write the data to the screen
423                         for (; first < last; NEXT(first))
424                                 screen_char(first);
425                 }
426                 curmove();
427
428                 // Wait for local user keypresses
429                 pfd.fd = G.kbd_fd;
430                 pfd.events = POLLIN;
431                 bytes_read = 0;
432                 switch (poll(&pfd, 1, poll_timeout_ms)) {
433                         char *k;
434                 case -1:
435                         if (errno != EINTR)
436                                 cleanup(1);
437                         break;
438                 case 0:
439                         if (++G.nokeys >= 4)
440                                 G.nokeys = G.escape_count = 0;
441                         break;
442                 default:
443                         // Read the keys pressed
444                         k = keybuf + G.key_count;
445                         bytes_read = read(G.kbd_fd, k, sizeof(keybuf) - G.key_count);
446                         if (bytes_read < 0)
447                                 cleanup(1);
448
449                         // Do exit processing
450                         for (i = 0; i < bytes_read; i++) {
451                                 if (k[i] != '\033') G.escape_count = 0;
452                                 else if (++G.escape_count >= 3)
453                                         cleanup(0);
454                         }
455                 }
456                 poll_timeout_ms = 250;
457
458                 // Insert all keys pressed into the virtual console's input
459                 // buffer.  Don't do this if the virtual console is in scan
460                 // code mode - giving ASCII characters to a program expecting
461                 // scan codes will confuse it.
462                 if (!(option_mask32 & FLAG(v)) && G.escape_count == 0) {
463                         int handle, result;
464                         long kbd_mode;
465
466                         G.key_count += bytes_read;
467                         handle = xopen(tty_name, O_WRONLY);
468                         result = ioctl(handle, KDGKBMODE, &kbd_mode);
469                         if (result == -1)
470                                 /* nothing */;
471                         else if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE)
472                                 G.key_count = 0; // scan code mode
473                         else {
474                                 for (i = 0; i < G.key_count && result != -1; i++)
475                                         result = ioctl(handle, TIOCSTI, keybuf + i);
476                                 G.key_count -= i;
477                                 if (G.key_count)
478                                         memmove(keybuf, keybuf + i, G.key_count);
479                                 // If there is an application on console which reacts
480                                 // to keypresses, we need to make our first sleep
481                                 // shorter to quickly redraw whatever it printed there.
482                                 poll_timeout_ms = 20;
483                         }
484                         // Close & re-open tty in case they have
485                         // swapped virtual consoles
486                         close(handle);
487
488                         // We sometimes get spurious IO errors on the TTY
489                         // as programs close and re-open it
490                         if (result != -1)
491                                 G.ioerror_count = 0;
492                         else if (errno != EIO || ++G.ioerror_count > 4)
493                                 cleanup(1);
494                 }
495         }
496 }