|
|
| var enableRedirectionLinks = true;
|
| var enableRESTAPI = true;
|
|
|
| const defaultConfig = {
|
|
|
| HttpPort: 90,
|
| UseHTTPS: false,
|
|
|
| MatchmakerPort: 9999,
|
|
|
|
|
| LogToFile: true
|
| };
|
|
|
|
|
| const argv = require('yargs').argv;
|
|
|
| var configFile = (typeof argv.configFile != 'undefined') ? argv.configFile.toString() : '.\\config.json';
|
| console.log(`configFile ${configFile}`);
|
| const config = require('./modules/config.js').init(configFile, defaultConfig);
|
| console.log("Config: " + JSON.stringify(config, null, '\t'));
|
|
|
| const express = require('express');
|
| var cors = require('cors');
|
| const app = express();
|
| const http = require('http').Server(app);
|
| const fs = require('fs');
|
| const path = require('path');
|
| const logging = require('./modules/logging.js');
|
| logging.RegisterConsoleLogger();
|
|
|
| if (config.LogToFile) {
|
| logging.RegisterFileLogger('./logs');
|
| }
|
|
|
|
|
| var cirrusServers = new Map();
|
|
|
|
|
|
|
|
|
|
|
| if (typeof argv.HttpPort != 'undefined') {
|
| config.HttpPort = argv.HttpPort;
|
| }
|
| if (typeof argv.MatchmakerPort != 'undefined') {
|
| config.MatchmakerPort = argv.MatchmakerPort;
|
| }
|
|
|
| http.listen(config.HttpPort, () => {
|
| console.log('HTTP listening on *:' + config.HttpPort);
|
| });
|
|
|
|
|
| if (config.UseHTTPS) {
|
|
|
| const options = {
|
| key: fs.readFileSync(path.join(__dirname, './certificates/client-key.pem')),
|
| cert: fs.readFileSync(path.join(__dirname, './certificates/client-cert.pem'))
|
| };
|
|
|
| var https = require('https').Server(options, app);
|
|
|
|
|
| console.log('Redirecting http->https');
|
| app.use(function (req, res, next) {
|
| if (!req.secure) {
|
| if (req.get('Host')) {
|
| var hostAddressParts = req.get('Host').split(':');
|
| var hostAddress = hostAddressParts[0];
|
| if (httpsPort != 443) {
|
| hostAddress = `${hostAddress}:${httpsPort}`;
|
| }
|
| return res.redirect(['https://', hostAddress, req.originalUrl].join(''));
|
| } else {
|
| console.error(`unable to get host name from header. Requestor ${req.ip}, url path: '${req.originalUrl}', available headers ${JSON.stringify(req.headers)}`);
|
| return res.status(400).send('Bad Request');
|
| }
|
| }
|
| next();
|
| });
|
|
|
| https.listen(443, function () {
|
| console.log('Https listening on 443');
|
| });
|
| }
|
|
|
|
|
|
|
| function sendRetryResponse(res) {
|
| res.send(`All ${cirrusServers.size} Cirrus servers are in use. Retrying in <span id="countdown">10</span> seconds.
|
| <script>
|
| var countdown = document.getElementById("countdown").textContent;
|
| setInterval(function() {
|
| countdown--;
|
| if (countdown == 0) {
|
| window.location.reload(1);
|
| } else {
|
| document.getElementById("countdown").textContent = countdown;
|
| }
|
| }, 1000);
|
| </script>`);
|
| }
|
|
|
|
|
| function getAvailableCirrusServer() {
|
| for (cirrusServer of cirrusServers.values()) {
|
| if (cirrusServer.numConnectedClients === 0 && cirrusServer.ready === true) {
|
|
|
|
|
|
|
| if( cirrusServer.lastRedirect ) {
|
| if( ((Date.now() - cirrusServer.lastRedirect) / 1000) < 45 )
|
| continue;
|
| }
|
| cirrusServer.lastRedirect = Date.now();
|
|
|
| return cirrusServer;
|
| }
|
| }
|
|
|
| console.log('WARNING: No empty Cirrus servers are available');
|
| return undefined;
|
| }
|
|
|
| if(enableRESTAPI) {
|
|
|
| app.options('/signallingserver', cors())
|
| app.get('/signallingserver', cors(), (req, res) => {
|
| cirrusServer = getAvailableCirrusServer();
|
| if (cirrusServer != undefined) {
|
| res.json({ signallingServer: `${cirrusServer.address}:${cirrusServer.port}`});
|
| console.log(`Returning ${cirrusServer.address}:${cirrusServer.port}`);
|
| } else {
|
| res.json({ signallingServer: '', error: 'No signalling servers available'});
|
| }
|
| });
|
| }
|
|
|
| if(enableRedirectionLinks) {
|
|
|
| app.get('/', (req, res) => {
|
| cirrusServer = getAvailableCirrusServer();
|
| if (cirrusServer != undefined) {
|
| res.redirect(`http://${cirrusServer.address}:${cirrusServer.port}/`);
|
|
|
| console.log(`Redirect to ${cirrusServer.address}:${cirrusServer.port}`);
|
| } else {
|
| sendRetryResponse(res);
|
| }
|
| });
|
|
|
|
|
| app.get('/custom_html/:htmlFilename', (req, res) => {
|
| cirrusServer = getAvailableCirrusServer();
|
| if (cirrusServer != undefined) {
|
| res.redirect(`http://${cirrusServer.address}:${cirrusServer.port}/custom_html/${req.params.htmlFilename}`);
|
| console.log(`Redirect to ${cirrusServer.address}:${cirrusServer.port}`);
|
| } else {
|
| sendRetryResponse(res);
|
| }
|
| });
|
| }
|
|
|
|
|
|
|
|
|
|
|
| const net = require('net');
|
|
|
| function disconnect(connection) {
|
| console.log(`Ending connection to remote address ${connection.remoteAddress}`);
|
| connection.end();
|
| }
|
|
|
| const matchmaker = net.createServer((connection) => {
|
| connection.on('data', (data) => {
|
| try {
|
| message = JSON.parse(data);
|
|
|
| if(message)
|
| console.log(`Message TYPE: ${message.type}`);
|
| } catch(e) {
|
| console.log(`ERROR (${e.toString()}): Failed to parse Cirrus information from data: ${data.toString()}`);
|
| disconnect(connection);
|
| return;
|
| }
|
| if (message.type === 'connect') {
|
|
|
| cirrusServer = {
|
| address: message.address,
|
| port: message.port,
|
| numConnectedClients: 0,
|
| lastPingReceived: Date.now()
|
| };
|
| cirrusServer.ready = message.ready === true;
|
|
|
|
|
|
|
|
|
| if(message.playerConnected == true) {
|
| cirrusServer.numConnectedClients = 1;
|
| }
|
|
|
|
|
| let server = [...cirrusServers.entries()].find(([key, val]) => val.address === cirrusServer.address && val.port === cirrusServer.port);
|
|
|
|
|
| if (!server || server.size <= 0) {
|
| console.log(`Adding connection for ${cirrusServer.address.split(".")[0]} with playerConnected: ${message.playerConnected}`)
|
| cirrusServers.set(connection, cirrusServer);
|
| } else {
|
| console.log(`RECONNECT: cirrus server address ${cirrusServer.address.split(".")[0]} already found--replacing. playerConnected: ${message.playerConnected}`)
|
| var foundServer = cirrusServers.get(server[0]);
|
|
|
|
|
| if (foundServer) {
|
| cirrusServers.set(connection, cirrusServer);
|
| console.log(`Replacing server with original with numConn: ${cirrusServer.numConnectedClients}`);
|
| cirrusServers.delete(server[0]);
|
| } else {
|
| cirrusServers.set(connection, cirrusServer);
|
| console.log("Connection not found in Map() -- adding a new one");
|
| }
|
| }
|
| } else if (message.type === 'streamerConnected') {
|
|
|
| cirrusServer = cirrusServers.get(connection);
|
| if(cirrusServer) {
|
| cirrusServer.ready = true;
|
| console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} ready for use`);
|
| } else {
|
| disconnect(connection);
|
| }
|
| } else if (message.type === 'streamerDisconnected') {
|
|
|
| cirrusServer = cirrusServers.get(connection);
|
| if(cirrusServer) {
|
| cirrusServer.ready = false;
|
| console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} no longer ready for use`);
|
| } else {
|
| disconnect(connection);
|
| }
|
| } else if (message.type === 'clientConnected') {
|
|
|
| cirrusServer = cirrusServers.get(connection);
|
| if(cirrusServer) {
|
| cirrusServer.numConnectedClients++;
|
| console.log(`Client connected to Cirrus server ${cirrusServer.address}:${cirrusServer.port}`);
|
| } else {
|
| disconnect(connection);
|
| }
|
| } else if (message.type === 'clientDisconnected') {
|
|
|
| cirrusServer = cirrusServers.get(connection);
|
| if(cirrusServer) {
|
| cirrusServer.numConnectedClients--;
|
| console.log(`Client disconnected from Cirrus server ${cirrusServer.address}:${cirrusServer.port}`);
|
| } else {
|
| disconnect(connection);
|
| }
|
| } else if (message.type === 'ping') {
|
| cirrusServer = cirrusServers.get(connection);
|
| if(cirrusServer) {
|
| cirrusServer.lastPingReceived = Date.now();
|
| } else {
|
| disconnect(connection);
|
| }
|
| } else {
|
| console.log('ERROR: Unknown data: ' + JSON.stringify(message));
|
| disconnect(connection);
|
| }
|
| });
|
|
|
|
|
| connection.on('error', () => {
|
| cirrusServer = cirrusServers.get(connection);
|
| if(cirrusServer) {
|
| cirrusServers.delete(connection);
|
| console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} disconnected from Matchmaker`);
|
| } else {
|
| console.log(`Disconnected machine that wasn't a registered cirrus server, remote address: ${connection.remoteAddress}`);
|
| }
|
| });
|
| });
|
|
|
| matchmaker.listen(config.MatchmakerPort, () => {
|
| console.log('Matchmaker listening on *:' + config.MatchmakerPort);
|
| });
|
|
|