forked from AllenDBB/infinite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
425 lines (381 loc) · 13.6 KB
/
app.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
/**
* Main file
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This is the main Pokemon Showdown app, and the file you should be
* running to start Pokemon Showdown if you're using it normally.
*
* This file sets up our SockJS server, which handles communication
* between users and your server, and also sets up globals. You can
* see details in their corresponding files, but here's an overview:
*
* Users - from users.js
*
* Most of the communication with users happens in users.js, we just
* forward messages between the sockets.js and users.js.
*
* Rooms - from rooms.js
*
* Every chat room and battle is a room, and what they do is done in
* rooms.js. There's also a global room which every user is in, and
* handles miscellaneous things like welcoming the user.
*
* Tools - from tools.js
*
* Handles getting data about Pokemon, items, etc. *
*
* Simulator - from simulator.js
*
* Used to access the simulator itself.
*
* CommandParser - from command-parser.js
*
* Parses text commands like /me
*
* Sockets - from sockets.js
*
* Used to abstract out network connections. sockets.js handles
* the actual server and connection set-up.
*
* @license MIT license
*/
/*********************************************************
* Make sure we have everything set up correctly
*********************************************************/
// Make sure our dependencies are available, and install them if they
// aren't
function runNpm(command) {
command = 'npm ' + command + ' && ' + process.execPath + ' app.js';
console.log('Running `' + command + '`...');
require('child_process').spawn('sh', ['-c', command], {stdio: 'inherit', detached: true});
process.exit(0);
}
try {
require('sugar');
} catch (e) {
runNpm('install');
}
if (!Object.select) {
runNpm('update');
}
// Make sure config.js exists, and copy it over from config-example.js
// if it doesn't
var fs = require('graceful-fs');
// Synchronously, since it's needed before we can start the server
if (!fs.existsSync('./config/config.js')) {
console.log("config.js doesn't exist - creating one with default settings...");
fs.writeFileSync('./config/config.js',
fs.readFileSync('./config/config-example.js')
);
}
/*********************************************************
* Load configuration
*********************************************************/
global.Config = require('./config/config.js');
if (Config.watchconfig) {
fs.watchFile('./config/config.js', function (curr, prev) {
if (curr.mtime <= prev.mtime) return;
try {
delete require.cache[require.resolve('./config/config.js')];
global.Config = require('./config/config.js');
console.log('Reloaded config/config.js');
} catch (e) {}
});
}
// Autoconfigure the app when running in cloud hosting environments:
var cloudenv = require('cloud-env');
Config.bindaddress = cloudenv.get('IP', Config.bindaddress || '');
Config.port = cloudenv.get('PORT', Config.port);
if (process.argv[2] && parseInt(process.argv[2])) {
Config.port = parseInt(process.argv[2]);
}
global.ResourceMonitor = {
connections: {},
connectionTimes: {},
battles: {},
battleTimes: {},
battlePreps: {},
battlePrepTimes: {},
networkUse: {},
networkCount: {},
cmds: {},
cmdsTimes: {},
cmdsTotal: {lastCleanup: Date.now(), count: 0},
teamValidatorChanged: 0,
teamValidatorUnchanged: 0,
/**
* Counts a connection. Returns true if the connection should be terminated for abuse.
*/
log: function (text) {
console.log(text);
if (Rooms.rooms.staff) {
Rooms.rooms.staff.add('||' + text);
Rooms.rooms.staff.update();
}
},
logHTML: function (text) {
console.log(text);
if (Rooms.rooms.staff) {
Rooms.rooms.staff.add('|html|' + text);
Rooms.rooms.staff.update();
}
},
countConnection: function (ip, name) {
var now = Date.now();
var duration = now - this.connectionTimes[ip];
name = (name ? ': ' + name : '');
if (ip in this.connections && duration < 30 * 60 * 1000) {
this.connections[ip]++;
if (this.connections[ip] < 500 && duration < 5 * 60 * 1000 && this.connections[ip] % 30 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.connections[ip] < 500 && this.connections[ip] % 90 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.connections[ip] === 500) {
this.log('[ResourceMonitor] IP ' + ip + ' has been banned for connection flooding (' + this.connections[ip] + ' times in the last ' + duration.duration() + name + ')');
return true;
} else if (this.connections[ip] > 500) {
if (this.connections[ip] % 250 === 0) {
this.log('[ResourceMonitor] Banned IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name);
}
return true;
}
} else {
this.connections[ip] = 1;
this.connectionTimes[ip] = now;
}
},
/**
* Counts a battle. Returns true if the connection should be terminated for abuse.
*/
countBattle: function (ip, name) {
var now = Date.now();
var duration = now - this.battleTimes[ip];
name = (name ? ': ' + name : '');
if (ip in this.battles && duration < 30 * 60 * 1000) {
this.battles[ip]++;
if (duration < 5 * 60 * 1000 && this.battles[ip] % 15 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has battled ' + this.battles[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.battles[ip] % 75 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has battled ' + this.battles[ip] + ' times in the last ' + duration.duration() + name);
}
} else {
this.battles[ip] = 1;
this.battleTimes[ip] = now;
}
},
/**
* Counts battle prep. Returns true if too much
*/
countPrepBattle: function (ip) {
var now = Date.now();
var duration = now - this.battlePrepTimes[ip];
if (ip in this.battlePreps && duration < 3 * 60 * 1000) {
this.battlePreps[ip]++;
if (this.battlePreps[ip] > 6) {
return true;
}
} else {
this.battlePreps[ip] = 1;
this.battlePrepTimes[ip] = now;
}
},
/**
* data
*/
countNetworkUse: function (size) {
if (this.activeIp in this.networkUse) {
this.networkUse[this.activeIp] += size;
this.networkCount[this.activeIp]++;
} else {
this.networkUse[this.activeIp] = size;
this.networkCount[this.activeIp] = 1;
}
},
writeNetworkUse: function () {
var buf = '';
for (var i in this.networkUse) {
buf += '' + this.networkUse[i] + '\t' + this.networkCount[i] + '\t' + i + '\n';
}
fs.writeFile('logs/networkuse.tsv', buf);
},
clearNetworkUse: function () {
this.networkUse = {};
this.networkCount = {};
},
/**
* Counts roughly the size of an object to have an idea of the server load.
*/
sizeOfObject: function (object) {
var objectList = [];
var stack = [object];
var bytes = 0;
while (stack.length) {
var value = stack.pop();
if (typeof value === 'boolean') bytes += 4;
else if (typeof value === 'string') bytes += value.length * 2;
else if (typeof value === 'number') bytes += 8;
else if (typeof value === 'object' && objectList.indexOf(value) === -1) {
objectList.push(value);
for (var i in value) stack.push(value[i]);
}
}
return bytes;
},
/**
* Controls the amount of times a cmd command is used
*/
countCmd: function (ip, name) {
var now = Date.now();
var duration = now - this.cmdsTimes[ip];
name = (name ? ': ' + name : '');
if (!this.cmdsTotal) this.cmdsTotal = {lastCleanup: 0, count: 0};
if (now - this.cmdsTotal.lastCleanup > 60 * 1000) {
this.cmdsTotal.count = 0;
this.cmdsTotal.lastCleanup = now;
}
this.cmdsTotal.count++;
if (ip in this.cmds && duration < 60 * 1000) {
this.cmds[ip]++;
if (duration < 60 * 1000 && this.cmds[ip] % 5 === 0) {
if (this.cmds[ip] >= 3) {
if (this.cmds[ip] % 30 === 0) this.log('CMD command from ' + ip + ' blocked for ' + this.cmds[ip] + 'th use in the last ' + duration.duration() + name);
return true;
}
this.log('[ResourceMonitor] IP ' + ip + ' has used CMD command ' + this.cmds[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.cmds[ip] % 15 === 0) {
this.log('CMD command from ' + ip + ' blocked for ' + this.cmds[ip] + 'th use in the last ' + duration.duration() + name);
return true;
}
} else if (this.cmdsTotal.count > 8000) {
// One CMD check per user per minute on average (to-do: make this better)
this.log('CMD command for ' + ip + ' blocked because CMD has been used ' + this.cmdsTotal.count + ' times in the last minute.');
return true;
} else {
this.cmds[ip] = 1;
this.cmdsTimes[ip] = now;
}
}
};
/*********************************************************
* Set up most of our globals
*********************************************************/
/**
* Converts anything to an ID. An ID must have only lowercase alphanumeric
* characters.
* If a string is passed, it will be converted to lowercase and
* non-alphanumeric characters will be stripped.
* If an object with an ID is passed, its ID will be returned.
* Otherwise, an empty string will be returned.
*/
global.toId = function (text) {
if (text && text.id) text = text.id;
else if (text && text.userid) text = text.userid;
return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
/**
* Sanitizes a username or Pokemon nickname
*
* Returns the passed name, sanitized for safe use as a name in the PS
* protocol.
*
* Such a string must uphold these guarantees:
* - must not contain any ASCII whitespace character other than a space
* - must not start or end with a space character
* - must not contain any of: | , [ ]
* - must not be the empty string
*
* If no such string can be found, returns the empty string. Calling
* functions are expected to check for that condition and deal with it
* accordingly.
*
* toName also enforces that there are not multiple space characters
* in the name, although this is not strictly necessary for safety.
*/
global.toName = function (name) {
name = string(name);
name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim();
if (name.length > 18) name = name.substr(0, 18).trim();
return name;
};
/**
* Safely ensures the passed variable is a string
* Simply doing '' + str can crash if str.toString crashes or isn't a function
* If we're expecting a string and being given anything that isn't a string
* or a number, it's safe to assume it's an error, and return ''
*/
global.string = function (str) {
if (typeof str === 'string' || typeof str === 'number') return '' + str;
return '';
};
global.LoginServer = require('./loginserver.js');
global.Users = require('./users.js');
global.Rooms = require('./rooms.js');
delete process.send; // in case we're a child process
global.Verifier = require('./verifier.js');
global.CommandParser = require('./command-parser.js');
global.Simulator = require('./simulator.js');
global.Tournaments = require('./tournaments');
try {
global.Dnsbl = require('./dnsbl.js');
} catch (e) {
global.Dnsbl = {query:function () {}};
}
global.Cidr = require('./cidr.js');
if (Config.crashguard) {
// graceful crash - allow current battles to finish before restarting
var lastCrash = 0;
process.on('uncaughtException', function (err) {
var dateNow = Date.now();
var quietCrash = require('./crashlogger.js')(err, 'The main process');
quietCrash = quietCrash || ((dateNow - lastCrash) <= 1000 * 60 * 5);
lastCrash = Date.now();
if (quietCrash) return;
var stack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />");
if (Rooms.lobby) {
Rooms.lobby.addRaw('<div class="broadcast-red"><b>THE SERVER HAS CRASHED:</b> ' + stack + '<br />Please restart the server.</div>');
Rooms.lobby.addRaw('<div class="broadcast-red">You will not be able to talk in the lobby or start new battles until the server restarts.</div>');
}
Config.modchat = 'crash';
Rooms.global.lockdown = true;
});
}
/*********************************************************
* Start networking processes to be connected to
*********************************************************/
global.Sockets = require('./sockets.js');
global.Bot = require('./bot.js');
/*********************************************************
* Set up our last global
*********************************************************/
// This slow operation is done *after* we start listening for connections
// to the server. Anybody who connects while this require() is running will
// have to wait a couple seconds before they are able to join the server, but
// at least they probably won't receive a connection error message.
global.Tools = require('./tools.js');
// After loading tools, generate and cache the format list.
Rooms.global.formatListText = Rooms.global.getFormatListText();
global.TeamValidator = require('./team-validator.js');
// load ipbans at our leisure
fs.readFile('./config/ipbans.txt', function (err, data) {
if (err) return;
data = ('' + data).split("\n");
var rangebans = [];
for (var i = 0; i < data.length; i++) {
data[i] = data[i].split('#')[0].trim();
if (!data[i]) continue;
if (data[i].indexOf('/') >= 0) {
rangebans.push(data[i]);
} else if (!Users.bannedIps[data[i]]) {
Users.bannedIps[data[i]] = '#ipban';
}
}
Users.checkRangeBanned = Cidr.checker(rangebans);
});
global.Core = require('./core.js').core;
global.Components = require('./components.js');
global.Poll = require('./core.js').core.poll();
global.SysopAccess = require('./core.js').sysopAccess();
/*********************************************************
* Start up the REPL server
*********************************************************/
require('./repl.js').start('app', function (cmd) { return eval(cmd); });