-
Notifications
You must be signed in to change notification settings - Fork 4
/
packetio.ts
267 lines (243 loc) · 7.13 KB
/
packetio.ts
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
import { EventEmitter } from 'events';
import { Socket } from 'net';
import { INCOMING_KEY, OUTGOING_KEY, RC4 } from './crypto';
import { Packet } from './packet';
import { PacketMap } from './packet-map';
import { createPacket } from './create-packet';
import { Reader } from './reader';
import { Writer } from './writer';
/**
* The configuration for the RC4 ciphers used by this PacketIO.
*/
export interface RC4Config {
incomingKey: string;
outgoingKey: string;
}
/**
* An RC4 configuration which is suitable for
* PacketIO instances being used as a client.
*/
const DEFAULT_RC4: RC4Config = {
incomingKey: INCOMING_KEY,
outgoingKey: OUTGOING_KEY,
};
/**
* A utility class which implements the RotMG messaging protocol on top of a `Socket`.
*/
export class PacketIO extends EventEmitter {
/**
* The socket this packet interface is attached to.
*/
socket: Socket;
/**
* A packet map object which can be used to resolve incoming and outgoing packet types.
*/
packetMap: PacketMap;
/**
* The last packet which was received.
*/
get lastIncomingPacket(): Packet {
return this._lastIncomingPacket;
}
/**
* The last packet which was sent.
*/
get lastOutgoingPacket(): Packet {
return this._lastOutgoingPacket;
}
private sendRC4: RC4;
private receiveRC4: RC4;
private outgoingQueue: Packet[];
private writer: Writer;
private reader: Reader;
private eventHandlers: Map<string, (...args: any[]) => void>;
// tslint:disable:variable-name
private _lastIncomingPacket: Packet;
private _lastOutgoingPacket: Packet;
// tslint:enable:variable-name
/**
* Creates a new `PacketIO` instance.
* @param opts The options to use for this instance.
*/
constructor(opts: { socket?: Socket, rc4?: RC4Config, packetMap?: PacketMap } = { rc4: DEFAULT_RC4, packetMap: {} }) {
super();
if (!opts.rc4) {
opts.rc4 = DEFAULT_RC4;
}
this.writer = new Writer();
this.reader = new Reader();
this.outgoingQueue = [];
this.sendRC4 = new RC4(Buffer.from(opts.rc4.outgoingKey, 'hex'));
this.receiveRC4 = new RC4(Buffer.from(opts.rc4.incomingKey, 'hex'));
this.packetMap = opts.packetMap || {};
this.eventHandlers = new Map([
['data', this.onData.bind(this)],
['connect', this.resetState.bind(this)]
]);
if (opts.socket) {
this.attach(opts.socket);
}
}
/**
* Attaches this Packet IO to the `socket`.
* @param socket The socket to attach to.
*/
attach(socket: Socket): void {
if (!(socket instanceof Socket)) {
throw new TypeError(`Parameter "socket" should be a Socket, not ${typeof socket}`);
}
if (this.socket) {
this.detach();
}
// we should reset the state here in
// case the socket is already connected.
this.resetState();
this.socket = socket;
for (const [event, listener] of this.eventHandlers) {
this.socket.on(event, listener);
}
}
/**
* Detaches this Packet IO from its `Socket`.
*/
detach(): void {
if (this.socket) {
for (const [event, listener] of this.eventHandlers) {
this.socket.removeListener(event, listener);
}
this.socket = undefined;
}
}
/**
* Sends a packet.
* @param packet The packet to send.
*/
send(packet: Packet) {
if (!this.socket || this.socket.destroyed) {
this.emitError(new Error('Not attached to a socket.'));
return;
}
const type = this.packetMap[packet.type];
if (type === undefined) {
this.emitError(new Error(`Mapper is missing an id for the packet type ${packet.type}`));
return;
}
if (this.outgoingQueue.length === 0) {
this.outgoingQueue.push(packet);
this.drainQueue();
} else {
this.outgoingQueue.push(packet);
}
}
/**
* Takes packets from the outgoing queue and writes
* them to the socket.
*/
private async drainQueue() {
while (this.outgoingQueue.length > 0) {
this._lastOutgoingPacket = this.outgoingQueue[0];
this.writer.index = 5;
const type = this.packetMap[this.outgoingQueue[0].type];
this.outgoingQueue[0].write(this.writer);
this.writer.writeHeader(type);
this.sendRC4.cipher(this.writer.buffer.slice(5, this.writer.index));
await new Promise((resolve) => {
if (this.socket && !this.socket.write(this.writer.buffer.slice(0, this.writer.index))) {
this.socket.once('drain', resolve);
} else {
process.nextTick(resolve);
}
});
this.outgoingQueue.shift();
}
}
/**
* Emits a packet from this PacketIO instance. This will only
* emit the packet to the clients subscribed to this particular PacketIO.
* @param packet The packet to emit.
*/
emitPacket(packet: Packet): void {
if (packet && typeof packet.type === 'string') {
this._lastIncomingPacket = packet;
this.emit(packet.type, packet);
} else {
throw new TypeError(`Parameter "packet" must be a Packet, not ${typeof packet}`);
}
}
/**
* Resets the reader buffer and the RC4 instances.
*/
private resetState(): void {
this.resetBuffer();
this.sendRC4.reset();
this.receiveRC4.reset();
}
/**
* Adds the data received from the socket to the reader buffer.
* @param data The data received.
*/
private onData(data: Buffer): void {
let dataIdx = 0;
while (dataIdx < data.length) {
const copied = data.copy(this.reader.buffer, this.reader.index, dataIdx, dataIdx + this.reader.remaining);
dataIdx += copied;
this.reader.index += copied;
if (this.reader.remaining === 0) {
if (this.reader.length === 4) {
const newSize = this.reader.buffer.readInt32BE(0);
this.reader.resizeBuffer(newSize);
} else {
const packet = this.constructPacket();
this.resetBuffer();
if (packet) {
this.emitPacket(packet);
}
}
}
}
}
/**
* Attempts to create a packet from the data contained
* in the reader buffer. No packet will be created if
* there is no event listener for the packet type.
*/
private constructPacket(): Packet {
this.receiveRC4.cipher(this.reader.buffer.slice(5, this.reader.length));
try {
const id = this.reader.buffer.readInt8(4);
const type = this.packetMap[id];
if (!type) {
throw new Error(`No packet type for the id ${id}`);
}
if (this.listenerCount(type) !== 0) {
const packet = createPacket(type);
this.reader.index = 5;
packet.read(this.reader);
return packet;
}
} catch (error) {
this.emitError(error);
}
return undefined;
}
/**
* Resets the incoming packet buffer so that it
* is ready to receive the next packet header.
*/
private resetBuffer(): void {
this.reader.resizeBuffer(4);
this.reader.index = 0;
}
/**
* Emits an `'error'` event if there are any listeners for it,
* or throws the error if there are no listeners.
* @param error The error to emit.
*/
private emitError(error: Error): void {
if (this.listenerCount('error') === 0) {
throw error;
} else {
this.emit('error', error);
}
}
}