-
Notifications
You must be signed in to change notification settings - Fork 6
/
artemisNet.js
411 lines (335 loc) · 11 KB
/
artemisNet.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
// Main artemis low(ish)-level network interface
var net = require('net');
var fs = require('fs');
var reader = require('./artemisBufferReader').artemisBufferReader;
// Server Address, will only be set if connected.
var serverAddr = null;
// How many times to retry connecting to a server. 0 disables.
var retries = 0;
// Placeholder for the socket object
var sock;
// Note that "connect" and "disconnect" would conflict on the
// browser side with the built-in events for socket.io
var eventHandlers = {
"connected": [],
"disconnected": [],
"connectError": [],
"packet": []
};
// Connect to the server.
// Params: server address (string) and whether to retry connections to this
// server (boolean)
function connect (addr, r) {
console.log('Connecting to server: ', addr);
if (r !== null) {
retries = r;
}
serverAddr = addr;
sock = net.connect({host: addr, port:2010}, function(){
console.log('Connected to server: ', addr);
sock.on('data', onPacket);
sock.on('end', onDisconnect);
fireEvents('connected');
}).on('error', function(){
if (retries >= 0) {
console.error('Trying to reconnect, ' + retries + ' attempts left');
setTimeout(function(){connect(serverAddr,retries-1)}, 1000);
} else {
console.error('Connection refused');
fireEvents('disconnected');
}
});
}
function disconnect (addr, r) {
retries = 0;
if (sock) {
sock.end();
}
}
// Aux function to fire all event handlers of the given event.
// The event handler will be passed 'data', a generic object
// containing the human-readable contents of the packet.
// In the special case of the 'packet' event, a 'packetType'
// is added to the struct.
function fireEvents(eventType, data, packetType) {
for (var i in eventHandlers[eventType]) {
eventHandlers[eventType][i](data, packetType);
}
}
// Attach an event listener
function on(eventType, fn) {
if (eventHandlers.hasOwnProperty(eventType)) {
eventHandlers[eventType].push(fn);
// console.log('Attached event to packet type: ', eventType);
} else {
// console.log('No registered packet type: ', eventType);
}
}
// Detach an event listener
function off(eventType, fn) {
var i = eventHandlers[eventType].indexOf(fn);
if (i != -1) {
delete(eventHandlers[eventType][i]);
}
}
var previousBuffer = null;
// When a packet is received, parse its header and delegate further
// parsing depending on the packet type.
function onPacket(buffer) {
var header = {};
if (previousBuffer) {
buffer = Buffer.concat([previousBuffer, buffer]);
// console.log('Concatenating previously received data, now is ',buffer);
previousBuffer = null;
}
var data = new reader(buffer);
if (buffer.length < 24) {
// console.log('End of TCP datagram reached while parsing packet headers');
previousBuffer = buffer;
return;
}
header.magic = data.readLong();
header.packetLength = data.readLong();
header.origin = data.readLong();
header.unknown = data.readLong();
header.bytesRemaining = data.readLong();
header.type = data.readLong();
header.subtype = null;
// console.log(header);
if (header.magic != 0xdeadbeef) {
console.error('Bad magic number!!', header.magic);
// console.log(buffer);
return;
}
if (header.packetLength != (header.bytesRemaining + 20)) {
console.error('Packet length and remaining bytes mismatch!!');
return;
}
if (buffer.length < header.packetLength) {
// console.log('End of TCP datagram before end of packet');
previousBuffer = buffer;
return;
}
var packetDef = null;
if (knownPackets.hasOwnProperty( header.type )) {
var packets = [];
var packetTypes = [];
var subtypeLength = 0;
var packetDef;
if (knownPackets[header.type].subpackets) {
subtypeLength = knownPackets[header.type].subtypeLength;
}
// One packet may contain several subpackets, just concatenated.
while(data.pointer < header.packetLength)
{
if (subtypeLength == 1) {
header.subtype = data.readByte();
} else if (subtypeLength == 4) {
header.subtype = data.readLong();
}
if (!subtypeLength) {
packetDef = knownPackets[header.type];
}
if (subtypeLength) {
if (!header.subtype) {
// console.log('End of subpackets');
break;
}
if ( knownSubPackets[header.type].hasOwnProperty(header.subtype)) {
packetDef = knownSubPackets[header.type][header.subtype];
}
}
var packetType;
if (packetDef) {
packetType = packetDef.name;
} else {
console.error('Unknown packet!', header.type, header.subtype);
}
// Unfortunately, there might be some bugs still present
// with random crashes involving reading outside the
// recv buffer, so let's wrap this into a try-catch...
try {
packetTypes.push(packetType);
var unpacked = packetDef.unpack(data);
packets.push(unpacked);
// Debug: log non-entity-update, non-usually-seen packets
if (header.type != 0x80803df9 &&
// packetType != 'togglePause' &&
packetType != 'intel' &&
packetType != 'damcon' &&
packetType != 'beamFired' &&
packetType != 'allShipSettings' &&
packetType != 'consoleStatus' &&
// packetType != 'gameRestart' &&
packetType != 'soundEffect' &&
packetType != 'commsIncoming' &&
packetType != 'playerShipDamage' &&
// packetType != 'weaponsUpdate' &&
packetType != 'destroyObject') {
console.log(packetType, unpacked);
}
} catch(e) {
console.error('Aaaaiiieeeee, something went wrong while parsing a packet of type ' + packetType + '!');
console.error(e);
var str = '';
for (var i = 0; i<header.packetLength && i<data.buffer.length; i++) {
var hex = data.buffer.readUInt8(i).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
str += hex + ' ';
}
console.log('Data was:');
console.log(str);
break;
}
}
// Some packets, particularly the stationUpdate one,
// may return more than one payload.
// if (Array.isArray(packet)) {
for (i in packets) {
// console.log(packetTypes[i], packets[i]);
fireEvents(packetTypes[i], packets[i]);
fireEvents('packet', packets[i], packetTypes[i]);
}
// Packets with 1-byte subtype are packed to 4 bytes.
// This means the last 00 is really the last 00000000 and
// we need to advance the pointer a little bit.
if (subtypeLength == 1) {
data.pointer+=3;
}
// Code to debug unknown/weird/mishandled packets
if (data.pointer != header.packetLength) {
console.log('Mismatching read length and packet length: ', data.pointer, header.packetLength, ' , data size: ', data.buffer.length);
console.log('Last packet was: ', packetTypes[packets.length-1], packets[packets.length-1]);
var str = '';
for (var i = 0; i<data.pointer && i<data.buffer.length; i++) {
var hex = data.buffer.readUInt8(i).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
str += hex + ' ';
}
console.log('Data was:');
console.log(str);
var str = '';
for (var i = data.pointer; i<=header.packetLength && i<data.buffer.length; i++) {
var hex = data.buffer.readUInt8(i).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
str += hex + ' ';
}
console.log('Data ahead is:');
console.log(str);
}
} else {
console.error('Unknown packet type: ', header.type.toString(16), ', subtype: ', header.subtype);
// Display the unknown payload if it's not a magic word
// marking the start of the next packet.
if (data.length) {
if (data.buffer.readLong(0) != 0xdeadbeef) {
console.log('Unknown payload: ', data.buffer.slice(0,header.packetLength));
}
}
fireEvents('packet', header);
}
// Perhaps we still have some data in the same TCP packet, so let's use a bit of recursivity...
if (data.buffer.length > header.packetLength) {
onPacket( data.buffer.slice(header.packetLength) );
}
}
function onDisconnect(){
console.log('Disconnected from server!');
fireEvents('gameOver');
fireEvents('disconnected');
if (retries) {
console.error('Trying to reconnect');
setTimeout(function(){connect(serverAddr,retries-1)}, 1000);
}
}
// Given a packet name and structure, pack it into a buffer and send it.
// Will call the underlying packet 'pack' function.
function emit(packetName, data) {
if (!packetsByName.hasOwnProperty(packetName)) {
return false;
}
var packet = packetsByName[ packetName ];
if (!packet.pack) {
return false;
}
// Declare a buffer big enough, and wrap it with our helpers.
var writer = new reader( new Buffer(2048) ); // Yes, yes, I know the naming doesn't make any sense.
writer.writeLong(0xdeadbeef); // Magic number
writer.writeLong(0); /// packetLength FIXME!!! Will need to re-write with real length
writer.writeLong(2); // Origin = client (not server)
writer.writeLong(0); // Unknown
writer.writeLong(0); /// bytesRemaining FIXME!!! Will need to re-write with real length
writer.writeLong( packet.type );
if (packet.subtypeLength == 1) {
writer.writeByte( packet.subtype );
} else if (packet.subtypeLength == 4) {
writer.writeLong( packet.subtype );
}
packet.pack( writer, data );
// Re-write packetLength
writer.buffer.writeUInt32LE(writer.pointer, 4);
// Re-write remainingBytes
writer.buffer.writeUInt32LE(writer.pointer - 20, 16);
// Finally, send the useful part of the buffer.
sock.write( writer.buffer.slice(0,writer.pointer) );
}
var knownPackets = {};
var knownSubPackets = {};
var packetsByName = {};
// Register a new packet type (usually from an external file).
// Expects an object with properties:
// - name (string)
// - type (int32)
// - subtype (either null or int8)
// - pack (an optional function for custom packing)
// - unpack (an optional function for custom unpacking)
function registerPacketType( packet ) {
if (packet.subtype === null) {
knownPackets[ packet.type ] = packet;
knownPackets[ packet.type ].subpackets = false;
} else {
knownPackets[ packet.type ] = {
type: packet.type,
name: "subpacket",
subpackets: true,
subtypeLength: packet.subtypeLength
};
if (!knownSubPackets.hasOwnProperty(packet.type)) {
knownSubPackets[ packet.type ] = {};
}
knownSubPackets[ packet.type ][ packet.subtype ] =
packet;
}
if (!eventHandlers.hasOwnProperty(packet.name)) {
eventHandlers[ packet.name ] = [];
}
packetsByName[ packet.name ] = packet;
/// TODO!!! Implement the translation of browser-side "emit"s to
/// glitter-side "emit"s.
}
// Import known packet types. Their definitions are scattered
// across two levels of subdirectories to make editing a bit saner.
function recursiveRegisterPacket(dirname) {
var packetFiles = fs.readdirSync(dirname);
for (i in packetFiles) {
var fullname = dirname + '/' + packetFiles[i];
if (fs.statSync(fullname).isDirectory()) {
recursiveRegisterPacket(fullname);
} else {
console.log('Registering packet: ' + fullname);
registerPacketType( require(fullname) );
}
}
}
recursiveRegisterPacket(__dirname + '/packets');
exports.connect = connect;
exports.disconnect = disconnect;
exports.on = on;
exports.off = off;
exports.emit = emit;