-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex_blind.js
119 lines (105 loc) · 3.22 KB
/
index_blind.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
// This will naively match input and send output
//
const net = require('net');
const fs = require('fs');
function hexToBuffer(hex) {
const buffer = Buffer.alloc(hex.length/2);
let index = 0;
while (index < hex.length) {
const hexByte = hex.substring(index, index + 2);
buffer[index/2] = Number("0x" + hexByte);
index += 2;
}
return buffer;
}
const lines = fs.readFileSync('output_abc.txt', 'utf8').split('\n')
.map(e => e.trim())
.map((line) => {
const [_type, msg] = line.split(" ");
const out = {
"type": _type,
buffer: hexToBuffer(msg)
};
return out;
});
const server = net.createServer((socket) => {
console.log('New socket connection!');
const data = [];
function onData(buffer) {
data.push(...buffer);
}
function closeConnection() {
clearTimeout(readTimeoutId);
clearTimeout(cmdLoopTimeoutId);
socket.end();
}
let readTimeoutId = -1;
async function read(byteLength) {
return new Promise((resolve, reject) => {
const checkData = () => {
if (socket.destroyed) {
reject();
}
if (data.length >= byteLength) {
const dataSlice = data.splice(0, byteLength);
resolve(Buffer.from(dataSlice));
} else {
readTimeoutId = setImmediate(checkData);
}
};
readTimeoutId = setImmediate(checkData);
});
}
socket.on('data', onData);
let lineIndex = 0;
async function socketLoop() {
let line = lines[lineIndex];
if (line == null) {
closeConnection();
return;
}
if (line.type === 'in') {
const bufferLength = line.buffer.length;
const sentBuffer = await read(bufferLength);
for (let i = 0; i < bufferLength; i++) {
if (sentBuffer[i] !== line.buffer[i]) {
throw `Invalid buffer [${lineIndex + 1}@${i + 4}]`;
}
}
lineIndex++;
line = lines[lineIndex];
}
while (line.type === 'out') {
socket.write(line.buffer);
lineIndex++;
line = lines[lineIndex];
}
}
const cmdLoop = async () => {
try {
await socketLoop();
} catch (e) {
console.log(e);
closeConnection();
return;
}
cmdLoopTimeoutId = setImmediate(cmdLoop);
};
cmdLoopTimeoutId = setImmediate(cmdLoop);
}).on('error', (err) => {
// Handle errors here.
// throw err;
});
server.listen(744, 'localhost', 511, () => {
console.log('opened server on', server.address());
});
console.log('Started listening');
process.on('uncaughtException',function(err){
if (err.code === 'ECONNRESET') {
// ignore this
} else {
console.log('something terrible happened..');
console.log(err);
process.exit(-1);
}
});