-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevil-example.js
137 lines (111 loc) · 2.84 KB
/
evil-example.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
let { netcat } = require('.');
class Server {
constructor(port) {
this.stage = 'methodLn';
this.reqHeaders = {};
this.reqBody = '';
let nc = netcat('-l', '-p', port);
// Prevent inheritting Node's stdin.
// We need to write to netcat's stdin to respond
// to requests.
nc.spawnConf.stdin = 'pipe';
let firstLineReceived;
this.firstLineReceived = new Promise(resolve => {
firstLineReceived = resolve;
});
this.promise = nc.forEach((ln, i) => {
if (i === 0) {
firstLineReceived();
this.res = nc.proc.stdin;
}
return this[this.stage](ln);
});
}
get contentLength() {
return Number(this.reqHeaders['content-length'] || 0);
}
respond() {
let resBody;
if (this.reqBody) {
resBody = 'Echo: ' + this.reqBody;
}
else {
resBody = `
<input name="input">
<button onclick="send()">Send</button>
<script>
function send() {
fetch('/', {
method: 'post',
headers: {
'content-type': 'text/plain',
},
body: document.querySelector('input').value + '\\n',
})
.then(res => res.text())
.then(body => {
document.querySelector('pre').appendChild(
document.createTextNode(body)
);
})
.catch(console.error.bind(console));
}
</script>
<pre></pre>
`;
}
let { res } = this;
res.write(`HTTP/1.0 200 OK\n`);
res.write(`Content-Type: text/html\n`);
res.write(`Content-Length: ${resBody.length}\n`);
res.write(`\n`);
res.write(resBody);
res.end();
}
methodLn(ln) {
console.log(ln);
[this.method, this.path] = ln.split(' ');
this.stage = 'headerLn';
}
headerLn(ln) {
ln = ln.trim();
if (ln) {
let [name, val] = ln.split(':')
.map(x => x.trim());
this.reqHeaders[name.toLowerCase()] = val;
}
else if (this.reqHeaders['content-length']) {
this.stage = 'contentLn';
}
else {
this.stage = 'shutUp';
this.respond();
}
}
contentLn(ln) {
this.reqBody += `${ln}\n`;
if (this.reqBody.length >= this.contentLength) {
this.stage = 'shutUp';
this.respond();
}
}
then(...args) {
return this.promise.then(...args);
}
catch(...args) {
return this.promise.catch(...args);
}
}
async function main() {
while(true) {
let server = new Server(process.env.PORT || 3000);
// Log errors.
server.catch(console.error);
// As soon as a connection is established, netcat
// stops listening for new connections. Wait until
// first line of request is received, then loop
// (start a new server).
await server.firstLineReceived;
}
}
main().catch(console.error);