0a5fdccadd93e9c6df85f138dd6353af28cf4509
[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         char 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         if (!BW && G.last_attr != ATTR(data)) {
116                 //                            BLGCRMOW
117                 static const char color[8] = "04261537";
118
119                 printf("\033[%c;4%c;3%cm",
120                         (ATTR(data) & 8) ? '1'  // bold
121                                          : '0', // defaults
122                         color[(ATTR(data) >> 4) & 7], color[ATTR(data) & 7]);
123                 G.last_attr = ATTR(data);
124         }
125         bb_putchar(CHAR(data));
126 }
127
128 #define clrscr()  printf("\033[1;1H" "\033[0J")
129 #define curoff()  printf("\033[?25l")
130
131 static void curon(void)
132 {
133         printf("\033[?25h");
134 }
135
136 static void gotoxy(int row, int line)
137 {
138         printf("\033[%u;%uH", line + 1, row + 1);
139 }
140
141 static void screen_dump(void)
142 {
143         int linefeed_cnt;
144         int line, row;
145         int linecnt = G.info.lines - G.y;
146         char *data = G.data + G.current + (2 * G.y * G.info.rows);
147
148         linefeed_cnt = 0;
149         for (line = 0; line < linecnt && line < G.height; line++) {
150                 int space_cnt = 0;
151                 for (row = 0; row < G.info.rows; row++, NEXT(data)) {
152                         unsigned tty_row = row - G.x; // if will catch row < G.x too
153
154                         if (tty_row >= G.width)
155                                 continue;
156                         space_cnt++;
157                         if (BW && (CHAR(data) | ' ') == ' ')
158                                 continue;
159                         while (linefeed_cnt != 0) {
160                                 bb_putchar('\r');
161                                 bb_putchar('\n');
162                                 linefeed_cnt--;
163                         }
164                         while (--space_cnt)
165                                 bb_putchar(' ');
166                         screen_char(data);
167                 }
168                 linefeed_cnt++;
169         }
170 }
171
172 static void curmove(void)
173 {
174         unsigned cx = G.info.cursor_x - G.x;
175         unsigned cy = G.info.cursor_y - G.y;
176
177         if (cx >= G.width || cy >= G.height) {
178                 curoff();
179         } else {
180                 curon();
181                 gotoxy(cx, cy);
182         }
183         fflush_all();
184 }
185
186 static void cleanup(int code)
187 {
188         curon();
189         fflush_all();
190         tcsetattr(G.kbd_fd, TCSANOW, &G.term_orig);
191         if (ENABLE_FEATURE_CLEAN_UP) {
192                 free(ptr_to_globals);
193                 close(G.kbd_fd);
194         }
195         // Reset attributes
196         if (!BW)
197                 printf("\033[0m");
198         bb_putchar('\n');
199         if (code > 1)
200                 kill_myself_with_sig(code); // does not return
201         exit(code);
202 }
203
204 static void get_initial_data(const char* vcsa_name)
205 {
206         int size;
207         G.vcsa_fd = xopen(vcsa_name, O_RDONLY);
208         xread(G.vcsa_fd, &G.info, 4);
209         G.size = size = G.info.rows * G.info.lines * 2;
210         G.width = G.height = UINT_MAX;
211         G.data = xzalloc(2 * size);
212         screen_read_close();
213 }
214
215 static void create_cdev_if_doesnt_exist(const char* name, dev_t dev)
216 {
217         int fd = open(name, O_RDONLY);
218         if (fd != -1)
219                 close(fd);
220         else if (errno == ENOENT)
221                 mknod(name, S_IFCHR | 0660, dev);
222 }
223
224 static NOINLINE void start_shell_in_child(const char* tty_name)
225 {
226         int pid = vfork();
227         if (pid < 0) {
228                 bb_perror_msg_and_die("vfork");
229         }
230         if (pid == 0) {
231                 struct termios termchild;
232                 char *shell = getenv("SHELL");
233
234                 if (!shell)
235                         shell = (char *) DEFAULT_SHELL;
236                 signal(SIGHUP, SIG_IGN);
237                 // set tty as a controlling tty
238                 setsid();
239                 // make tty to be input, output, error
240                 close(0);
241                 xopen(tty_name, O_RDWR); // uses fd 0
242                 xdup2(0, 1);
243                 xdup2(0, 2);
244                 ioctl(0, TIOCSCTTY, 1);
245                 tcsetpgrp(0, getpid());
246                 tcgetattr(0, &termchild);
247                 termchild.c_lflag |= ECHO;
248                 termchild.c_oflag |= ONLCR | XTABS;
249                 termchild.c_iflag |= ICRNL;
250                 termchild.c_iflag &= ~IXOFF;
251                 tcsetattr_stdin_TCSANOW(&termchild);
252                 execl(shell, shell, "-i", (char *) NULL);
253                 bb_simple_perror_msg_and_die(shell);
254         }
255 }
256
257 int conspy_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
258 int conspy_main(int argc UNUSED_PARAM, char **argv)
259 {
260         char vcsa_name[sizeof("/dev/vcsa") + 2];
261         char tty_name[sizeof("/dev/tty") + 2];
262 #define keybuf bb_common_bufsiz1
263         struct termios termbuf;
264         unsigned opts;
265         unsigned ttynum;
266         int poll_timeout_ms;
267 #if ENABLE_LONG_OPTS
268         static const char getopt_longopts[] ALIGN1 =
269                 "viewonly\0"     No_argument "v"
270                 "createdevice\0" No_argument "c"
271                 "session\0"      No_argument "s"
272                 "nocolors\0"     No_argument "n"
273                 "dump\0"         No_argument "d"
274                 "follow\0"       No_argument "f"
275                 ;
276
277         applet_long_options = getopt_longopts;
278 #endif
279         INIT_G();
280
281         opt_complementary = "x+:y+"; // numeric params
282         opts = getopt32(argv, "vcsndfx:y:", &G.x, &G.y);
283         argv += optind;
284         ttynum = 0;
285         if (argv[0]) {
286                 ttynum = xatou_range(argv[0], 0, 63);
287         }
288         sprintf(vcsa_name, "/dev/vcsa%u", ttynum);
289         sprintf(tty_name, "%s%u", "/dev/tty", ttynum);
290         if (opts & FLAG(c)) {
291                 if ((opts & (FLAG(s)|FLAG(v))) != FLAG(v))
292                         create_cdev_if_doesnt_exist(tty_name, makedev(4, ttynum));
293                 create_cdev_if_doesnt_exist(vcsa_name, makedev(7, 128 + ttynum));
294         }
295         if ((opts & FLAG(s)) && ttynum) {
296                 start_shell_in_child(tty_name);
297         }
298
299         get_initial_data(vcsa_name);
300         G.kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
301         if (opts & FLAG(d)) {
302                 screen_dump();
303                 bb_putchar('\n');
304                 if (ENABLE_FEATURE_CLEAN_UP) {
305                         free(ptr_to_globals);
306                         close(G.kbd_fd);
307                 }
308                 return 0;
309         }
310
311         bb_signals(BB_FATAL_SIGS, cleanup);
312         // All characters must be passed through to us unaltered
313         tcgetattr(G.kbd_fd, &G.term_orig);
314         termbuf = G.term_orig;
315         termbuf.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
316         termbuf.c_oflag &= ~(OPOST);
317         termbuf.c_lflag &= ~(ISIG|ICANON|ECHO);
318         termbuf.c_cc[VMIN] = 1;
319         termbuf.c_cc[VTIME] = 0;
320         tcsetattr(G.kbd_fd, TCSANOW, &termbuf);
321         poll_timeout_ms = 250;
322         while (1) {
323                 struct pollfd pfd;
324                 int bytes_read;
325                 int i, j;
326                 char *data, *old;
327
328                 old = G.data + G.current;
329                 G.current = G.size - G.current;
330                 data = G.data + G.current;
331                 
332                 // Close & re-open vcsa in case they have
333                 // swapped virtual consoles
334                 G.vcsa_fd = xopen(vcsa_name, O_RDONLY);
335                 xread(G.vcsa_fd, &G.info, 4);
336                 if (G.size != (G.info.rows * G.info.lines * 2)) {
337                         cleanup(1);
338                 }
339                 i = G.width;
340                 j = G.height;
341                 get_terminal_width_height(G.kbd_fd, &G.width, &G.height);
342                 if ((option_mask32 & FLAG(f))) {
343                         int nx = G.info.cursor_x - G.width + 1;
344                         int ny = G.info.cursor_y - G.height + 1;
345
346                         if (G.info.cursor_x < G.x) {
347                                 G.x = G.info.cursor_x;
348                                 i = 0;  // force refresh
349                         }
350                         if (nx > G.x) {
351                                 G.x = nx;
352                                 i = 0;  // force refresh
353                         }
354                         if (G.info.cursor_y < G.y) {
355                                 G.y = G.info.cursor_y;
356                                 i = 0;  // force refresh
357                         }
358                         if (ny > G.y) {
359                                 G.y = ny;
360                                 i = 0;  // force refresh
361                         }
362                 }
363
364                 // Scan console data and redraw our tty where needed
365                 screen_read_close();
366                 if (i != G.width || j != G.height) {
367                         clrscr();
368                         screen_dump();
369                 }
370                 else for (i = 0; i < G.info.lines; i++) {
371                         char *last = last;
372                         char *first = NULL;
373                         int iy = i - G.y;
374
375                         if (iy >= (int) G.height)
376                                 break;
377                         for (j = 0; j < G.info.rows; j++) {
378                                 last = data;
379                                 if (DATA(data) != DATA(old) && iy >= 0) {
380                                         unsigned jx = j - G.x;
381
382                                         last = NULL;
383                                         if (first == NULL && jx < G.width) {
384                                                 first = data;
385                                                 gotoxy(jx, iy);
386                                         }
387                                 }
388                                 NEXT(old);
389                                 NEXT(data);
390                         }
391                         if (first == NULL)
392                                 continue;
393                         if (last == NULL)
394                                 last = data;
395
396                         // Write the data to the screen
397                         for (; first < last; NEXT(first))
398                                 screen_char(first);
399                 }
400                 curmove();
401
402                 // Wait for local user keypresses
403                 pfd.fd = G.kbd_fd;
404                 pfd.events = POLLIN;
405                 bytes_read = 0;
406                 switch (poll(&pfd, 1, poll_timeout_ms)) {
407                         char *k;
408                 case -1:
409                         if (errno != EINTR)
410                                 cleanup(1);
411                         break;
412                 case 0:
413                         if (++G.nokeys >= 4)
414                                 G.nokeys = G.escape_count = 0;
415                         break;
416                 default:
417                         // Read the keys pressed
418                         k = keybuf + G.key_count;
419                         bytes_read = read(G.kbd_fd, k, sizeof(keybuf) - G.key_count);
420                         if (bytes_read < 0)
421                                 cleanup(1);
422
423                         // Do exit processing
424                         for (i = 0; i < bytes_read; i++) {
425                                 if (k[i] != '\033') G.escape_count = 0;
426                                 else if (++G.escape_count >= 3)
427                                         cleanup(0);
428                         }
429                 }
430                 poll_timeout_ms = 250;
431
432                 // Insert all keys pressed into the virtual console's input
433                 // buffer.  Don't do this if the virtual console is in scan
434                 // code mode - giving ASCII characters to a program expecting
435                 // scan codes will confuse it.
436                 if (!(option_mask32 & FLAG(v)) && G.escape_count == 0) {
437                         int handle, result;
438                         long kbd_mode;
439
440                         G.key_count += bytes_read;
441                         handle = xopen(tty_name, O_WRONLY);
442                         result = ioctl(handle, KDGKBMODE, &kbd_mode);
443                         if (result == -1)
444                                 /* nothing */;
445                         else if (kbd_mode != K_XLATE && kbd_mode != K_UNICODE)
446                                 G.key_count = 0; // scan code mode
447                         else {
448                                 for (i = 0; i < G.key_count && result != -1; i++)
449                                         result = ioctl(handle, TIOCSTI, keybuf + i);
450                                 G.key_count -= i;
451                                 if (G.key_count)
452                                         memmove(keybuf, keybuf + i, G.key_count);
453                                 // If there is an application on console which reacts
454                                 // to keypresses, we need to make our first sleep
455                                 // shorter to quickly redraw whatever it printed there.
456                                 poll_timeout_ms = 20;
457                         }
458                         // Close & re-open tty in case they have
459                         // swapped virtual consoles
460                         close(handle);
461
462                         // We sometimes get spurious IO errors on the TTY
463                         // as programs close and re-open it
464                         if (result != -1)
465                                 G.ioerror_count = 0;
466                         else if (errno != EIO || ++G.ioerror_count > 4)
467                                 cleanup(1);
468                 }
469         }
470 }