conspy: code shrink
[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
13 //applet:IF_CONSPY(APPLET(conspy, _BB_DIR_BIN, _BB_SUID_DROP))
14
15 //kbuild:lib-$(CONFIG_CONSPY) += conspy.o
16
17 //config:config CONSPY
18 //config:       bool "conspy"
19 //config:       default n
20 //config:       help
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
25
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."
31 //usage:     "\n"
32 //usage:     "\nOptions:"
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"
41
42 #include "libbb.h"
43 #include <sys/kd.h>
44
45 struct screen_info {
46         unsigned char lines, cols, cursor_x, cursor_y;
47 };
48
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))
53
54 struct globals {
55         char* data;
56         int size;
57         int x, y;
58         int kbd_fd;
59         int vcsa_fd;
60         int ioerror_count;
61         int key_count;
62         int escape_count;
63         int nokeys;
64         int current;
65         // cached local tty parameters
66         unsigned width;
67         unsigned height;
68         unsigned col;
69         unsigned line;
70         smallint curoff;
71         uint8_t last_attr;
72         uint8_t force_attr_change;
73         char attrbuf[sizeof("\033[0;1;5;30;40m")];
74         // remote console
75         struct screen_info remote;
76         // saved local tty terminfo
77         struct termios term_orig;
78 };
79
80 #define G (*ptr_to_globals)
81 #define INIT_G() do { \
82         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
83         G.attrbuf[0] = '\033'; \
84         G.attrbuf[1] = '['; \
85         G.force_attr_change = 0xff; \
86 } while (0)
87
88 enum {
89         FLAG_v,  // view only
90         FLAG_c,  // create device if need
91         FLAG_s,  // session
92         FLAG_n,  // no colors
93         FLAG_d,  // dump screen
94         FLAG_f,  // follow cursor
95 };
96 #define FLAG(x) (1 << FLAG_##x)
97 #define BW (option_mask32 & FLAG(n))
98
99 static void screen_read_close(void)
100 {
101         unsigned i, j;
102         char *data = G.data + G.current;
103
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
109
110                         if (CHAR(data) < ' ')
111                                 *data = ' '; // CHAR(data) = ' ';
112                         if (y >= G.height || x >= G.width)
113                                 DATA(data) = 0;
114                 }
115         }
116         close(G.vcsa_fd);
117 }
118
119 static void screen_char(char *data)
120 {
121         if (!BW) {
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;
125
126                 if (attr_diff) {
127 // Attribute layout for VGA compatible text videobuffer:
128 // blinking text
129 // |red bkgd
130 // ||green bkgd
131 // |||blue bkgd
132 // vvvv
133 // 00000000 <- lsb bit on the right
134 //     bold text / text 8th bit
135 //      red text
136 //       green text
137 //        blue text
138 // TODO: apparently framebuffer-based console uses different layout
139 // (bug? attempt to get 8th text bit in better position?)
140 // red bkgd
141 // |green bkgd
142 // ||blue bkgd
143 // vvv
144 // 00000000 <- lsb bit on the right
145 //    bold text
146 //     red text
147 //      green text
148 //       blue text
149 //        text 8th bit
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;
154                         char *ptr;
155
156                         ptr = G.attrbuf + 2; /* skip "ESC [" */
157
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"
164                                 *ptr++ = ';';
165                                 // must set fg & bg, maybe need to set bold or blink:
166                                 attr_diff = attr | ~(bold_mask | blink_mask);
167                         }
168                         G.force_attr_change = 0;
169                         G.last_attr = attr;
170                         if (attr_diff & bold_mask) {
171                                 *ptr++ = '1';
172                                 *ptr++ = ';';
173                         }
174                         if (attr_diff & blink_mask) {
175                                 *ptr++ = '5';
176                                 *ptr++ = ';';
177                         }
178                         if (attr_diff & fg_mask) {
179                                 *ptr++ = '3';
180                                 *ptr++ = color[attr & fg_mask];
181                                 *ptr++ = ';';
182                         }
183                         if (attr_diff & bg_mask) {
184                                 *ptr++ = '4';
185                                 *ptr++ = color[(attr & bg_mask) >> 4];
186                                 *ptr++ = ';';
187                         }
188                         if (ptr != G.attrbuf + 2) {
189                                 ptr[-1] = 'm';
190                                 *ptr = '\0';
191                                 fputs(G.attrbuf, stdout);
192                         }
193                 }
194         }
195         putchar(CHAR(data));
196         G.col++;
197 }
198
199 static void clrscr(void)
200 {
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;
204 }
205
206 static void curoff(void)
207 {
208         if (!G.curoff) {
209                 G.curoff = 1;
210                 fputs("\033[?25l", stdout);
211         }
212 }
213
214 static void curon(void)
215 {
216         if (G.curoff) {
217                 G.curoff = 0;
218                 fputs("\033[?25h", stdout);
219         }
220 }
221
222 static void gotoxy(int col, int line)
223 {
224         if (G.col != col || G.line != line) {
225                 G.col = col;
226                 G.line = line;
227                 printf("\033[%u;%uH", line + 1, col + 1);
228         }
229 }
230
231 static void screen_dump(void)
232 {
233         int linefeed_cnt;
234         int line, col;
235         int linecnt = G.remote.lines - G.y;
236         char *data = G.data + G.current + (2 * G.y * G.remote.cols);
237
238         linefeed_cnt = 0;
239         for (line = 0; line < linecnt && line < G.height; line++) {
240                 int space_cnt = 0;
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
243
244                         if (tty_col >= G.width)
245                                 continue;
246                         space_cnt++;
247                         if (BW && CHAR(data) == ' ')
248                                 continue;
249                         while (linefeed_cnt != 0) {
250                                 //bb_putchar('\r'); - tty driver does it for us
251                                 bb_putchar('\n');
252                                 linefeed_cnt--;
253                         }
254                         while (--space_cnt)
255                                 bb_putchar(' ');
256                         screen_char(data);
257                 }
258                 linefeed_cnt++;
259         }
260 }
261
262 static void curmove(void)
263 {
264         unsigned cx = G.remote.cursor_x - G.x;
265         unsigned cy = G.remote.cursor_y - G.y;
266
267         if (cx >= G.width || cy >= G.height) {
268                 curoff();
269         } else {
270                 curon();
271                 gotoxy(cx, cy);
272         }
273         fflush_all();
274 }
275
276 static void cleanup(int code)
277 {
278         curon();
279         fflush_all();
280         tcsetattr(G.kbd_fd, TCSANOW, &G.term_orig);
281         if (ENABLE_FEATURE_CLEAN_UP) {
282                 close(G.kbd_fd);
283         }
284         // Reset attributes
285         if (!BW)
286                 fputs("\033[0m", stdout);
287         bb_putchar('\n');
288         if (code > 1)
289                 kill_myself_with_sig(code); // does not return
290         exit(code);
291 }
292
293 static void get_initial_data(const char* vcsa_name)
294 {
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);
300         screen_read_close();
301 }
302
303 static void create_cdev_if_doesnt_exist(const char* name, dev_t dev)
304 {
305         int fd = open(name, O_RDONLY);
306         if (fd != -1)
307                 close(fd);
308         else if (errno == ENOENT)
309                 mknod(name, S_IFCHR | 0660, dev);
310 }
311
312 static NOINLINE void start_shell_in_child(const char* tty_name)
313 {
314         int pid = vfork();
315         if (pid < 0) {
316                 bb_perror_msg_and_die("vfork");
317         }
318         if (pid == 0) {
319                 struct termios termchild;
320                 char *shell = getenv("SHELL");
321
322                 if (!shell)
323                         shell = (char *) DEFAULT_SHELL;
324                 signal(SIGHUP, SIG_IGN);
325                 // set tty as a controlling tty
326                 setsid();
327                 // make tty to be input, output, error
328                 close(0);
329                 xopen(tty_name, O_RDWR); // uses fd 0
330                 xdup2(0, 1);
331                 xdup2(0, 2);
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);
342         }
343 }
344
345 int conspy_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
346 int conspy_main(int argc UNUSED_PARAM, char **argv)
347 {
348         char vcsa_name[sizeof("/dev/vcsaNN")];
349         char tty_name[sizeof("/dev/ttyNN")];
350 #define keybuf bb_common_bufsiz1
351         struct termios termbuf;
352         unsigned opts;
353         unsigned ttynum;
354         int poll_timeout_ms;
355 #if ENABLE_LONG_OPTS
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"
363                 ;
364
365         applet_long_options = getopt_longopts;
366 #endif
367         INIT_G();
368         strcpy(vcsa_name, "/dev/vcsa");
369
370         opt_complementary = "x+:y+"; // numeric params
371         opts = getopt32(argv, "vcsndfx:y:", &G.x, &G.y);
372         argv += optind;
373         ttynum = 0;
374         if (argv[0]) {
375                 ttynum = xatou_range(argv[0], 0, 63);
376                 sprintf(vcsa_name + sizeof("/dev/vcsa")-1, "%u", ttynum);
377         }
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));
383         }
384         if ((opts & FLAG(s)) && ttynum) {
385                 start_shell_in_child(tty_name);
386         }
387
388         get_initial_data(vcsa_name);
389         if (opts & FLAG(d)) {
390                 screen_dump();
391                 bb_putchar('\n');
392                 return 0;
393         }
394
395         bb_signals(BB_FATAL_SIGS, cleanup);
396
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);
407
408         poll_timeout_ms = 250;
409         while (1) {
410                 struct pollfd pfd;
411                 int bytes_read;
412                 int i, j;
413                 char *data, *old;
414
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)) {
420                         cleanup(1);
421                 }
422                 i = G.width;
423                 j = G.height;
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;
428
429                         if (G.remote.cursor_x < G.x) {
430                                 G.x = G.remote.cursor_x;
431                                 i = 0;  // force refresh
432                         }
433                         if (nx > G.x) {
434                                 G.x = nx;
435                                 i = 0;  // force refresh
436                         }
437                         if (G.remote.cursor_y < G.y) {
438                                 G.y = G.remote.cursor_y;
439                                 i = 0;  // force refresh
440                         }
441                         if (ny > G.y) {
442                                 G.y = ny;
443                                 i = 0;  // force refresh
444                         }
445                 }
446
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;
451                 screen_read_close();
452                 if (i != G.width || j != G.height) {
453                         clrscr();
454                         screen_dump();
455                 } else {
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;
463
464                                 if (iy >= G.height)
465                                         break;
466                                 old += G.x * 2;
467                                 data += G.x * 2;
468                                 for (j = G.x; j < G.remote.cols; j++, NEXT(old), NEXT(data)) {
469                                         unsigned jx = j - G.x;
470
471                                         if (jx < G.width && DATA(data) != DATA(old)) {
472                                                 last = data;
473                                                 if (!first) {
474                                                         first = data;
475                                                         gotoxy(jx, iy);
476                                                 }
477                                         }
478                                 }
479                                 if (first) {
480                                         // Rewrite updated data on the local screen
481                                         for (; first <= last; NEXT(first))
482                                                 screen_char(first);
483                                 }
484                         }
485                 }
486                 curmove();
487
488                 // Wait for local user keypresses
489                 pfd.fd = G.kbd_fd;
490                 pfd.events = POLLIN;
491                 bytes_read = 0;
492                 switch (poll(&pfd, 1, poll_timeout_ms)) {
493                         char *k;
494                 case -1:
495                         if (errno != EINTR)
496                                 cleanup(1);
497                         break;
498                 case 0:
499                         if (++G.nokeys >= 4)
500                                 G.nokeys = G.escape_count = 0;
501                         break;
502                 default:
503                         // Read the keys pressed
504                         k = keybuf + G.key_count;
505                         bytes_read = read(G.kbd_fd, k, sizeof(keybuf) - G.key_count);
506                         if (bytes_read < 0)
507                                 cleanup(1);
508
509                         // Do exit processing
510                         for (i = 0; i < bytes_read; i++) {
511                                 if (k[i] != '\033')
512                                         G.escape_count = 0;
513                                 else if (++G.escape_count >= 3)
514                                         cleanup(0);
515                         }
516                 }
517                 poll_timeout_ms = 250;
518
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) {
524                         int handle, result;
525                         long kbd_mode;
526
527                         G.key_count += bytes_read;
528                         handle = xopen(tty_name, O_WRONLY);
529                         result = ioctl(handle, KDGKBMODE, &kbd_mode);
530                         if (result == -1)
531                                 /* nothing */;
532                         else if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE)
533                                 G.key_count = 0; // scan code mode
534                         else {
535                                 for (i = 0; i < G.key_count && result != -1; i++)
536                                         result = ioctl(handle, TIOCSTI, keybuf + i);
537                                 G.key_count -= i;
538                                 if (G.key_count)
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;
544                         }
545                         // Close & re-open tty in case they have
546                         // swapped virtual consoles
547                         close(handle);
548
549                         // We sometimes get spurious IO errors on the TTY
550                         // as programs close and re-open it
551                         if (result != -1)
552                                 G.ioerror_count = 0;
553                         else if (errno != EIO || ++G.ioerror_count > 4)
554                                 cleanup(1);
555                 }
556         }
557 }