-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
428 lines (357 loc) · 13.1 KB
/
router.js
File metadata and controls
428 lines (357 loc) · 13.1 KB
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
/**
* @module {function} - YGOSharp Router and Shell
* @description This is the routing and proxy system. The System checks a number of CTOS commands and from them works out if to just route. the connection to an existing connection or start a new YGOCore. If a new YGOCore is needed it works out what config file is needed for that instance of dueling based on the `roompass` in the connection string of the `CTOS_JOIN` command.
* @author Jamezs "AccessDenied" L Gladney.
* @version 0.0.1
* @example
processIncomingTrasmission(data, socket, task);
*/
/*jslint node: true, plusplus: true, unparam: false, nomen: true*/
'use strict';
var portmin = 30000 + process.env.PORTRANGE * 100, //Port Ranges
portmax = (30000 + process.env.PORTRANGE * 100) + 100,
handleCoreMessage, // Send messages BACK to the MASTER PROCESS
startDirectory = __dirname,
fs = require('fs'),
path = require('path'),
childProcess = require('child_process'),
net = require('net'),
parsePackets = require('./parsepackets.js'), //Get data sets out of the YGOPro Network API.
recieveCTOS = require('./recieveCTOS'), // Translate data sets into messages of the API
gamelist = {},
registry = {
//People that have read this source code.
SnarkyChild: '::ffff: 127.0.0.1',
AccessDenied: '::ffff:127.0.0.1',
Irate: '::ffff:127.0.0.1',
Chibi: '::ffff:127.0.0.1',
OmniMage: '::ffff:127.0.0.1'
},
//winston = require('winston'),
coreIsInPlace = false,
ps = require('ps-node'),
internalGames = [], // internal list of all games the bot is playing
//enums = require('./libs/enums.js'),
Socket = require('primus').createSocket({
iknowclusterwillbreakconnections: true
}),
client = {
write: function() {
console.log(' [ProcessCTOS]system not ready yet');
}
},
childProcess = require('child_process'),
startDirectory = __dirname;
var primaryScripts = {
0: '../http/ygopro/script',
1: '../ygopro-tcg-scripts',
2: '../http/ygopro/script',
3: '../http/ygopro/script',
4: '../http/ygopro/script',
5: '../http/ygopro/script',
99: '../ygopro-goat-scripts'
};
var secondaryScripts = {
0: '../http/ygopro/script',
1: '../http/ygopro/script',
2: '../http/ygopro/script',
3: '../http/ygopro/script',
4: '../http/ygopro/script',
5: '../http/ygopro/script',
99: '../http/ygopro/script'
};
var dbs = {
'ini/config.ini': '../http/ygopro/databases/0-en-OCGTCG.cdb',
'ini/newgioh.ini': '../http/ygopro/databases/4-Newgioh.cdb',
'ini/goat.ini': '../http/ygopro/databases/3-Goats.cdb',
'ini/3-config.ini': '../http/ygopro/databases/Z-CWA.cdb',
'ini/4-config.ini': '../http/ygopro/databases',
'ini/5-config.ini': '../http/ygopro/databases'
};
function parseDuelOptions(duelOptions) {
//{"200OOO8000,0,5,1,U,PaS5w":{"port":8000,"players":[],"started":false}}
var duelOptionsParts = duelOptions.split(','),
settings = { //Determine time limit
//Use classic TCG rules?
isTCGRuled: (duelOptionsParts[0][3] === 'O') ? 'false' : 'true',
//Check Deck for Illegal cards?
isDeckChecked: (duelOptionsParts[0][4] === 'O') ? 'false' : 'true',
//Shuffle deck at start?
isShuffled: (duelOptionsParts[0][5] === 'O') ? 'false' : 'true',
//Choose Starting Life Points
lifePoints: duelOptionsParts[0].substring(6),
//Determine Banlist
banList: parseInt(duelOptionsParts[1], 10),
//Select how many cards to draw on first hand
openDraws: duelOptionsParts[2],
//Select how many cards to draw each turn
turnDraws: duelOptionsParts[3],
//Choose whether duel is locked
isLocked: (duelOptionsParts[4] === 'U') ? false : true,
//Copy password
password: duelOptionsParts[5]
};
settings.timeLimit = (Number(duelOptionsParts[0][2]) + 1) * 180;
settings.allowedCards = duelOptionsParts[0][0];
settings.gameMode = duelOptionsParts[0][1];
return settings;
}
fs.exists(startDirectory + '../ygosharp/YGOSharp.exe', function(exist) {
if (!exist) {
console.log(' [ProcessCTOS]', path.resolve(startDirectory + '../ygosharp/YGOSharp.exe') + ' is missing!');
return;
} else {
//coreErrors.info('YGOCore is in place, allowing connections.');
coreIsInPlace = true;
}
});
/**
* Listen to the MASTER process for messages to the SLAVE
processes. That message will be an update to the internal
gamelist of each SLAVE process */
function processTask(task, socket) {
var i = 0,
l = 0,
players,
output = [];
for (i; task.length > i; i++) {
output.push(recieveCTOS(task[i], socket.username, socket.hostString));
}
for (l; output.length > l; l++) {
if (output[l].CTOS_JOIN_GAME) {
socket.active = true;
socket.hostString = output[l].CTOS_JOIN_GAME;
}
if (output[l].CTOS_PLAYER_INFO) {
socket.username = output[l].CTOS_PLAYER_INFO;
}
}
}
/** After determining the routing location, then connect the CLIENT to
the proper YGOCore and monitor the connection
*/
function connectToCore(port, data, socket) {
socket.active_ygocore = net.connect(port, '127.0.0.1', function() {
/* Unlimit the speed of the connection
by not doing processing on the data
to incease up network optimization */
socket.active_ygocore.setNoDelay(true);
/*proxy the data*/
socket.active_ygocore.write(data);
socket.active = false;
socket.active_ygocore.on('data', function(core_data) {
socket.write(core_data);
});
socket.on('close', function() {
if (socket.active_ygocore) {
socket.active_ygocore.end();
}
});
socket.on('error', function(error) {
socket.active_ygocore.end();
});
});
socket.active_ygocore.on('error', function(error) {
//cHistory.info('--GAME');
if (socket.alpha) {
handleCoreMessage('::::endduel|' + socket.hostString, port, socket, data);
}
socket.end();
});
socket.active_ygocore.on('close', function() {
if (socket.alpha) {
handleCoreMessage('::::endduel|' + socket.hostString, port, socket, data);
}
socket.end();
});
}
/** Each YGOCore needs to operate on its own port,
each SLAVE is given a range to loop through. This
is actually a very poor way of doing this and
frequently fails; rewrite is needed*/
function portfinder(min, max, callback) {
var rooms,
activerooms = [],
num = Math.floor(Math.random() * 10000);
function isPortTaken(port, fn) {
var tester = net.createServer().once('error', function(err) {
if (err.code !== 'EADDRINUSE') {
return fn(err);
}
fn(null, true);
}).once('listening', function() {
tester.once('close', function() {
fn(null, false);
}).close();
}).listen(port);
}
function portResolve(error) {
if (error) {
portfinder(min, max, callback);
} else {
callback(null, num);
}
}
isPortTaken(num, portResolve);
}
/** The routing is done based on the
game string or rather `roompass` in
connection request */
function pickCoreConfig(socket) {
var output = 'ini/';
if (socket.hostString.indexOf(",2,5,1") > -1) {
return "ini/goat.ini";
}
if (socket.hostString.indexOf(",4,5,1") > -1) {
return "ini/newgioh.ini";
}
if (socket.hostString[0] > '2') {
return output + socket.hostString[0] + '-config.ini';
} else {
/*load default configuration */
return output + 'config.ini';
}
}
/** send the YGOCore API commands back to the main process, some cleanup
is needed before sending the message. Basic logging for finding idiots
later after they have misbehaved or providing administrative ablities
to kill or act on games */
function handleCoreMessage(core_message_raw, port, socket, data, pid) {
if (core_message_raw.toString().indexOf("::::") < 0) {
return;
}
var core_message = core_message_raw.toString().split('|'),
n;
if (core_message[0].trim() === '::::network-ready') {
connectToCore(port, data, socket);
//cHistory.info('++GAME: ' + pid);
}
client.write({
password: process.env.OPERPASS,
action: 'gamelistEvent',
messagetype: 'coreMessage',
coreMessage: {
core_message_raw: core_message_raw.toString(),
port: port,
pid: pid,
game: socket.hostString
}
});
}
/**
* Checks if a given password is valid, returns true or false
* @param {string} passIn [[Description]]
* @returns {boolean} [[Description]]
*/
function legalPassword(passIn) {
if (passIn.length !== 24) {
console.log(' [ProcessCTOS]', 'Invalid password length', passIn);
return false;
}
var re = new RegExp("\\d\\d\\d(O|T)(O|T)(O|T)(\\d)+,(\\d)|(\\d\\d),\\d,\\d,(\\w)+,(\\w)+"),
output = re.test(passIn);
if (output) {
return true;
} else {
console.log(' [ProcessCTOS]', 'Invalid password construction');
return false;
}
}
/**Unlike DevPro, Salvation does not preload its
YGOCores. It calls them on demand. This posses a
few issues but provides routing flexiblity. When a
YGOCore is needed it needs to figure out a few
things. 1.) The configuration file, 2.) a port
number to use and 3.) if it is a valid duel to use
server resources on. */
function startCore(port, socket, data, callback) {
var configfile = pickCoreConfig(socket),
params = port + ' ' + configfile,
translated,
paramlist;
//console.log(configfile);
if (!legalPassword(socket.hostString)) {
//deal with bad game request
return;
}
translated = parseDuelOptions(socket.hostString);
if (configfile === 'ini/goat.ini') {
translated.allowedCards = 99;
translated.isTCGRuled = true;
}
paramlist = ['StandardStreamProtocol=true',
'Port=' + port,
'ClientVersion=0x1339',
'BanlistFile=../http/ygopro/lflist.conf',
'PrimaryScriptDirectory=' + primaryScripts[translated.allowedCards],
'SecondaryScriptDirectory=' + secondaryScripts[translated.allowedCards],
'ScriptDirectory=' + primaryScripts[translated.allowedCards],
'DatabaseFile=' + dbs[configfile],
'Rule=' + translated.allowedCards,
'Mode=' + translated.gameMode,
'Banlist=' + translated.banList,
'StartLp=' + translated.lifePoints,
'GameTimer=' + translated.timeLimit,
'NoCheckDeck=' + translated.isDeckChecked,
'NoShuffleDeck=' + translated.isShuffled,
'EnablePriority=' + translated.isTCGRuled
];
//console.log(paramlist.join(' '));
socket.core = childProcess.spawn(startDirectory + '/../ygosharp/YGOSharp.exe', paramlist, {
cwd: startDirectory + '/../YGOSharp'
}, function(error, stdout, stderr) {
//coreErrors.info(error, stdout, stderr);
handleCoreMessage('::::endduel|' + socket.hostString, port, socket, data, socket.core.pid);
console.log('game ended naturally');
});
socket.core.stdout.on('error', function(error) {
//coreErrors.info(error);
handleCoreMessage('::::endduel|' + socket.hostString, port, socket, data, socket.core.pid);
//socket.core.kill();
console.log('game ended with issues', error);
});
/* This is important, handle YGOCore API calls for managing the gamelist */
socket.core.stdout.on('data', function(core_message_raw) {
handleCoreMessage(core_message_raw, port, socket, data, socket.core.pid);
});
setInterval(function() {
if (socket.heartbeat) {
socket.heartbeat = 0;
return;
}
try {
socket.core.kill();
} catch (e) {
console.log('DOA');
}
}, 600000);
}
/** Call the server and make
sure the user is registered and
not banned. This call is beside
the normal duel request so the
user can connect to a game
possibly before being DC'd
based on connection speeds.
..and VOLIA! Game Request Routing */
function processIncomingTrasmission(data, socket, task) {
processTask(task, socket);
if (!socket.active_ygocore && socket.hostString) {
if (gamelist[socket.hostString]) {
socket.alpha = false;
connectToCore(gamelist[socket.hostString].port, data, socket);
} else {
portfinder(++portmin, portmax, function(error, port) {
socket.alpha = true;
startCore(port, socket, data);
});
}
/* after looping to much reset the ports*/
if (portmin === portmax) {
portmin = 30000 + process.env.PORTRANGE * 100;
}
return;
}
return data;
}
module.exports = processIncomingTrasmission;