1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
/* con device */
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
struct termios save;
void
host(int fd)
{
int cc;
char buf[128];
for (;;) {
cc = read(fd, buf, sizeof buf);
#ifdef HEX
if (cc < 0)
break;
for (int i = 0; i < cc; ++i) {
char hex[3];
sprintf(hex, "%02X", (unsigned char) buf[i]);
write(1, hex, 2);
}
#else
if (cc > 0)
write(1, buf, cc);
else if (cc < 0)
break;
#endif
}
}
void
hup(int signo)
{
write(1, "HUP\n", 4);
tcsetattr(0, TCSADRAIN, &save);
_exit(0);
}
void
user(int fd)
{
char c, last = '\r';
signal(SIGHUP, hup);
for (;;)
while (read(0, &c, 1) > 0) {
if (c == '~' && (last == '\n' || last == '\r'
|| last == 4)) {
read(0, &c, 1);
if (c == '.')
return;
}
write(fd, &c, 1);
last = c;
}
}
int
main(int argc, char *argv[])
{
int fd;
pid_t pid;
struct termios t;
if (argc != 2)
exit(1);
fd = open(argv[1], O_RDWR | O_NDELAY);
if (fd < 0)
exit(2);
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NDELAY);
tcgetattr(fd, &t);
t.c_cc[VMIN] = 1;
t.c_cc[VTIME] = 0;
tcsetattr(fd, TCSADRAIN, &t);
tcgetattr(0, &t);
save = t;
t.c_iflag = 0;
t.c_oflag = 0;
t.c_lflag = 0;
t.c_cc[VMIN] = 1;
t.c_cc[VTIME] = 0;
tcsetattr(0, TCSADRAIN, &t);
if ((pid = fork()) > 0) {
user(fd);
} else if (pid == 0) {
host(fd);
} else {
perror("fork");
_exit(EXIT_FAILURE);
}
tcsetattr(0, TCSADRAIN, &save);
kill(pid, SIGKILL);
close(fd);
_exit(EXIT_SUCCESS);
}
|