-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
441 lines (377 loc) · 11.4 KB
/
index.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
const net = require('net');
const fs = require('fs');
function bufferToString(buffer, encoding) {
return buffer.subarray(0, buffer.indexOf(0)).toString(encoding);
}
const CMD = {
// Debug only
[0x01FF0001]: {
name: "CMD_PUSH_REPLAY_FILE",
run: function(socket, cmdArg, {replay}) {
socket.write(hexToBuffer('00000080'));
const filePath = bufferToString(cmdArg.subarray(0, 32), 'ascii');
const index = cmdArg.readUInt32LE(32);
replay.pushReplayFile(filePath, index);
socket.write(hexToBuffer('00000080'));
console.log('Done pushing!');
}
},
[0x01FF0002]: {
name: "CMD_POP_REPLAY_FILE",
run: function(socket, _, {replay}) {
socket.write(hexToBuffer('00000080'));
if (replay.popReplayFile()) {
socket.write(hexToBuffer('00000080'));
} else {
socket.write(hexToBuffer('010000F0'));
}
}
},
// regular
[0xBDAA0001]: {
name: "CMD_PROC_LIST",
run: function(socket, _, {replay}) {
// send count
let out = replay.matchOut();
socket.write(hexToBuffer(out.data));
// send out data
out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA0002]: {
name: "CMD_PROC_READ",
run: async function (socket, _, {replay}) {
const out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA0003]: {
name: "CMD_PROC_WRITE",
run: async function (socket, argBuffer, {read,replay}) {
const length = argBuffer.readUInt32LE(12);
const cmdWrite = await read(length);
replay.matchIn(cmdWrite);
const out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA0004]: {
name: "CMD_PROC_MAPS",
run: function(socket, argBuffer, {self, replay}) {
const callKey = bufferToHex(argBuffer);
// send count
let out = replay.matchOut();
socket.write(hexToBuffer(out.data));
// send data
out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA0005]: {
name: "CMD_PROC_INSTALL",
run: function(socket, argBuffer, {replay}) {
// const pid = argBuffer.readUInt32LE(0);
// send start thingy
// send start
let out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA0006]: {
name: "CMD_PROC_CALL",
run: function(socket, _, {replay}) {
// send return code
let out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA000B]: {
name: "CMD_PROC_ALLOC",
run: function(socket, argBuffer, {replay}) {
const callKey = bufferToHex(argBuffer);
let out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
},
[0xBDAA000C]: {
name: "CMD_PROC_FREE",
run: function(socket, argBuffer) {
// doesn't need to do anything
}
},
};
function parseReplayLine(line) {
line = line.trim();
let match = line.match(/\w+/);
if (!match) {
throw Error(`Must have type.`);
}
const type = match[0];
let index = 2;
line = line.substring(type.length);
index += type.length;
const args = [];
while (line.length) {
match = line.match(/\s*0x([A-F0-9]+)/);
if (!match) {
throw {char: index, message: 'Unexpected character!'};
}
args.push(match[1]);
line = line.substring(match[0].length);
index += match[0].length;
}
return {
type,
args
}
}
function processLines(lines) {
const processed = [];
for (let line of lines) {
let numberMatch = line.match(/^(\d+):/);
if (!numberMatch) {
continue;
}
line = line.substring(numberMatch[0].length);
const lineIndex = Number(numberMatch[1]);
if (!line.startsWith('(')) {
continue;
}
if (!line.endsWith(')')) {
throw Error(`${lineIndex}: Missing closing parenthesis! `);
}
let replayValue;
try {
replayValue = parseReplayLine(line.substring(1, line.length - 1));
} catch (e) {
throw Error(`${lineIndex}@${e.char}: ${e.message}`);
}
processed.push(replayValue);
}
return processed;
}
function createReplayList(lines) {
const prosLines = processLines(lines);
const list = [];
for (const prosLine of prosLines) {
const line = {
type: prosLine.type,
};
list.push(line);
switch(prosLine.type) {
case 'cmd': {
line.name = prosLine.args[0];
line.argLength = prosLine.args[1];
break;
}
case 'in':
case 'out': {
line.data = prosLine.args[0];
break;
}
default:
break;
}
}
return list;
}
const cacheReplayFiles = {
};
function Replay() {
let replayStack = [];
let currentReplay = null;
function getCurrentItem() {
if (currentReplay == null) {
throw 'currentReplay is null!';
}
const {arr, index} = currentReplay;
return arr[index];
}
function increaseIndex() {
currentReplay.index++;
}
function reset() {
currentReplay.index = 0;
}
function matchOut() {
const out = getCurrentItem();
if (out.type !== 'out') {
throw Error(`At @${currentReplay.index}: Expected <out> but got <${out.type}>.`);
}
increaseIndex();
return out;
}
function matchIn(buffer) {
let data = bufferToHex(buffer);
const ins = getCurrentItem();
if (ins.type !== 'in') {
throw Error(`At @${currentReplay.index}: Expected <in> but got <${ins.type}>.`);
}
if (ins.data !== data) {
throw Error(`At @${currentReplay.index}: ${ins.data} does not match ${data}.`);
}
increaseIndex();
return ins;
}
function matchCommand(buffer) {
const cmd = getCurrentItem();
if (cmd.type !== 'cmd') {
throw Error(`At @${currentReplay.index}: Expected <cmd> but got <${cmd.type}>.`);
}
const name = bufferToHex(buffer.subarray(0, 4));
const argLength = bufferToHex(buffer.subarray(4));
if (cmd.name !== name) {
throw Error(`At @${currentReplay.index}: ${name} does not match ${cmd.name}.`);
}
if (cmd.argLength !== argLength) {
throw Error(`At @${currentReplay.index}: ${argLength} does not match ${cmd.argLength}.`);
}
increaseIndex();
return cmd;
}
function pushReplayFile(filePath, newIndex) {
let replayArr = cacheReplayFiles[filePath];
if (!cacheReplayFiles[filePath]) {
const lines = fs.readFileSync(filePath, 'utf8').split('\n').map(e => e.trim());
replayArr = cacheReplayFiles[filePath] = createReplayList(lines);
}
if (currentReplay && currentReplay.arr == replayArr) {
currentReplay.index = newIndex;
} else {
currentReplay = {
arr: replayArr,
index: newIndex
};
replayStack.push(currentReplay);
}
}
function popReplayFile() {
let success = false;
if (replayStack.length > 1) {
replayStack.pop();
currentReplay = replayStack[replayStack.length - 1];
success = true;
}
return success;
}
return {
pushReplayFile,
popReplayFile,
matchCommand,
matchIn,
matchOut,
reset,
};
}
function bufferToHex(buffer) {
let str = "";
if (buffer == null) debugger;
for(const byte of buffer) {
str += byte.toString(16).padStart(2, "0").toUpperCase();
}
return str;
}
Buffer = Buffer || {
alloc: (value) => {return new Uint8Array(Array(value).fill(0))}
};
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 PACKET_MAGIC = 0xFFAABBCC;
// CacheReplay('output.txt');
const server = net.createServer((socket) => {
console.log('New socket connection!');
const replay = Replay();
async function execCmd(cmd, bufferArgs, helper) {
if (!helper.isDebug) {
const out = replay.matchOut();
socket.write(hexToBuffer(out.data));
}
await cmd.run(socket, bufferArgs, helper);
}
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, _) => {
const checkData = () => {
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);
async function checkForCmd() {
const cmdPacket = await read(12);
if (cmdPacket.readUInt32LE(0) != PACKET_MAGIC) {
sendStatus(socket, CMD_ERROR);
}
const cmdNumber = cmdPacket.readUInt32LE(4);
const cmd = CMD[cmdNumber];
if (!cmd) {
console.log('Trying to execute', cmdNumber.toString(16));
sendStatus(socket, CMD_ERROR);
return;
}
console.log('CMD ', cmd.name);
let isDebug = (cmdNumber & 0x7fFF0000) == 0x1ff0000;
const cmdArgLength = cmdPacket.readUInt32LE(8);
let cmdArg = null;
if (!isDebug) {
replay.matchCommand(cmdPacket.subarray(4));
}
if (cmdArgLength > 0) {
cmdArg = await read(cmdArgLength);
}
if (!isDebug && cmdArg) {
replay.matchIn(cmdArg);
}
await execCmd(cmd, cmdArg, {isDebug, read, replay});
}
let cmdLoopTimeoutId = -1;
const cmdLoop = async () => {
try {
await checkForCmd();
} catch (e) {
console.log(e);
closeConnection();
}
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());
});
process.on('uncaughtException',function(err){
if (err.code === 'ECONNRESET') {
// ignore this
} else {
console.log('something terrible happened..');
console.log(err);
process.exit(-1);
}
});