forked from MrHilgert/csgo-log-receiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PacketParser.js
81 lines (51 loc) · 1.88 KB
/
PacketParser.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
const Errors = require('./Errors');
const MAGIC = {
header: Buffer.alloc(4, 255),
bytePassword: 0x53,
byteNoPassword: 0x52,
strHeaderEnd: 'L '
};
class PacketParser {
constructor(server) {
this.server = server;
}
parse(message, senderInfo) {
if (message.length < 16)
return { error: Errors.tooShort };
if (!this.validateHeader(message))
return { error: Errors.badHeader };
if (!this.validatePassword(message, senderInfo))
return { error: Errors.invalidPassword };
let payload = this.extractMessage(message);
return payload || { error: Errors.invalidPayload };
}
validateHeader(message) {
return message.slice(0, MAGIC.header.length).compare(MAGIC.header) === 0;
}
validatePassword(message, senderInfo) {
let packetType = message[4];
let serverOpts = this.server.getSource(senderInfo);
if(!serverOpts) return false;
if (packetType === MAGIC.bytePassword) {
if(!serverOpts.password) return false;
let receivedPassword = this.extractPassword(message);
if(!receivedPassword) return false;
if(serverOpts.password !== receivedPassword) return false;
return true;
}else if(packetType === MAGIC.byteNoPassword) {
if(!serverOpts.password) return true;
}
return false;
}
extractMessage(message) {
let start = message.indexOf(MAGIC.strHeaderEnd);
if(start < 0) return undefined;
return message.slice(start + MAGIC.strHeaderEnd.length, message.length -2).toString();
}
extractPassword(message) {
let end = message.indexOf(MAGIC.strHeaderEnd);
if(end < 0) return undefined;
return message.slice(MAGIC.header.length + 1, end).toString();
}
}
module.exports = PacketParser;