From e0977eac2261af6f1c89b0718800811b4ef689ab Mon Sep 17 00:00:00 2001 From: Ylian Saint-Hilaire Date: Thu, 12 Nov 2020 13:16:25 -0800 Subject: [PATCH] Server peering fixes. --- meshcentral.js | 3 +- meshdevicefile.js | 106 ++++++++++++++++++++++++++-------------------- meshuser.js | 2 +- 3 files changed, 64 insertions(+), 47 deletions(-) diff --git a/meshcentral.js b/meshcentral.js index 46d8c9eb..e1c3a28b 100644 --- a/meshcentral.js +++ b/meshcentral.js @@ -138,7 +138,7 @@ function CreateMeshCentralServer(config, args) { try { require('./pass').hash('test', function () { }, 0); } catch (e) { console.log('Old version of node, must upgrade.'); return; } // TODO: Not sure if this test works or not. // Check for invalid arguments - var validArguments = ['_', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'showitem', 'listuserids', 'showusergroups', 'shownodes', 'showallmeshes', 'showmeshes', 'showevents', 'showsmbios', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'xinstall', 'xuninstall', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbmerge', 'dbfix', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'logintoken', 'logintokenkey', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'vaultpushconfigfiles', 'vaultpullconfigfiles', 'vaultdeleteconfigfiles', 'configkey', 'loadconfigfromdb', 'npmpath', 'serverid', 'recordencryptionrecode', 'vault', 'token', 'unsealkey', 'name', 'log', 'dbstats', 'translate', 'createaccount', 'resetaccount', 'pass', 'adminaccount', 'removeaccount', 'domain', 'email']; + var validArguments = ['_', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'showitem', 'listuserids', 'showusergroups', 'shownodes', 'showallmeshes', 'showmeshes', 'showevents', 'showsmbios', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'xinstall', 'xuninstall', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbmerge', 'dbfix', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'logintoken', 'logintokenkey', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'vaultpushconfigfiles', 'vaultpullconfigfiles', 'vaultdeleteconfigfiles', 'configkey', 'loadconfigfromdb', 'npmpath', 'serverid', 'recordencryptionrecode', 'vault', 'token', 'unsealkey', 'name', 'log', 'dbstats', 'translate', 'createaccount', 'resetaccount', 'pass', 'adminaccount', 'removeaccount', 'domain', 'email', 'configfile']; for (var arg in obj.args) { obj.args[arg.toLocaleLowerCase()] = obj.args[arg]; if (validArguments.indexOf(arg.toLocaleLowerCase()) == -1) { console.log('Invalid argument "' + arg + '", use --help.'); return; } } if (obj.args.mongodb == true) { console.log('Must specify: --mongodb [connectionstring] \r\nSee https://docs.mongodb.com/manual/reference/connection-string/ for MongoDB connection string.'); return; } for (i in obj.config.settings) { obj.args[i] = obj.config.settings[i]; } // Place all settings into arguments, arguments have already been placed into settings so arguments take precedence. @@ -2621,6 +2621,7 @@ function getConfig(createSampleConfig) { // Read configuration file if present and change arguments. var config = {}, configFilePath = path.join(datapath, 'config.json'); + if (args.configfile) { configFilePath = path.join(datapath, args.configfile); } if (fs.existsSync(configFilePath)) { // Load and validate the configuration file try { config = require(configFilePath); } catch (e) { console.log('ERROR: Unable to parse ' + configFilePath + '.'); return null; } diff --git a/meshdevicefile.js b/meshdevicefile.js index b12b89a5..120cf8d8 100644 --- a/meshdevicefile.js +++ b/meshdevicefile.js @@ -121,7 +121,7 @@ module.exports.CreateMeshDeviceFile = function (parent, ws, res, req, domain, us }; function performRelay() { - if (obj.id == null) { try { obj.close(); } catch (e) { } return null; } // Attempt to connect without id, drop this. + if (obj.id == null) { try { obj.close(); } catch (e) { } return; } // Attempt to connect without id, drop this. if (obj.ws != null) { obj.ws._socket.setKeepAlive(true, 240000); } // Set TCP keep alive // Check the peer connection status @@ -137,7 +137,7 @@ module.exports.CreateMeshDeviceFile = function (parent, ws, res, req, domain, us delete obj.id; delete obj.ws; delete obj.peer; - return null; + return; } // Connect to peer @@ -160,9 +160,9 @@ module.exports.CreateMeshDeviceFile = function (parent, ws, res, req, domain, us parent.parent.debug('relay', 'FileRelay connected: ' + obj.id + ' (' + obj.req.clientIp + ' --> ' + obj.peer.req.clientIp + ')'); // Log the connection - if (sessionUser != null) { - var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: sessionUser._id, username: sessionUser.name, msg: "Started file transfer session" + ' \"' + obj.id + '\" from ' + obj.peer.req.clientIp + ' to ' + req.clientIp, protocol: req.query.p, nodeid: req.query.nodeid }; - parent.parent.DispatchEvent(['*', sessionUser._id], obj, event); + if (obj.user != null) { + var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msg: "Started file transfer session" + ' \"' + obj.id + '\" from ' + obj.peer.req.clientIp + ' to ' + req.clientIp, protocol: req.query.p, nodeid: req.query.nodeid }; + parent.parent.DispatchEvent(['*', obj.user._id], obj, event); } } else { // Connected already, drop this connection. @@ -171,60 +171,76 @@ module.exports.CreateMeshDeviceFile = function (parent, ws, res, req, domain, us delete obj.id; delete obj.ws; delete obj.peer; - return null; + return; } } else { // Wait for other relay connection parent.wsrelays[obj.id] = { peer1: obj, state: 1, timeout: setTimeout(closeBothSides, 30000) }; parent.parent.debug('relay', 'FileRelay holding: ' + obj.id + ' (' + obj.req.clientIp + ') ' + (obj.authenticated ? 'Authenticated' : '')); + if (obj.ws != null) { + // Websocket connection + obj.ws._socket.pause(); - // Check if a peer server has this connection - if (parent.parent.multiServer != null) { - var rsession = parent.wsPeerRelays[obj.id]; - if ((rsession != null) && (rsession.serverId > parent.parent.serverId)) { - // We must initiate the connection to the peer - parent.parent.multiServer.createPeerRelay(ws, req, rsession.serverId, obj.req.session.userid); - delete parent.wsrelays[obj.id]; - } else { - // Send message to other peers that we have this connection - parent.parent.multiServer.DispatchMessage(JSON.stringify({ action: 'relay', id: obj.id })); + // Check if a peer server has this connection + if (parent.parent.multiServer != null) { + var rsession = parent.wsPeerRelays[obj.id]; + if ((rsession != null) && (rsession.serverId > parent.parent.serverId)) { + // We must initiate the connection to the peer + parent.parent.multiServer.createPeerRelay(ws, req, rsession.serverId, obj.req.session.userid); + delete parent.wsrelays[obj.id]; + return; + } else { + + // Unexpected connection, drop it + if (obj.ws) { obj.ws.close(); } + parent.parent.debug('relay', 'FileRelay unexpected connection: ' + obj.id + ' (' + obj.req.clientIp + ')'); + delete obj.id; + delete obj.ws; + delete obj.peer; + return; + } } + } else { + // HTTP connection, Send message to other peers that we have this connection + parent.parent.multiServer.DispatchMessage(JSON.stringify({ action: 'relay', id: obj.id })); + return; } } } - } - // Websocket handling - if (obj.ws != null) { - // When data is received from the mesh relay web socket - obj.ws.on('message', function (data) { - if (typeof data == 'string') { - var cmd = null; - try { cmd = JSON.parse(data); } catch (ex) { } - if ((cmd == null) || (typeof cmd.op == 'string')) { - if (cmd.op == 'ok') { - setContentDispositionHeader(this.res, 'application/octet-stream', this.file, cmd.size, 'file.bin'); - } else { - try { this.res.sendStatus(401); } catch (ex) { } + // Websocket handling + if (obj.ws != null) { + // When data is received from the mesh relay web socket + obj.ws.on('message', function (data) { + if (this.res == null) { return; } // File download websocket does not have an HTTP peer, should not happen. + if (typeof data == 'string') { + var cmd = null; + try { cmd = JSON.parse(data); } catch (ex) { } + if ((cmd == null) || (typeof cmd.op == 'string')) { + if (cmd.op == 'ok') { + setContentDispositionHeader(this.res, 'application/octet-stream', this.file, cmd.size, 'file.bin'); + } else { + try { this.res.sendStatus(401); } catch (ex) { } + } } + } else { + var unpause = function unpauseFunc(err) { try { unpauseFunc.s.resume(); } catch (ex) { } } + unpause.s = this._socket; + this._socket.pause(); + try { this.res.write(data, unpause); } catch (ex) { } } - } else { - var unpause = function unpauseFunc(err) { try { unpauseFunc.s.resume(); } catch (ex) { } } - unpause.s = this._socket; - this._socket.pause(); - try { this.res.write(data, unpause); } catch (ex) { } - } - }); + }); - // If error, close both sides of the relay. - obj.ws.on('error', function (err) { - parent.relaySessionErrorCount++; - //console.log('FileRelay error from ' + obj.req.clientIp + ', ' + err.toString().split('\r')[0] + '.'); - closeBothSides(); - }); + // If error, close both sides of the relay. + obj.ws.on('error', function (err) { + parent.relaySessionErrorCount++; + //console.log('FileRelay error from ' + obj.req.clientIp + ', ' + err.toString().split('\r')[0] + '.'); + closeBothSides(); + }); - // If the relay web socket is closed, close both sides. - obj.ws.on('close', function (req) { closeBothSides(); }); + // If the relay web socket is closed, close both sides. + obj.ws.on('close', function (req) { closeBothSides(); }); + } } // Close both our side and the peer side. @@ -278,7 +294,7 @@ module.exports.CreateMeshDeviceFile = function (parent, ws, res, req, domain, us // Set the content disposition header for a HTTP response. // Because the filename can't have any special characters in it, we need to be extra careful. function setContentDispositionHeader(res, type, name, size, altname) { - var name = require('path').basename(name).split('\\').join('').split('/').join('').split(':').join('').split('*').join('').split('?').join('').split('"').join('').split('<').join('').split('>').join('').split('|').join('').split(' ').join('').split('\'').join(''); + if (name != null) { name = require('path').basename(name).split('\\').join('').split('/').join('').split(':').join('').split('*').join('').split('?').join('').split('"').join('').split('<').join('').split('>').join('').split('|').join('').split(' ').join('').split('\'').join(''); } else { name = altname; } try { var x = { 'Cache-Control': 'no-store', 'Content-Type': type, 'Content-Disposition': 'attachment; filename="' + name + '"' }; if (typeof size == 'number') { x['Content-Length'] = size; } diff --git a/meshuser.js b/meshuser.js index 4ef1e8f4..c8b02c94 100644 --- a/meshuser.js +++ b/meshuser.js @@ -240,7 +240,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use var routing = parent.parent.GetRoutingServerId(command.nodeid, 1); // 1 = MeshAgent routing type if (routing != null) { // Check if we have permission to send a message to that node - parent.GetNodeWithRights(domain, user, agent.dbNodeKey, function (node, rights, visible) { + parent.GetNodeWithRights(domain, user, command.nodeid, function (node, rights, visible) { if ((requiredRights != null) && ((rights & requiredRights) == 0)) { if (func) { func(false); return; } } // Check Required Rights if ((requiredNonRights != null) && (rights != MESHRIGHT_ADMIN) && ((rights & requiredNonRights) != 0)) { if (func) { func(false); return; } } // Check Required None Rights