forked from DeepRoost/infinite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.js
441 lines (395 loc) · 13.1 KB
/
sockets.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
/**
* Connections
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Abstraction layer for multi-process SockJS connections.
*
* This file handles all the communications between the users'
* browsers, the networking processes, and users.js in the
* main process.
*
* @license MIT license
*/
// var cluster = require('cluster');
global.Config = require('./config/config');
var fakeProcess = new (require('./fake-process').FakeProcess)();
/* if (cluster.isMaster) {
cluster.setupMaster({
exec: 'sockets.js'
}); */
var workers = exports.workers = {};
var spawnWorker = exports.spawnWorker = function () {
var worker = fakeProcess.server;
var id = worker.id;
workers[id] = worker;
worker.on('message', function (data) {
// console.log('master received: ' + data);
switch (data.charAt(0)) {
case '*': // *socketid, ip
// connect
var nlPos = data.indexOf('\n');
Users.socketConnect(worker, id, data.substr(1, nlPos - 1), data.substr(nlPos + 1));
break;
case '!': // !socketid
// disconnect
Users.socketDisconnect(worker, id, data.substr(1));
break;
case '<': // <socketid, message
// message
var nlPos = data.indexOf('\n');
Users.socketReceive(worker, id, data.substr(1, nlPos - 1), data.substr(nlPos + 1));
break;
}
});
};
// var workerCount = Config.workers || 1;
// for (var i = 0; i < workerCount; i++) {
spawnWorker();
//}
var killWorker = exports.killWorker = function (worker) {
/*var idd = worker.id + '-';
var count = 0;
for (var connectionid in Users.connections) {
if (connectionid.substr(idd.length) === idd) {
var connection = Users.connections[connectionid];
Users.socketDisconnect(worker, worker.id, connection.socketid);
count++;
}
}
try {
worker.kill();
} catch (e) {}
delete workers[worker.id];
return count;*/
return 0;
};
var killPid = exports.killPid = function (pid) {
/* pid = '' + pid;
for (var id in workers) {
var worker = workers[id];
if (pid === '' + worker.process.pid) {
return killWorker(worker);
}
} */
return false;
};
exports.socketSend = function (worker, socketid, message) {
worker.send('>' + socketid + '\n' + message);
};
exports.socketDisconnect = function (worker, socketid) {
worker.send('!' + socketid);
};
exports.channelBroadcast = function (channelid, message) {
for (var workerid in workers) {
workers[workerid].send('#' + channelid + '\n' + message);
}
};
exports.channelSend = function (worker, channelid, message) {
worker.send('#' + channelid + '\n' + message);
};
exports.channelAdd = function (worker, channelid, socketid) {
worker.send('+'+channelid + '\n' + socketid);
};
exports.channelRemove = function (worker, channelid, socketid) {
worker.send('-' + channelid + '\n' + socketid);
};
exports.subchannelBroadcast = function (channelid, message) {
for (var workerid in workers) {
workers[workerid].send(':' + channelid + '\n' + message);
}
};
exports.subchannelMove = function (worker, channelid, subchannelid, socketid) {
worker.send('.' + channelid + '\n' + subchannelid + '\n' + socketid);
};
//} else {
// is worker
if (process.env.PSPORT) Config.port = +process.env.PSPORT;
if (process.env.PSBINDADDR) Config.bindaddress = process.env.PSBINDADDR;
// ofe is optional
// if installed, it will heap dump if the process runs out of memory
try {
require('ofe').call();
} catch (e) {}
// Static HTTP server
// This handles the custom CSS and custom avatar features, and also
// redirects yourserver:8001 to yourserver-8001.psim.us
// It's optional if you don't need these features.
global.Cidr = require('./cidr');
if (Config.crashguard) {
// graceful crash
/*process.on('uncaughtException', function (err) {
require('./crashlogger.js')(err, 'Socket process ' + cluster.worker.id + ' (' + process.pid + ')');
});*/
}
var app = require('http').createServer();
var appssl;
if (Config.ssl) {
appssl = require('https').createServer(Config.ssl.options);
}
try {
(function () {
var fs = require('graceful-fs');
var nodestatic = require('node-static');
var cssserver = new nodestatic.Server('./config');
var avatarserver = new nodestatic.Server('./config/avatars');
var staticserver = new nodestatic.Server('./static');
var staticRequestHandler = function (request, response) {
request.resume();
request.addListener('end', function () {
if (Config.customHttpResponse && Config.customHttpResponse(request, response)) return;
var server;
if (request.url === '/custom.css') {
server = cssserver;
} else if (request.url.substr(0, 9) === '/avatars/') {
request.url = request.url.substr(8);
server = avatarserver;
} else {
if (/^\/([A-Za-z0-9][A-Za-z0-9-]*)\/?$/.test(request.url)) {
request.url = '/';
}
server = staticserver;
}
server.serve(request, response, function (e, res) {
fs.appendFile('logs/access.log',
request.socket.remoteAddress + ' - - [' + new Date().toLocaleString() + '] "' +
request.method + ' ' + request.url + ' HTTP/' + request.httpVersion + '" ' +
(e ? e.status : 200) + ' ? "' + (request.headers['referer'] || '-') + '" "' + (request.headers['user-agent'] || '-') + '"\n');
if (e && (e.status === 404)) {
staticserver.serveFile('404.html', 404, {}, request, response);
}
});
});
};
app.on('request', staticRequestHandler);
if (appssl) {
appssl.on('request', staticRequestHandler);
}
})();
} catch (e) {
console.log('Could not start node-static - try `npm install` if you want to use it');
}
// SockJS server
// This is the main server that handles users connecting to our server
// and doing things on our server.
var sockjs = require('sockjs');
var server = sockjs.createServer({
sockjs_url: "//play.pokemonshowdown.com/js/lib/sockjs-0.3.min.js",
log: function (severity, message) {
if (severity === 'error') console.log('ERROR: ' + message);
},
prefix: '/showdown',
websocket: !Config.disableWebsocket
});
var sockets = {};
var channels = {};
var subchannels = {};
// Deal with phantom connections.
var sweepClosedSockets = function () {
for (var s in sockets) {
if (sockets[s].protocol === 'xhr-streaming' &&
sockets[s]._session &&
sockets[s]._session.recv) {
sockets[s]._session.recv.didClose();
}
// A ghost connection's `_session.to_tref._idlePrev` (and `_idleNext`) property is `null` while
// it is an object for normal users. Under normal circumstances, those properties should only be
// `null` when the timeout has already been called, but somehow it's not happening for some connections.
// Simply calling `_session.timeout_cb` (the function bound to the aformentioned timeout) manually
// on those connections kills those connections. For a bit of background, this timeout is the timeout
// that sockjs sets to wait for users to reconnect within that time to continue their session.
if (sockets[s]._session &&
sockets[s]._session.to_tref &&
!sockets[s]._session.to_tref._idlePrev) {
sockets[s]._session.timeout_cb();
}
}
};
var interval;
if (!Config.herokuHack) {
interval = setInterval(sweepClosedSockets, 1000 * 60 * 10);
}
fakeProcess.client.on('message', function (data) {
// console.log('worker received: ' + data);
var socket = null;
var channel = null;
var socketid = null;
var channelid = null;
switch (data.charAt(0)) {
case '!': // !socketid
// destroy
socketid = data.substr(1);
socket = sockets[socketid];
if (!socket) return;
socket.end();
// After sending the FIN packet, we make sure the I/O is totally blocked for this socket
socket.destroy();
delete sockets[socketid];
for (channelid in channels) {
delete channels[channelid][socketid];
}
break;
case '>': // >socketid, message
// message
var nlLoc = data.indexOf('\n');
socket = sockets[data.substr(1, nlLoc - 1)];
if (!socket) return;
socket.write(data.substr(nlLoc + 1));
break;
case '#': // #channelid, message
// message to channel
var nlLoc = data.indexOf('\n');
channel = channels[data.substr(1, nlLoc - 1)];
var message = data.substr(nlLoc + 1);
for (socketid in channel) {
channel[socketid].write(message);
}
break;
case '+': // +channelid, socketid
// add to channel
var nlLoc = data.indexOf('\n');
socketid = data.substr(nlLoc + 1);
socket = sockets[socketid];
if (!socket) return;
channelid = data.substr(1, nlLoc - 1);
channel = channels[channelid];
if (!channel) channel = channels[channelid] = Object.create(null);
channel[socketid] = socket;
break;
case '-': // -channelid, socketid
// remove from channel
var nlLoc = data.indexOf('\n');
var channelid = data.slice(1, nlLoc);
channel = channels[channelid];
if (!channel) return;
var socketid = data.slice(nlLoc + 1);
delete channel[socketid];
if (subchannels[channelid]) delete subchannels[channelid][socketid];
var isEmpty = true;
for (var socketid in channel) {
isEmpty = false;
break;
}
if (isEmpty) {
delete channels[channelid];
delete subchannels[channelid];
}
break;
case '.': // .channelid, subchannelid, socketid
// move subchannel
var nlLoc = data.indexOf('\n');
var channelid = data.slice(1, nlLoc);
var nlLoc2 = data.indexOf('\n', nlLoc + 1);
var subchannelid = data.slice(nlLoc + 1, nlLoc2);
var socketid = data.slice(nlLoc2 + 1);
var subchannel = subchannels[channelid];
if (!subchannel) subchannel = subchannels[channelid] = Object.create(null);
if (subchannelid === '0') {
delete subchannel[socketid];
} else {
subchannel[socketid] = subchannelid;
}
break;
case ':': // :channelid, message
// message to subchannel
var nlLoc = data.indexOf('\n');
var channelid = data.slice(1, nlLoc);
var channel = channels[channelid];
var subchannel = subchannels[channelid];
var message = data.substr(nlLoc + 1);
var messages = [null, null, null];
for (socketid in channel) {
switch (subchannel ? subchannel[socketid] : '0') {
case '1':
if (!messages[1]) {
messages[1] = message.replace(/\n\|split\n[^\n]*\n([^\n]*)\n[^\n]*\n[^\n]*/g, '\n$1\n');
}
channel[socketid].write(messages[1]);
break;
case '2':
if (!messages[2]) {
messages[2] = message.replace(/\n\|split\n[^\n]*\n[^\n]*\n([^\n]*)\n[^\n]*/g, '\n$1\n');
}
channel[socketid].write(messages[2]);
break;
default:
if (!messages[0]) {
messages[0] = message.replace(/\n\|split\n([^\n]*)\n[^\n]*\n[^\n]*\n[^\n]*/g, '\n$1\n');
}
channel[socketid].write(messages[0]);
break;
}
}
break;
}
});
// this is global so it can be hotpatched if necessary
var isTrustedProxyIp = Cidr.checker(Config.proxyIps);
var socketCounter = 0;
server.on('connection', function (socket) {
if (!socket) {
// For reasons that are not entirely clear, SockJS sometimes triggers
// this event with a null `socket` argument.
return;
} else if (!socket.remoteAddress) {
// This condition occurs several times per day. It may be a SockJS bug.
try {
socket.end();
} catch (e) {}
return;
}
var socketid = socket.id = (++socketCounter);
sockets[socket.id] = socket;
if (isTrustedProxyIp(socket.remoteAddress)) {
var ips = (socket.headers['x-forwarded-for'] || '').split(',');
var ip;
while ((ip = ips.pop())) {
ip = ip.trim();
if (!isTrustedProxyIp(ip)) {
socket.remoteAddress = ip;
break;
}
}
}
fakeProcess.client.send('*' + socketid + '\n' + socket.remoteAddress);
// console.log('CONNECT: ' + socket.remoteAddress + ' [' + socket.id + ']');
var interval;
if (Config.herokuHack) {
// see https://github.com/sockjs/sockjs-node/issues/57#issuecomment-5242187
interval = setInterval(function () {
try {
socket._session.recv.didClose();
} catch (e) {}
}, 15000);
}
socket.on('data', function (message) {
// drop empty messages (DDoS?)
if (!message) return;
// drop blank messages (DDoS?)
var pipeIndex = message.indexOf('|');
if (pipeIndex < 0 || pipeIndex === message.length - 1) return;
// drop legacy JSON messages
if (message.charAt(0) === '{') return;
fakeProcess.client.send('<' + socketid + '\n' + message);
});
socket.on('close', function () {
if (interval) {
clearInterval(interval);
}
fakeProcess.client.send('!' + socketid);
delete sockets[socketid];
for (var channelid in channels) {
delete channels[channelid][socketid];
}
});
});
server.installHandlers(app, {});
app.listen(Config.port, Config.bindaddress || undefined);
console.log('Worker ' /* + cluster.worker.id */+ ' now listening on ' + (Config.bindaddress || '*') + ':' + Config.port);
if (appssl) {
server.installHandlers(appssl, {});
appssl.listen(Config.ssl.port);
console.log('Worker ' /*+ cluster.worker.id*/ + ' now listening for SSL on port ' + Config.ssl.port);
}
console.log('Test your server at http://' + (Config.bindaddress || 'localhost') + ':' + Config.port);
// require('./repl.js').start('sockets-', cluster.worker.id + '-' + process.pid, function (cmd) { return eval(cmd); });
//}