Added new account creation and server peering flow control

Ylian Saint-Hilaire committed Sep 15, 2017 at 11:45 UTC 040440db79c9af4b5b9cba71f1cc55e8fccbe501
7 files changed +530 -193
meshagent.js
+34 -22
@@ -83,7 +83,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
83 }
84 }
85 else if (cmdid == 12) { // MeshCommand_AgentHash
86 - if ((msg.length == 36) && (obj.agentInfo != undefined) && (obj.agentInfo.update == true)) {
86 + if ((msg.length == 36) && (obj.agentInfo != null) && (obj.agentInfo.update == true)) {
87 var agenthash = obj.common.rstr2hex(msg.substring(4)).toLowerCase();
88 if (agenthash != obj.agentInfo.hash) {
89 // Mesh agent update required
@@ -168,7 +168,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
168 obj.send(obj.common.ShortToStr(2) + obj.common.ShortToStr(parent.agentCertificatAsn1.length) + parent.agentCertificatAsn1 + privateKey.sign(md)); // Command 2, certificate + signature
169
170 // Check the agent signature if we can
171 - if (obj.unauthsign != undefined) {
171 + if (obj.unauthsign != null) {
172 if (processAgentSignature(obj.unauthsign) == false) { disonnect(); return; } else { completeAgentConnection(); }
173 }
174 }
@@ -185,7 +185,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
185 obj.unauth.nodeid = obj.forge.pki.getPublicKeyFingerprint(obj.unauth.nodeCert.publicKey, { encoding: 'hex', md: obj.forge.md.sha256.create() });
186
187 // Check the agent signature if we can
188 - if (obj.agentnonce == undefined) { obj.unauthsign = msg.substring(4 + certlen); } else { if (processAgentSignature(msg.substring(4 + certlen)) == false) { disonnect(); return; } }
188 + if (obj.agentnonce == null) { obj.unauthsign = msg.substring(4 + certlen); } else { if (processAgentSignature(msg.substring(4 + certlen)) == false) { disonnect(); return; } }
189 completeAgentConnection();
190 }
191 else if (cmd == 3) {
@@ -248,7 +248,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
248 } else {
249 // Device already exists, look if changes has occured
250 device = nodes[0];
251 - if (device.agent == undefined) {
251 + if (device.agent == null) {
252 device.agent = { ver: obj.agentInfo.agentVersion, id: obj.agentInfo.agentId, caps: obj.agentInfo.capabilities }; change = 1;
253 } else {
254 var changes = [], change = 0;
@@ -292,7 +292,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
292
293 // Check if we need to make an native update check
294 obj.agentInfo = obj.parent.parent.meshAgentBinaries[obj.agentInfo.agentId];
295 - if ((obj.agentInfo != undefined) && (obj.agentInfo.update == true)) { obj.send(obj.common.ShortToStr(12) + obj.common.ShortToStr(0)); } // Ask the agent for it's executable binary hash
295 + if ((obj.agentInfo != null) && (obj.agentInfo.update == true)) { obj.send(obj.common.ShortToStr(12) + obj.common.ShortToStr(0)); } // Ask the agent for it's executable binary hash
296
297 // Check if we already have IP location information for this node
298 obj.db.Get('iploc_' + obj.remoteaddr, function (err, iplocs) {
@@ -364,52 +364,64 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
364 {
365 // Route a message.
366 // If this command has a sessionid, that is the target.
367 - if (command.sessionid != undefined) {
367 + if (command.sessionid != null) {
368 var splitsessionid = command.sessionid.split('/');
369 // Check that we are in the same domain and the user has rights over this node.
370 if ((splitsessionid[0] == 'user') && (splitsessionid[1] == domain.id)) {
371 // Check if this user has rights to get this message
372 - //if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 16) == 0)) return; // TODO!!!!!!!!!!!!!!!!!!!!!
372 + //if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 16) == 0)) return; // TODO!!!!!!!!!!!!!!!!!!!!!
373
374 - // See if the session is connected
374 + // See if the session is connected. If so, go ahead and send this message to the target node
375 var ws = obj.parent.wssessions2[command.sessionid];
376 -
377 - // Go ahead and send this message to the target node
378 - if (ws != undefined) {
376 + if (ws != null) {
377 command.nodeid = obj.dbNodeKey; // Set the nodeid, required for responses.
378 delete command.sessionid; // Remove the sessionid, since we are sending to that sessionid, so it's implyed.
379 ws.send(JSON.stringify(command));
380 + } else if (obj.parent.parent.multiServer != null) {
381 + // We need to send this message to other servers
382 + command.fromNodeid = obj.dbNodeKey;
383 + obj.parent.parent.multiServer.DispatchMessage(command);
384 }
385 }
384 - } else if (command.userid != undefined) { // If this command has a userid, that is the target.
386 + } else if (command.userid != null) { // If this command has a userid, that is the target.
387 var splituserid = command.userid.split('/');
388 // Check that we are in the same domain and the user has rights over this node.
389 if ((splituserid[0] == 'user') && (splituserid[1] == domain.id)) {
390 // Check if this user has rights to get this message
389 - //if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 16) == 0)) return; // TODO!!!!!!!!!!!!!!!!!!!!!
391 + //if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 16) == 0)) return; // TODO!!!!!!!!!!!!!!!!!!!!!
392
393 // See if the session is connected
394 var sessions = obj.parent.wssessions[command.userid];
395
396 // Go ahead and send this message to the target node
395 - if (sessions != undefined) {
397 + if (sessions != null) {
398 command.nodeid = obj.dbNodeKey; // Set the nodeid, required for responses.
399 delete command.userid; // Remove the userid, since we are sending to that userid, so it's implyed.
400 for (var i in sessions) { sessions[i].send(JSON.stringify(command)); }
401 }
402 }
403 } else { // Route this command to the mesh
404 + command.nodeid = obj.dbNodeKey;
405 + var cmdstr = JSON.stringify(command);
406 for (var userid in obj.parent.wssessions) { // Find all connected users for this mesh and send the message
407 var user = obj.parent.users[userid];
408 if (user) {
409 var rights = user.links[obj.dbMeshKey];
406 - if (rights != undefined) { // TODO: Look at what rights are needed for message routing
407 - command.nodeid = obj.dbNodeKey;
410 + if (rights != null) { // TODO: Look at what rights are needed for message routing
411 var sessions = obj.parent.wssessions[userid];
409 - for (var i in sessions) { sessions[i].send(JSON.stringify(command)); }
412 + // Send the message to all users on this server
413 + for (var i in sessions) { sessions[i].send(cmdstr); }
414 }
415 }
416 }
417 +
418 + // Send the message to all users of other servers
419 + if (obj.parent.parent.multiServer != null) {
420 + delete command.nodeid;
421 + command.fromNodeid = obj.dbNodeKey;
422 + command.meshid = obj.dbMeshKey;
423 + obj.parent.parent.multiServer.DispatchMessage(command);
424 + }
425 }
426 break;
427 }
@@ -455,10 +467,10 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
467
468 // Change the current core information string and event it
469 function ChangeAgentCoreInfo(command) {
458 - if ((command == undefined) || (command == null)) return; // Safety, should never happen.
470 + if ((command == null) || (command == null)) return; // Safety, should never happen.
471
472 // Check capabilities value
461 - if (command.caps == undefined || command.caps == null) { command.caps = 0; } else { if (typeof command.caps != 'number') command.caps = 0; }
473 + if (command.caps == null || command.caps == null) { command.caps = 0; } else { if (typeof command.caps != 'number') command.caps = 0; }
474
475 // Check that the mesh exists
476 obj.db.Get(obj.dbMeshKey, function (err, meshes) {
@@ -472,7 +484,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
484 var changes = [], change = 0;
485
486 // Check if anything changes
475 - if (device.agent.core != command.value) { if ((command.value == null) && (device.agent.core != undefined)) { delete device.agent.core; } else { device.agent.core = command.value; } change = 1; changes.push('agent core'); }
487 + if (device.agent.core != command.value) { if ((command.value == null) && (device.agent.core != null)) { delete device.agent.core; } else { device.agent.core = command.value; } change = 1; changes.push('agent core'); }
488 if ((device.agent.caps & 0xFFFFFFE7) != (command.caps & 0xFFFFFFE7)) { device.agent.caps = ((device.agent.caps & 24) + (command.caps & 0xFFFFFFE7)); change = 1; changes.push('agent capabilities'); } // Allow Javascript on the agent to change all capabilities except console and javascript support
489 if (command.intelamt) {
490 if (!device.intelamt) { device.intelamt = {}; }
@@ -504,7 +516,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
516
517 // Change the current core information string and event it
518 function ChangeAgentLocationInfo(command) {
507 - if ((command == undefined) || (command == null)) return; // Safety, should never happen.
519 + if ((command == null) || (command == null)) return; // Safety, should never happen.
520
521 // Check that the mesh exists
522 obj.db.Get(obj.dbMeshKey, function (err, meshes) {
@@ -539,7 +551,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
551
552 // Update the mesh agent tab in the database
553 function ChangeAgentTag(tag) {
542 - if (tag.length == 0) { tag = undefined; }
554 + if (tag.length == 0) { tag = null; }
555 // Get the node and change it if needed
556 obj.db.Get(obj.dbNodeKey, function (err, nodes) {
557 if (nodes.length != 1) return;
meshcentral.js
+40 -29
@@ -37,7 +37,7 @@ function CreateMeshCentralServer() {
37 obj.currentVer = null;
38 obj.maintenanceTimer = null;
39 obj.serverId = null;
40 -
40 +
41 // Create data and files folders if needed
42 try { obj.fs.mkdirSync(obj.datapath); } catch (e) { }
43 try { obj.fs.mkdirSync(obj.filespath); } catch (e) { }
@@ -84,7 +84,7 @@ function CreateMeshCentralServer() {
84 // Check if we need to install, start, stop, remove ourself as a background service
85 if ((obj.service != null) && ((obj.args.install == true) || (obj.args.uninstall == true) || (obj.args.start == true) || (obj.args.stop == true) || (obj.args.restart == true))) {
86 var env = [], xenv = ['user', 'port', 'mpsport', 'redirport', 'exactport', 'debug'];
87 - for (var i in xenv) { if (obj.args[xenv[i]] != undefined) { env.push({ name: 'mesh' + xenv[i], value: obj.args[xenv[i]] }); } } // Set some args as service environement variables.
87 + for (var i in xenv) { if (obj.args[xenv[i]] != null) { env.push({ name: 'mesh' + xenv[i], value: obj.args[xenv[i]] }); } } // Set some args as service environement variables.
88 var svc = new obj.service({ name: 'MeshCentral', description: 'MeshCentral Remote Management Server', script: process.argv[1] + '.js', env: env, wait: 2, grow: .5 });
89 svc.on('install', function () { console.log('MeshCentral service installed.'); svc.start(); });
90 svc.on('uninstall', function () { console.log('MeshCentral service uninstalled.'); process.exit(); });
@@ -150,7 +150,7 @@ function CreateMeshCentralServer() {
150
151 // Get current and latest MeshCentral server versions using NPM
152 obj.getLatestServerVersion = function (callback) {
153 - if (callback == undefined) return;
153 + if (callback == null) return;
154 var child_process = require('child_process');
155 var xprocess = child_process.exec('npm view meshcentral dist-tags.latest', function (error, stdout, stderr) { });
156 xprocess.data = '';
@@ -177,20 +177,20 @@ function CreateMeshCentralServer() {
177 if (require('fs').existsSync(obj.path.join(obj.datapath, 'config.json'))) {
178 // Load and validate the configuration file
179 try { obj.config = require(obj.path.join(obj.datapath, 'config.json')); } catch (e) { console.log('ERROR: Unable to parse ./data/config.json.'); return; }
180 - if (obj.config.domains == undefined) { obj.config.domains = {}; }
180 + if (obj.config.domains == null) { obj.config.domains = {}; }
181 for (var i in obj.config.domains) { if ((i.split('/').length > 1) || (i.split(' ').length > 1)) { console.log("ERROR: Error in config.json, domain names can't have spaces or /."); return; } }
182
183 // Set the command line arguments to the config file if they are not present
184 - if (obj.config.settings) { for (var i in obj.config.settings) { if (obj.args[i] == undefined) obj.args[i] = obj.config.settings[i]; } }
184 + if (obj.config.settings) { for (var i in obj.config.settings) { if (obj.args[i] == null) obj.args[i] = obj.config.settings[i]; } }
185 }
186
187 // Read environment variables. For a subset of arguments, we allow them to be read from environment variables.
188 var xenv = ['user', 'port', 'mpsport', 'redirport', 'exactport', 'debug'];
189 - for (var i in xenv) { if ((obj.args[xenv[i]] == undefined) && (process.env['mesh' + xenv[i]])) { obj.args[xenv[i]] = obj.common.toNumber(process.env['mesh' + xenv[i]]); } }
189 + for (var i in xenv) { if ((obj.args[xenv[i]] == null) && (process.env['mesh' + xenv[i]])) { obj.args[xenv[i]] = obj.common.toNumber(process.env['mesh' + xenv[i]]); } }
190
191 // Validate the domains, this is used for multi-hosting
192 - if (obj.config.domains == undefined) { obj.config.domains = {}; }
193 - if (obj.config.domains[''] == undefined) { obj.config.domains[''] = { }; }
192 + if (obj.config.domains == null) { obj.config.domains = {}; }
193 + if (obj.config.domains[''] == null) { obj.config.domains[''] = { }; }
194 var xdomains = {}; for (var i in obj.config.domains) { if (!obj.config.domains[i].title) { obj.config.domains[i].title = 'MeshCentral'; } if (!obj.config.domains[i].title2) { obj.config.domains[i].title2 = '2.0 Beta 1'; } xdomains[i.toLowerCase()] = obj.config.domains[i]; } obj.config.domains = xdomains;
195 var bannedDomains = ['public', 'private', 'images', 'scripts', 'styles', 'views']; // List of banned domains
196 for (var i in obj.config.domains) { for (var j in bannedDomains) { if (i == bannedDomains[j]) { console.log("ERROR: Domain '" + i + "' is not allowed domain name in ./data/config.json."); return; } } }
@@ -200,11 +200,11 @@ function CreateMeshCentralServer() {
200 //if (obj.servicelog != null) { var s = ''; for (var i in obj.args) { if (i != '_') { if (s.length > 0) { s += ', '; } s += i + "=" + obj.args[i]; } } logInfoEvent('MeshServer started with arguments: ' + s); }
201
202 // Look at passed in arguments
203 - if ((obj.args.ciralocalfqdn != undefined) && ((obj.args.lanonly == true) || (obj.args.wanonly == true))) { console.log("WARNING: CIRA local FQDN's ignored when server in LAN-only or WAN-only mode."); }
204 - if ((obj.args.ciralocalfqdn != undefined) && (obj.args.ciralocalfqdn.split(',').length > 4)) { console.log("WARNING: Can't have more than 4 CIRA local FQDN's. Ignoring value."); obj.args.ciralocalfqdn = undefined; }
205 - if (obj.args.port == undefined || typeof obj.args.port != 'number') { if (obj.args.notls == undefined) { obj.args.port = 443; } else { obj.args.port = 80; } }
206 - if (obj.args.mpsport == undefined || typeof obj.args.mpsport != 'number') obj.args.mpsport = 4433;
207 - if (obj.args.notls == undefined && obj.args.redirport == undefined) obj.args.redirport = 80;
203 + if ((obj.args.ciralocalfqdn != null) && ((obj.args.lanonly == true) || (obj.args.wanonly == true))) { console.log("WARNING: CIRA local FQDN's ignored when server in LAN-only or WAN-only mode."); }
204 + if ((obj.args.ciralocalfqdn != null) && (obj.args.ciralocalfqdn.split(',').length > 4)) { console.log("WARNING: Can't have more than 4 CIRA local FQDN's. Ignoring value."); obj.args.ciralocalfqdn = null; }
205 + if (obj.args.port == null || typeof obj.args.port != 'number') { if (obj.args.notls == null) { obj.args.port = 443; } else { obj.args.port = 80; } }
206 + if (obj.args.mpsport == null || typeof obj.args.mpsport != 'number') obj.args.mpsport = 4433;
207 + if (obj.args.notls == null && obj.args.redirport == null) obj.args.redirport = 80;
208 if (typeof obj.args.debug == 'number') obj.debugLevel = obj.args.debug;
209 if (obj.args.debug == true) obj.debugLevel = 1;
210 obj.db = require('./db.js').CreateDB(obj.args, obj.datapath);
@@ -249,13 +249,13 @@ function CreateMeshCentralServer() {
249 // Read or setup database configuration values
250 obj.db.Get('dbconfig', function (err, dbconfig) {
251 if (dbconfig.length == 1) { obj.dbconfig = dbconfig[0]; } else { obj.dbconfig = { _id: 'dbconfig', version: 1 }; }
252 - if (obj.dbconfig.amtWsEventSecret == undefined) { require('crypto').randomBytes(32, function (err, buf) { obj.dbconfig.amtWsEventSecret = buf.toString('hex'); obj.db.Set(obj.dbconfig); }); }
252 + if (obj.dbconfig.amtWsEventSecret == null) { require('crypto').randomBytes(32, function (err, buf) { obj.dbconfig.amtWsEventSecret = buf.toString('hex'); obj.db.Set(obj.dbconfig); }); }
253
254 // This is used by the user to create a username/password for a Intel AMT WSMAN event subscription
255 if (obj.args.getwspass) {
256 if (obj.args.getwspass.length == 64) {
257 require('crypto').randomBytes(6, function (err, buf) {
258 - while (obj.dbconfig.amtWsEventSecret == undefined) { process.nextTick(); }
258 + while (obj.dbconfig.amtWsEventSecret == null) { process.nextTick(); }
259 var username = buf.toString('hex');
260 var nodeid = obj.args.getwspass;
261 var pass = require('crypto').createHash('sha256').update(username.toLowerCase() + ":" + nodeid.toUpperCase() + ":" + obj.dbconfig.amtWsEventSecret).digest("base64").substring(0, 12).split("/").join("x").split("\\").join("x");
@@ -292,7 +292,7 @@ function CreateMeshCentralServer() {
292 // Setup Mesh Multi-Server if needed
293 obj.multiServer = require('./multiserver.js').CreateMultiServer(obj, obj.args);
294 if (obj.multiServer != null) {
295 - obj.serverId = obj.config.peers.serverId;
295 + obj.serverId = obj.multiServer.serverid;
296 for (var serverid in obj.config.peers.servers) { obj.peerConnectivityByNode[serverid] = {}; }
297 }
298
@@ -305,7 +305,7 @@ function CreateMeshCentralServer() {
305 }
306
307 // Setup and start the redirection server if needed
308 - if ((obj.args.redirport != undefined) && (typeof obj.args.redirport == 'number') && (obj.args.redirport != 0)) {
308 + if ((obj.args.redirport != null) && (typeof obj.args.redirport == 'number') && (obj.args.redirport != 0)) {
309 obj.redirserver = require('./redirserver.js').CreateRedirServer(obj, obj.db, obj.args, obj.certificates);
310 }
311
@@ -393,7 +393,7 @@ function CreateMeshCentralServer() {
393 }
394 obj.RemoveEventDispatchId = function (id) {
395 obj.debug(3, 'RemoveEventDispatchId', id);
396 - if (obj.eventsDispatch[id] != undefined) { delete obj.eventsDispatch[id]; }
396 + if (obj.eventsDispatch[id] != null) { delete obj.eventsDispatch[id]; }
397 }
398 obj.RemoveAllEventDispatch = function (target) {
399 obj.debug(3, 'RemoveAllEventDispatch');
@@ -420,13 +420,24 @@ function CreateMeshCentralServer() {
420 }
421 }
422 }
423 - if ((fromPeerServer == undefined) && (obj.multiServer != null) && (event.nopeers != 1)) { obj.multiServer.DispatchEvent(ids, source, event); }
423 + if ((fromPeerServer == null) && (obj.multiServer != null) && (event.nopeers != 1)) { obj.multiServer.DispatchEvent(ids, source, event); }
424 delete targets;
425 }
426
427 // Get the connection state of a node
428 obj.GetConnectivityState = function (nodeid) { return obj.connectivityByNode[nodeid]; }
429
430 + // Get the routing server id for a given node and connection type, can never be self.
431 + obj.GetRoutingServerId = function (nodeid, connectType) {
432 + if (obj.multiServer == null) return null;
433 + for (serverid in obj.peerConnectivityByNode) {
434 + if (serverid == obj.serverId) continue;
435 + var state = obj.peerConnectivityByNode[serverid][nodeid];
436 + if ((state != null) && ((state.connectivity & connectType) != 0)) { return { serverid: serverid, meshid: state.meshid }; }
437 + }
438 + return null;
439 + }
440 +
441 // Update the connection state of a node when in multi-server mode
442 // Update obj.connectivityByNode using obj.peerConnectivityByNode for the list of nodes in argument
443 obj.UpdateConnectivityState = function (nodeids) {
@@ -501,7 +512,7 @@ function CreateMeshCentralServer() {
512 if (connectType == 1) { state.agentPower = powerState; } else if (connectType == 2) { state.ciraPower = powerState; } else if (connectType == 4) { state.amtPower = powerState; }
513 var powerState = 0, oldPowerState = state.powerState;
514 if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; }
504 - if ((state.powerState == undefined) || (state.powerState != powerState)) {
515 + if ((state.powerState == null) || (state.powerState != powerState)) {
516 state.powerState = powerState;
517 eventConnectChange = 1;
518
@@ -531,7 +542,7 @@ function CreateMeshCentralServer() {
542 if (connectType == 1) { state.agentPower = powerState; } else if (connectType == 2) { state.ciraPower = powerState; } else if (connectType == 4) { state.amtPower = powerState; }
543 var powerState = 0;
544 if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; }
534 - if ((state.powerState == undefined) || (state.powerState != powerState)) { state.powerState = powerState; }
545 + if ((state.powerState == null) || (state.powerState != powerState)) { state.powerState = powerState; }
546
547 // Update the combined node state
548 var x = {}; x[nodeid] = 1;
@@ -552,7 +563,7 @@ function CreateMeshCentralServer() {
563
564 // Remove the agent connection from the nodes connection list
565 var state = obj.connectivityByNode[nodeid];
555 - if (state == undefined) return;
566 + if (state == null) return;
567
568 if ((state.connectivity & connectType) != 0) {
569 state.connectivity -= connectType;
@@ -566,7 +577,7 @@ function CreateMeshCentralServer() {
577 if (connectType == 1) { state.agentPower = 0; } else if (connectType == 2) { state.ciraPower = 0; } else if (connectType == 4) { state.amtPower = 0; }
578 var powerState = 0, oldPowerState = state.powerState;
579 if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; }
569 - if ((state.powerState == undefined) || (state.powerState != powerState)) {
580 + if ((state.powerState == null) || (state.powerState != powerState)) {
581 state.powerState = powerState;
582 eventConnectChange = 1;
583
@@ -583,7 +594,7 @@ function CreateMeshCentralServer() {
594 if (serverid == null) { serverid = obj.serverId; }
595 if (obj.peerConnectivityByNode[serverid] == null) return; // Guard against unknown serverid's
596 var state = obj.peerConnectivityByNode[serverid][nodeid];
586 - if (state == undefined) return;
597 + if (state == null) return;
598
599 // If existing state exist, remove this connection
600 if ((state.connectivity & connectType) != 0) {
@@ -597,7 +608,7 @@ function CreateMeshCentralServer() {
608 if (connectType == 1) { state.agentPower = 0; } else if (connectType == 2) { state.ciraPower = 0; } else if (connectType == 4) { state.amtPower = 0; }
609 var powerState = 0;
610 if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; }
600 - if ((state.powerState == undefined) || (state.powerState != powerState)) { state.powerState = powerState; }
611 + if ((state.powerState == null) || (state.powerState != powerState)) { state.powerState = powerState; }
612
613 // Update the combined node state
614 var x = {}; x[nodeid] = 1;
@@ -619,7 +630,7 @@ function CreateMeshCentralServer() {
630 obj.parent.defaultMeshCore = null;
631 obj.parent.defaultMeshCoreHash = null;
632 }
622 - if (func != undefined) { func(); }
633 + if (func != null) { func(); }
634 });
635 } else {
636 // Load default mesh agent core from meshcentral path if present
@@ -632,7 +643,7 @@ function CreateMeshCentralServer() {
643 obj.parent.defaultMeshCore = null;
644 obj.parent.defaultMeshCoreHash = null;
645 }
635 - if (func != undefined) { func(); }
646 + if (func != null) { func(); }
647 });
648 }
649 }
@@ -652,7 +663,7 @@ function CreateMeshCentralServer() {
663 stream.on('data', function (data) { this.hash.update(data, 'binary') });
664 stream.on('error', function (data) {
665 // If there is an error reading this file, make sure this agent is not in the agent table
655 - if (obj.meshAgentInstallScripts[this.info.id] != undefined) { delete obj.meshAgentInstallScripts[this.info.id]; }
666 + if (obj.meshAgentInstallScripts[this.info.id] != null) { delete obj.meshAgentInstallScripts[this.info.id]; }
667 });
668 stream.on('end', function () {
669 // Add the agent to the agent table with all information and the hash
@@ -710,7 +721,7 @@ function CreateMeshCentralServer() {
721 stream.on('data', function (data) { this.hash.update(data, 'binary') });
722 stream.on('error', function (data) {
723 // If there is an error reading this file, make sure this agent is not in the agent table
713 - if (obj.meshAgentBinaries[this.info.id] != undefined) { delete obj.meshAgentBinaries[this.info.id]; }
724 + if (obj.meshAgentBinaries[this.info.id] != null) { delete obj.meshAgentBinaries[this.info.id]; }
725 });
726 stream.on('end', function () {
727 // Add the agent to the agent table with all information and the hash
mesherrors.txt
+147
@@ -1795,3 +1795,150 @@ TypeError: Cannot read property 'meshid' of null
1795 at emitErrorNT (net.js:1265:8)
1796
1797
1798 +-------- 9/13/2017, 11:46:32 AM --------
1799 +
1800 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\webserver.js:1075
1801 + var r = obj.parent.GetRoutingServerId(command.nodeid, );
1802 + ^
1803 +SyntaxError: Unexpected token )
1804 + at exports.runInThisContext (vm.js:53:16)
1805 + at Module._compile (module.js:511:25)
1806 + at Object.Module._extensions..js (module.js:550:10)
1807 + at Module.load (module.js:456:32)
1808 + at tryModuleLoad (module.js:415:12)
1809 + at Function.Module._load (module.js:407:3)
1810 + at Module.require (module.js:466:17)
1811 + at require (internal/module.js:20:19)
1812 + at InternalFieldObject.ondone (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\meshcentral.js:304:45)
1813 +
1814 +
1815 +-------- 9/13/2017, 11:46:34 AM --------
1816 +
1817 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\webserver.js:1075
1818 + var r = obj.parent.GetRoutingServerId(command.nodeid, );
1819 + ^
1820 +SyntaxError: Unexpected token )
1821 + at exports.runInThisContext (vm.js:53:16)
1822 + at Module._compile (module.js:511:25)
1823 + at Object.Module._extensions..js (module.js:550:10)
1824 + at Module.load (module.js:456:32)
1825 + at tryModuleLoad (module.js:415:12)
1826 + at Function.Module._load (module.js:407:3)
1827 + at Module.require (module.js:466:17)
1828 + at require (internal/module.js:20:19)
1829 + at InternalFieldObject.ondone (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\meshcentral.js:304:45)
1830 +
1831 +
1832 +-------- 9/13/2017, 11:46:36 AM --------
1833 +
1834 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\webserver.js:1075
1835 + var r = obj.parent.GetRoutingServerId(command.nodeid, );
1836 + ^
1837 +SyntaxError: Unexpected token )
1838 + at exports.runInThisContext (vm.js:53:16)
1839 + at Module._compile (module.js:511:25)
1840 + at Object.Module._extensions..js (module.js:550:10)
1841 + at Module.load (module.js:456:32)
1842 + at tryModuleLoad (module.js:415:12)
1843 + at Function.Module._load (module.js:407:3)
1844 + at Module.require (module.js:466:17)
1845 + at require (internal/module.js:20:19)
1846 + at InternalFieldObject.ondone (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\meshcentral.js:304:45)
1847 +
1848 +
1849 +-------- 9/14/2017, 10:48:18 AM --------
1850 +
1851 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:451
1852 + console.log(ConnectToPeers);
1853 + ^
1854 +
1855 +ReferenceError: ConnectToPeers is not defined
1856 + at Object.obj.ConnectToPeers (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:451:21)
1857 + at Timeout._onTimeout (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:531:34)
1858 + at tryOnTimeout (timers.js:224:11)
1859 + at Timer.listOnTimeout (timers.js:198:5)
1860 +
1861 +
1862 +-------- 9/14/2017, 10:48:21 AM --------
1863 +
1864 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:451
1865 + console.log(ConnectToPeers);
1866 + ^
1867 +
1868 +ReferenceError: ConnectToPeers is not defined
1869 + at Object.obj.ConnectToPeers (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:451:21)
1870 + at Timeout._onTimeout (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:531:34)
1871 + at tryOnTimeout (timers.js:224:11)
1872 + at Timer.listOnTimeout (timers.js:198:5)
1873 +
1874 +
1875 +-------- 9/14/2017, 10:48:24 AM --------
1876 +
1877 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:451
1878 + console.log(ConnectToPeers);
1879 + ^
1880 +
1881 +ReferenceError: ConnectToPeers is not defined
1882 + at Object.obj.ConnectToPeers (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:451:21)
1883 + at Timeout._onTimeout (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:531:34)
1884 + at tryOnTimeout (timers.js:224:11)
1885 + at Timer.listOnTimeout (timers.js:198:5)
1886 +
1887 +
1888 +-------- 9/14/2017, 11:46:45 AM --------
1889 +
1890 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\webserver.js:645
1891 + var serverid = obj.GetRoutingServerId(req.query.host, 2); // Check for Intel CIRA connection
1892 + ^
1893 +
1894 +TypeError: obj.GetRoutingServerId is not a function
1895 + at C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\webserver.js:645:36
1896 + at newArguments.(anonymous function) (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\nedb\lib\executor.js:29:17)
1897 + at Cursor.execFn (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\nedb\lib\datastore.js:484:12)
1898 + at callback (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\nedb\lib\cursor.js:126:19)
1899 + at C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\nedb\lib\cursor.js:193:12
1900 + at C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\nedb\lib\datastore.js:329:14
1901 + at Object.async.eachSeries (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\async\lib\async.js:130:20)
1902 + at C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\nedb\lib\datastore.js:323:11
1903 + at fn (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\async\lib\async.js:582:34)
1904 + at Immediate._onImmediate (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\async\lib\async.js:498:34)
1905 +
1906 +
1907 +-------- 9/14/2017, 3:09:49 PM --------
1908 +
1909 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:573
1910 + for (var i in peerTunnel.pendingWs1Data) { peerTunnel.ws2.send(peerTunnel.pendingWs1Data[i]); }
1911 + ^
1912 +
1913 +TypeError: peerTunnel.ws2.send is not a function
1914 + at WebSocketClient.<anonymous> (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:573:75)
1915 + at emitOne (events.js:96:13)
1916 + at WebSocketClient.emit (events.js:188:7)
1917 + at WebSocketClient.succeedHandshake (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\websocket\lib\WebSocketClient.js:335:10)
1918 + at WebSocketClient.validateHandshake (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\websocket\lib\WebSocketClient.js:319:10)
1919 + at ClientRequest.handleRequestUpgrade (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\websocket\lib\WebSocketClient.js:248:14)
1920 + at emitThree (events.js:116:13)
1921 + at ClientRequest.emit (events.js:194:7)
1922 + at TLSSocket.socketOnData (_http_client.js:391:11)
1923 + at emitOne (events.js:96:13)
1924 +
1925 +
1926 +-------- 9/14/2017, 3:14:06 PM --------
1927 +
1928 +C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:573
1929 + for (var i in peerTunnel.pendingWs1Data) { peerTunnel.ws2.send(peerTunnel.pendingWs1Data[i]); }
1930 + ^
1931 +
1932 +TypeError: Cannot read property 'send' of null
1933 + at WebSocketClient.<anonymous> (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\multiserver.js:573:74)
1934 + at emitOne (events.js:96:13)
1935 + at WebSocketClient.emit (events.js:188:7)
1936 + at WebSocketClient.succeedHandshake (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\websocket\lib\WebSocketClient.js:335:10)
1937 + at WebSocketClient.validateHandshake (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\websocket\lib\WebSocketClient.js:319:10)
1938 + at ClientRequest.handleRequestUpgrade (C:\Users\Default.DESKTOP-M9I88C9\Desktop\AmtWebApp\meshcentral\node_modules\websocket\lib\WebSocketClient.js:248:14)
1939 + at emitThree (events.js:116:13)
1940 + at ClientRequest.emit (events.js:194:7)
1941 + at TLSSocket.socketOnData (_http_client.js:391:11)
1942 + at emitOne (events.js:96:13)
1943 +
1944 +
multiserver.js
+141 -15
@@ -13,6 +13,7 @@ module.exports.CreateMultiServer = function (parent, args) {
13 obj.forge = require('node-forge');
14 obj.outPeerServers = {}; // Outgoing peer servers
15 obj.peerServers = {}; // All connected servers (in & out). Only present in this list if the connection is setup
16 + obj.serverid = null;
17
18 // Create a mesh server module that will connect to other servers
19 obj.CreatePeerOutServer = function (parent, serverid, url) {
@@ -70,7 +71,7 @@ module.exports.CreateMultiServer = function (parent, args) {
71 obj.conn.on('close', function () { obj.parent.parent.debug(1, 'OutPeer ' + obj.serverid + ': Disconnected'); disconnect(); });
72
73 // Get the peer server's certificate and compute the server public key hash
73 - if (obj.ws.socket == undefined) return;
74 + if (obj.ws.socket == null) return;
75 var rawcertbuf = obj.ws.socket.getPeerCertificate().raw, rawcert = '';
76 for (var i = 0; i < rawcertbuf.length; i++) { rawcert += String.fromCharCode(rawcertbuf[i]); }
77 var serverCert = obj.forge.pki.certificateFromAsn1(obj.forge.asn1.fromDer(rawcert));
@@ -130,14 +131,14 @@ module.exports.CreateMultiServer = function (parent, args) {
131 obj.parent.parent.debug(1, 'OutPeer ' + obj.serverid + ': Verified peer connection to ' + obj.url);
132
133 // Send information about our server to the peer
133 - if (obj.connectionState == 15) { obj.conn.send(JSON.stringify({ action: 'info', serverid: obj.parent.peerConfig.serverId, dbid: obj.parent.parent.db.identifier, key: obj.parent.serverKey })); }
134 + if (obj.connectionState == 15) { obj.conn.send(JSON.stringify({ action: 'info', serverid: obj.parent.serverid, dbid: obj.parent.parent.db.identifier, key: obj.parent.serverKey })); }
135 //if ((obj.connectionState == 15) && (obj.connectHandler != null)) { obj.connectHandler(1); }
136 break;
137 }
138 case 4: {
139 // Server confirmed authentication, we are allowed to send commands to the server
140 obj.connectionState |= 8;
140 - if (obj.connectionState == 15) { obj.conn.send(JSON.stringify({ action: 'info', serverid: obj.parent.peerConfig.serverId, dbid: obj.parent.parent.db.identifier, key: obj.parent.serverKey })); }
141 + if (obj.connectionState == 15) { obj.conn.send(JSON.stringify({ action: 'info', serverid: obj.parent.serverid, dbid: obj.parent.parent.db.identifier, key: obj.parent.serverKey })); }
142 //if ((obj.connectionState == 15) && (obj.connectHandler != null)) { obj.connectHandler(1); }
143 break;
144 }
@@ -196,7 +197,7 @@ module.exports.CreateMultiServer = function (parent, args) {
197 if (obj.authenticated != 3) {
198 // We get the peer's serverid and database identifier.
199 if ((command.serverid != null) && (command.dbid != null)) {
199 - if (command.serverid == obj.parent.peerConfig.serverId) { console.log('ERROR: Same server ID, trying to peer with self. (' + obj.url + ', ' + command.serverid + ').'); return; }
200 + if (command.serverid == obj.parent.serverid) { console.log('ERROR: Same server ID, trying to peer with self. (' + obj.url + ', ' + command.serverid + ').'); return; }
201 if (command.dbid != obj.parent.parent.db.identifier) { console.log('ERROR: Database ID mismatch. Trying to peer to a server with the wrong database. (' + obj.url + ', ' + command.serverid + ').'); return; }
202 obj.peerServerId = command.serverid;
203 obj.peerServerKey = command.key;
@@ -282,7 +283,7 @@ module.exports.CreateMultiServer = function (parent, args) {
283 obj.send(obj.common.ShortToStr(2) + obj.common.ShortToStr(obj.agentCertificatAsn1.length) + obj.agentCertificatAsn1 + privateKey.sign(md)); // Command 2, certificate + signature
284
285 // Check the agent signature if we can
285 - if (obj.unauthsign != undefined) {
286 + if (obj.unauthsign != null) {
287 if (processAgentSignature(obj.unauthsign) == false) { disconnect(); return; } else { completePeerServerConnection(); }
288 }
289 }
@@ -299,7 +300,7 @@ module.exports.CreateMultiServer = function (parent, args) {
300 obj.unauth.nodeid = obj.forge.pki.getPublicKeyFingerprint(obj.unauth.nodeCert.publicKey, { encoding: 'hex', md: obj.forge.md.sha256.create() });
301
302 // Check the agent signature if we can
302 - if (obj.agentnonce == undefined) { obj.unauthsign = msg.substring(4 + certlen); } else { if (processAgentSignature(msg.substring(4 + certlen)) == false) { disconnect(); return; } }
303 + if (obj.agentnonce == null) { obj.unauthsign = msg.substring(4 + certlen); } else { if (processAgentSignature(msg.substring(4 + certlen)) == false) { disconnect(); return; } }
304 completePeerServerConnection();
305 }
306 else if (cmd == 3) {
@@ -327,7 +328,7 @@ module.exports.CreateMultiServer = function (parent, args) {
328 function completePeerServerConnection() {
329 if (obj.authenticated != 1) return;
330 obj.send(obj.common.ShortToStr(4));
330 - obj.send(JSON.stringify({ action: 'info', serverid: obj.parent.peerConfig.serverId, dbid: obj.parent.parent.db.identifier, key: obj.parent.serverKey }));
331 + obj.send(JSON.stringify({ action: 'info', serverid: obj.parent.serverid, dbid: obj.parent.parent.db.identifier, key: obj.parent.serverKey }));
332 obj.authenticated = 2;
333 }
334
@@ -359,7 +360,7 @@ module.exports.CreateMultiServer = function (parent, args) {
360 if (obj.authenticated != 3) {
361 // We get the peer's serverid and database identifier.
362 if ((command.serverid != null) && (command.dbid != null)) {
362 - if (command.serverid == obj.parent.peerConfig.serverId) { console.log('ERROR: Same server ID, trying to peer with self. (' + obj.remoteaddr + ', ' + command.serverid + ').'); return; }
363 + if (command.serverid == obj.parent.serverid) { console.log('ERROR: Same server ID, trying to peer with self. (' + obj.remoteaddr + ', ' + command.serverid + ').'); return; }
364 if (command.dbid != obj.parent.parent.db.identifier) { console.log('ERROR: Database ID mismatch. Trying to peer to a server with the wrong database. (' + obj.remoteaddr + ', ' + command.serverid + ').'); return; }
365 if (obj.parent.peerConfig.servers[command.serverid] == null) { console.log('ERROR: Unknown peer serverid: ' + command.serverid + ' (' + obj.remoteaddr + ').'); return; }
366 obj.peerServerId = command.serverid;
@@ -380,21 +381,32 @@ module.exports.CreateMultiServer = function (parent, args) {
381
382 // If we have no peering configuration, don't setup this object
383 if (obj.peerConfig == null) { return null; }
384 + obj.serverid = obj.parent.config.peers.serverId;
385 + if (obj.serverid == null) { obj.serverid = require("os").hostname(); }
386 + if (obj.parent.config.peers.servers[obj.serverid] == null) { console.log("Error: Unable to peer with other servers, \"" + obj.serverid + "\" not present in peer servers list."); return null; }
387
388 // Generate a cryptographic key used to encode and decode cookies
389 obj.generateCookieKey = function () {
390 return new Buffer(obj.crypto.randomBytes(32), 'binary').toString('hex');
391 }
392
393 + // Return the private key of a peer server
394 + obj.getServerCookieKey = function (serverid) {
395 + var server = obj.peerServers[serverid];
396 + if (server && server.peerServerKey) return server.peerServerKey;
397 + return null;
398 + }
399 +
400 // Encode an object as a cookie using a key
401 obj.encodeCookie = function (o, key) {
402 try {
392 - if (key == undefined) { key = obj.serverKey; }
403 + if (key == null) { key = obj.serverKey; }
404 + key = require('./common.js').hex2rstr(key);
405 o.time = Math.floor(Date.now() / 1000); // Add the cookie creation time
406 var msg = JSON.stringify(o);
407 msg = obj.crypto.createHmac('sha256', key.substring(16)).update(msg, 'binary', 'binary').digest('binary') + msg;
408 var iv = new Buffer(obj.crypto.randomBytes(16), 'binary');
397 - var cipher = obj.crypto.createCipheriv('aes-128-cbc', key.substring(0, 16), iv);
409 + var cipher = obj.crypto.createCipheriv('aes-128-cbc', new Buffer(key.substring(0, 16), 'binary'), iv);
410 crypted = cipher.update(msg, 'binary', 'binary');
411 crypted += cipher.final('binary');
412 var total = new Buffer(iv, 'binary').toString('hex') + new Buffer(crypted, 'binary').toString('hex'); // HEX: This is not an efficient concat, but it's very compatible.
@@ -406,11 +418,12 @@ module.exports.CreateMultiServer = function (parent, args) {
418 // Decode a cookie back into an object using a key. Return null if it's not a valid cookie.
419 obj.decodeCookie = function (cookie, key) {
420 try {
409 - if (key == undefined) { key = obj.serverKey; }
421 + if (key == null) { key = obj.serverKey; }
422 + key = require('./common.js').hex2rstr(key);
423 cookie = new Buffer(cookie.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex'); // HEX: This is not an efficient split, but it's very compatible.
424 var iv = new Buffer(cookie.substring(0, 32), 'hex');
425 var msg = new Buffer(cookie.substring(32), 'hex');
413 - var decipher = obj.crypto.createDecipheriv('aes-128-cbc', key.substring(0, 16), iv)
426 + var decipher = obj.crypto.createDecipheriv('aes-128-cbc', new Buffer(key.substring(0, 16), 'binary'), iv)
427 var dec = decipher.update(msg, 'binary', 'binary')
428 dec += decipher.final('binary');
429 var msg = dec.substring(32);
@@ -418,14 +431,14 @@ module.exports.CreateMultiServer = function (parent, args) {
431 var hash2 = obj.crypto.createHmac('sha256', key.substring(16)).update(msg, 'binary', 'binary').digest('binary');
432 if (hash1 !== hash2) { return null; }
433 var o = JSON.parse(msg);
421 - if ((o.time == null) || (o.time == undefined) || (typeof o.time != 'number')) { return null; }
434 + if ((o.time == null) || (o.time == null) || (typeof o.time != 'number')) { return null; }
435 o.time = o.time * 1000; // Decode the cookie creation time
436 o.dtime = Date.now() - o.time; // Decode how long ago the cookie was created
437 return o;
438 } catch (e) { return null; }
439 }
440
428 - // Dispatch an event to other MeshCentral2 peer servers
441 + // Dispatch an event to all other MeshCentral2 peer servers
442 obj.DispatchEvent = function (ids, source, event) {
443 var busmsg = JSON.stringify({ action: 'bus', ids: ids, event: event });
444 for (var serverid in obj.peerServers) { obj.peerServers[serverid].send(busmsg); }
@@ -436,11 +449,17 @@ module.exports.CreateMultiServer = function (parent, args) {
449 for (var serverid in obj.peerServers) { obj.peerServers[serverid].send(msg); }
450 }
451
452 + // Dispatch a message to other MeshCentral2 peer servers
453 + obj.DispatchMessageSingleServer = function (msg, serverid) {
454 + var server = obj.peerServers[serverid];
455 + if (server != null) { server.send(msg); }
456 + }
457 +
458 // Attempt to connect to all peers
459 obj.ConnectToPeers = function () {
460 for (serverId in obj.peerConfig.servers) {
461 // We will only connect to names that are larger then ours. This way, eveyone has one connection to everyone else (no cross-connections).
443 - if ((serverId > obj.peerConfig.serverId) && (obj.peerConfig.servers[serverId].url != null) && (obj.outPeerServers[serverId] == null)) {
462 + if ((serverId > obj.serverid) && (obj.peerConfig.servers[serverId].url != null) && (obj.outPeerServers[serverId] == null)) {
463 obj.outPeerServers[serverId] = obj.CreatePeerOutServer(obj, serverId, obj.peerConfig.servers[serverId].url);
464 }
465 }
@@ -484,7 +503,114 @@ module.exports.CreateMultiServer = function (parent, args) {
503 obj.parent.ClearConnectivityState(msg.meshid, msg.nodeid, msg.connectType, peerServerId);
504 break;
505 }
506 + case 'msg': {
507 + if (msg.sessionid != null) {
508 + // Route this message to a connected user session
509 + if (command.fromNodeid != null) { command.nodeid = command.fromNodeid; delete command.fromNodeid; }
510 + var ws = obj.parent.webserver.wssessions2[command.sessionid];
511 + if (ws != null) { ws.send(JSON.stringify(command)); }
512 + } else if (msg.nodeid != null) {
513 + // Route this message to a connected agent
514 + if (command.fromSessionid != null) { command.sessionid = command.fromSessionid; delete command.fromSessionid; }
515 + var agent = obj.parent.webserver.wsagents[msg.nodeid];
516 + if (agent != null) { delete msg.nodeid; agent.send(JSON.stringify(msg)); } // Remove the nodeid since it's implyed and send the message to the agent
517 + } else if (msg.meshid != null) {
518 + // Route this message to all users of this mesh
519 + if (command.fromNodeid != null) { command.nodeid = command.fromNodeid; delete command.fromNodeid; }
520 + var cmdstr = JSON.stringify(command);
521 + for (var userid in obj.parent.webserver.wssessions) { // Find all connected users for this mesh and send the message
522 + var user = obj.parent.webserver.users[userid];
523 + if (user) {
524 + var rights = user.links[msg.meshid];
525 + if (rights != null) { // TODO: Look at what rights are needed for message routing
526 + var sessions = obj.parent.webserver.wssessions[userid];
527 + // Send the message to all users on this server
528 + for (var i in sessions) { sessions[i].send(cmdstr); }
529 + }
530 + }
531 + }
532 + }
533 + break;
534 + }
535 + }
536 + }
537 +
538 + // Create a tunnel connection to a peer server
539 + obj.createPeerRelay = function (ws, req, serverid, user) {
540 + var server = obj.peerServers[serverid];
541 + if ((server == null) || (server.peerServerKey == null)) { return null; }
542 + var cookieKey = server.peerServerKey;
543 +
544 + // Build the connection URL
545 + var path = req.path;
546 + if (path[0] == '/') path = path.substring(1);
547 + if (path.substring(path.length - 11) == '/.websocket') { path = path.substring(0, path.length - 11); }
548 + var queryStr = ''
549 + for (var i in req.query) { queryStr += ((queryStr == '') ? '?' : '&') + i + '=' + req.query[i]; }
550 + queryStr += ((queryStr == '') ? '?' : '&') + 'auth=' + obj.encodeCookie({ userid: user._id, domainid: user.domain }, cookieKey);
551 + var url = obj.peerConfig.servers[serverid].url + path + queryStr;
552 +
553 + // Setup an connect the web socket
554 + var tunnel = obj.createPeerRelayEx(ws, url, serverid);
555 + tunnel.connect();
556 + }
557 +
558 + // Create a tunnel connection to a peer server
559 + // We assume that "ws" is paused already.
560 + obj.createPeerRelayEx = function (ws, url, serverid) {
561 + var peerTunnel = { parent: obj, ws1: ws, ws2: null, url: url, serverid: serverid };
562 +
563 + peerTunnel.connect = function () {
564 + // Get the web socket setup
565 + var WebSocketClient = require('websocket').client;
566 + peerTunnel.wsclient = new WebSocketClient();
567 +
568 + // Register the connection failed event
569 + peerTunnel.wsclient.on('connectFailed', function (error) { peerTunnel.parent.parent.debug(1, 'FTunnel ' + obj.serverid + ': Failed connection'); disconnect(); });
570 +
571 + // Register the connection event
572 + peerTunnel.wsclient.on('connect', function (connection) {
573 + peerTunnel.ws2 = connection;
574 +
575 + // If error, do nothing
576 + peerTunnel.ws2.on('error', function (err) { peerTunnel.parent.parent.debug(1, 'FTunnel: Connection Error: ' + err); peerTunnel.close(); });
577 +
578 + // If the mesh agent web socket is closed, clean up.
579 + peerTunnel.ws2.on('close', function (req) { peerTunnel.parent.parent.debug(1, 'FTunnel disconnect ' + peerTunnel.nodeid); peerTunnel.close(); });
580 +
581 + // If a message is received from the peer, Peer ---> Browser
582 + peerTunnel.ws2.on('message', function (msg) { if (msg.type == 'binary') { peerTunnel.ws2.pause(); peerTunnel.ws1.send(msg.binaryData, function () { peerTunnel.ws2.resume(); }); } });
583 +
584 + // Resume the web socket to start the data flow
585 + peerTunnel.ws1.resume();
586 + });
587 +
588 + // If a message is received from the browser, Browser ---> Peer
589 + peerTunnel.ws1.on('message', function (msg) { peerTunnel.ws1.pause(); peerTunnel.ws2.send(msg, function () { peerTunnel.ws1.resume(); }); });
590 +
591 + // If error, do nothing
592 + peerTunnel.ws1.on('error', function (err) { console.log(err); peerTunnel.close(); });
593 +
594 + // If the web socket is closed, close the associated TCP connection.
595 + peerTunnel.ws1.on('close', function (req) { peerTunnel.parent.parent.debug(1, 'FTunnel disconnect ' + peerTunnel.nodeid); peerTunnel.close(); });
596 +
597 + peerTunnel.wsclient.connect(peerTunnel.url, null, null, null, { rejectUnauthorized: false });
598 + }
599 +
600 + // Disconnect both sides of the tunnel
601 + peerTunnel.close = function (arg) {
602 + if (arg == 2) {
603 + // Hard close, close the TCP socket
604 + try { peerTunnel.ws1._socket._parent.end(); peerTunnel.parent.parent.debug(1, 'FTunnel1: Hard disconnect'); } catch (e) { console.log(e); }
605 + try { peerTunnel.ws2._socket._parent.end(); peerTunnel.parent.parent.debug(1, 'FTunnel2: Hard disconnect'); } catch (e) { console.log(e); }
606 + } else {
607 + // Soft close, close the websocket
608 + try { peerTunnel.ws1.close(); peerTunnel.parent.parent.debug(1, 'FTunnel1: Soft disconnect '); } catch (e) { console.log(e); }
609 + try { peerTunnel.ws2.close(); peerTunnel.parent.parent.debug(1, 'FTunnel2: Soft disconnect '); } catch (e) { console.log(e); }
610 + }
611 }
612 +
613 + return peerTunnel;
614 }
615
616 obj.serverKey = obj.generateCookieKey();
package.json
+1 -1
@@ -1,6 +1,6 @@
1 {
2 "name": "meshcentral",
3 - "version": "0.0.7-u",
3 + "version": "0.0.7-w",
4 "keywords": [
5 "Remote Management",
6 "Intel AMT",
views/login.handlebars
+8 -1
@@ -87,6 +87,10 @@
87 <td align=right>Password Hint:</td>
88 <td><input id=apasswordhint type=text name=apasswordhint autocomplete=off maxlength=250 /></td>
89 </tr>
90 + <tr id=newAccountPass title="Enter the account creation token">
91 + <td align=right>Creation Token:</td>
92 + <td><input id=anewaccountpass type=password name=anewaccountpass autocomplete=off maxlength=250 onchange=validateCreate() onkeyup=validateCreate() /></td>
93 + </tr>
94 <tr>
95 <td colspan=2>
96 <div style=float:right><input id=createButton type=submit value="Create Account" disabled="disabled" /></div>
@@ -136,6 +140,7 @@
140 </div>
141 <script>
142 var passhint = "{{{passhint}}}";
143 + var newAccountPass = {{{newAccountPass}}};
144
145 function startup() {
146 window.onresize = center;
@@ -145,6 +150,7 @@
150 if ('{{loginmode}}' != '') { go({{loginmode}}); } else { go(1); }
151 QV('newAccountDiv', '{{{newAccount}}}' != '0' );
152 if ((passhint != null) && (passhint.length > 0)) { QV("showPassHintLink", true); }
153 + QV("anewaccountpass", (newAccountPass == 1));
154 }
155
156 function showPassHint() {
@@ -172,7 +178,8 @@
178
179 function validateCreate() {
180 setDialogMode(0);
175 - var ok = (Q('ausername').value.length > 0 && Q('aemail').value.length > 0 && Q('apassword1').value.length > 0 && Q('apassword2').value == Q('apassword1').value);
181 + var ok = (Q('ausername').value.length > 0 && Q('aemail').value.length > 0 && Q('apassword1').value.length > 0 && (Q('apassword2').value == Q('apassword1').value));
182 + if ((newAccountPass == 1) && (Q('anewaccountpass').value.length == 0)) { ok = false; }
183 QE('createButton', ok);
184 if (Q('apassword1').value == '') {
185 QH('passWarning', '');
webserver.js
+159 -125
@@ -108,7 +108,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
108
109 // Session-persisted message middleware
110 obj.app.use(function (req, res, next) {
111 - if (req.session != undefined) {
111 + if (req.session != null) {
112 var err = req.session.error;
113 var msg = req.session.success;
114 var passhint = req.session.passhint;
@@ -146,7 +146,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
146 // Query the db for the given username
147 if (!user) return fn(new Error('cannot find user'));
148 // Apply the same algorithm to the POSTed password, applying the hash against the pass / salt, if there is a match we found the user
149 - if (user.salt == undefined) {
149 + if (user.salt == null) {
150 fn(new Error('invalid password'));
151 } else {
152 obj.hash(pass, user.salt, function (err, hash) {
@@ -250,6 +250,13 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
250 req.session.error = '<b style=color:#8C001A>Unable to create account.</b>';;
251 res.redirect(domain.url);
252 } else {
253 + // Check if there is domain.newAccountToken, check if supplied token is valid
254 + if ((domain.newAccountsPass != null) && (domain.newAccountsPass != '') && (req.body.anewaccountpass != domain.newAccountsPass)) {
255 + req.session.loginmode = 2;
256 + req.session.error = '<b style=color:#8C001A>Invalid account creation token.</b>';
257 + res.redirect(domain.url);
258 + return;
259 + }
260 // Check if user exists
261 if (obj.users['user/' + domain.id + '/' + req.body.username.toLowerCase()]) {
262 req.session.loginmode = 2;
@@ -334,7 +341,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
341 req.session.userid = 'user/' + domain.id + '/~';
342 req.session.domainid = domain.id;
343 req.session.currentNode = '';
337 - if (obj.users[req.session.userid] == undefined) {
344 + if (obj.users[req.session.userid] == null) {
345 // Create the dummy user ~ with impossible password
346 obj.users[req.session.userid] = { type: 'user', _id: req.session.userid, name: '~', email: '~', domain: domain.id, siteadmin: 0xFFFFFFFF };
347 obj.db.SetUser(obj.users[req.session.userid]);
@@ -374,14 +381,14 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
381 res.render(obj.path.join(__dirname, 'views/default'), { viewmode: viewmode, currentNode: currentNode, logoutControl: logoutcontrol, title: domain.title, title2: domain.title2, domainurl: domain.url, domain: domain.id, debuglevel: parent.debugLevel, serverDnsName: obj.certificates.CommonName, serverPublicPort: args.port, noServerBackup: (args.noserverbackup == 1 ? 1 : 0), features: features, mpspass: args.mpspass });
382 } else {
383 // Send back the login application
377 - res.render(obj.path.join(__dirname, 'views/login'), { loginmode: req.session.loginmode, rootCertLink: getRootCertLink(), title: domain.title, title2: domain.title2, newAccount: domain.newAccounts, serverDnsName: obj.certificates.CommonName, serverPublicPort: obj.args.port });
384 + res.render(obj.path.join(__dirname, 'views/login'), { loginmode: req.session.loginmode, rootCertLink: getRootCertLink(), title: domain.title, title2: domain.title2, newAccount: domain.newAccounts, newAccountPass: ((domain.newAccountsPass == null)?0:1), serverDnsName: obj.certificates.CommonName, serverPublicPort: obj.args.port });
385 }
386 }
387
388 // Get the link to the root certificate if needed
389 function getRootCertLink() {
390 // TODO: This is not quite right, we need to check if the HTTPS certificate is issued from MeshCentralRoot, if so, add this download link.
384 - if (obj.args.notls == undefined && obj.certificates.RootName.substring(0, 16) == 'MeshCentralRoot-') { return '<a href=/MeshServerRootCert.cer title="Download the root certificate for this server">Root Certificate</a>'; }
391 + if (obj.args.notls == null && obj.certificates.RootName.substring(0, 16) == 'MeshCentralRoot-') { return '<a href=/MeshServerRootCert.cer title="Download the root certificate for this server">Root Certificate</a>'; }
392 return '';
393 }
394
@@ -436,7 +443,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
443 scriptFile.scriptBlocks[3].vars.password.value = obj.args.mpspass ? obj.args.mpspass : 'A@xew9rt'; // Set the password
444 scriptFile.scriptBlocks[4].vars.AccessInfo1.value = obj.certificates.CommonName + ':' + obj.args.mpsport; // Set the primary server name:port to set periodic timer
445 //scriptFile.scriptBlocks[4].vars.AccessInfo2.value = obj.certificates.CommonName + ':' + obj.args.mpsport; // Set the secondary server name:port to set periodic timer
439 - if (obj.args.ciralocalfqdn != undefined) { scriptFile.scriptBlocks[6].vars.DetectionStrings.value = obj.args.ciralocalfqdn; } // Set the environment detection local FQDN's
446 + if (obj.args.ciralocalfqdn != null) { scriptFile.scriptBlocks[6].vars.DetectionStrings.value = obj.args.ciralocalfqdn; } // Set the environment detection local FQDN's
447
448 // Compile the script
449 var scriptEngine = require('./amtscript.js').CreateAmtScriptEngine();
@@ -461,7 +468,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
468 scriptFile.scriptBlocks[3].vars.password.value = obj.args.mpspass ? obj.args.mpspass : 'A@xew9rt'; // Set the password
469 scriptFile.scriptBlocks[4].vars.AccessInfo1.value = obj.certificates.CommonName + ':' + obj.args.mpsport; // Set the primary server name:port to set periodic timer
470 //scriptFile.scriptBlocks[4].vars.AccessInfo2.value = obj.certificates.CommonName + ':' + obj.args.mpsport; // Set the secondary server name:port to set periodic timer
464 - if (obj.args.ciralocalfqdn != undefined) { scriptFile.scriptBlocks[6].vars.DetectionStrings.value = obj.args.ciralocalfqdn; } // Set the environment detection local FQDN's
471 + if (obj.args.ciralocalfqdn != null) { scriptFile.scriptBlocks[6].vars.DetectionStrings.value = obj.args.ciralocalfqdn; } // Set the environment detection local FQDN's
472
473 // Compile the script
474 var scriptEngine = require('./amtscript.js').CreateAmtScriptEngine();
@@ -509,9 +516,9 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
516 // Download a file from the server
517 function handleDownloadFile(req, res) {
518 var domain = getDomain(req);
512 - if ((req.query.link == undefined) || (req.session == undefined) || (req.session.userid == undefined) || (domain == null) || (domain.userQuota == -1)) { res.sendStatus(404); return; }
519 + if ((req.query.link == null) || (req.session == null) || (req.session.userid == null) || (domain == null) || (domain.userQuota == -1)) { res.sendStatus(404); return; }
520 var user = obj.users[req.session.userid];
514 - if (user == undefined) { res.sendStatus(404); return; }
521 + if (user == null) { res.sendStatus(404); return; }
522 var file = getServerFilePath(user, domain, req.query.link);
523 if (file == null) { res.sendStatus(404); return; }
524 res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=\"' + file.name + '\"' });
@@ -528,7 +535,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
535 var multiparty = require('multiparty');
536 var form = new multiparty.Form();
537 form.parse(req, function (err, fields, files) {
531 - if ((fields == undefined) || (fields.attrib == undefined) || (fields.attrib.length != 1)) { res.sendStatus(404); return; }
538 + if ((fields == null) || (fields.attrib == null) || (fields.attrib.length != 1)) { res.sendStatus(404); return; }
539 for (var i in files.files) {
540 var file = files.files[i];
541 readEntireTextFile(file.path, function (data) {
@@ -552,13 +559,13 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
559 var multiparty = require('multiparty');
560 var form = new multiparty.Form();
561 form.parse(req, function (err, fields, files) {
555 - if ((fields == undefined) || (fields.link == undefined) || (fields.link.length != 1)) { res.sendStatus(404); return; }
562 + if ((fields == null) || (fields.link == null) || (fields.link.length != 1)) { res.sendStatus(404); return; }
563 var xfile = getServerFilePath(user, domain, decodeURIComponent(fields.link[0]));
564 if (xfile == null) { res.sendStatus(404); return; }
565 // Get total bytes in the path
566 var totalsize = readTotalFileSize(xfile.fullpath);
567 if (totalsize < xfile.quota) { // Check if the quota is not already broken
561 - if (fields.name != undefined) {
568 + if (fields.name != null) {
569 // Upload method where all the file data is within the fields.
570 var names = fields.name[0].split('*'), sizes = fields.size[0].split('*'), types = fields.type[0].split('*'), datas = fields.data[0].split('*');
571 if ((names.length == sizes.length) && (types.length == datas.length) && (names.length == types.length)) {
@@ -591,11 +598,11 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
598 obj.subscribe = function (userid, target) {
599 var user = obj.users[userid];
600 var subscriptions = [userid, 'server-global'];
594 - if (user.siteadmin != undefined) {
601 + if (user.siteadmin != null) {
602 if (user.siteadmin == 0xFFFFFFFF) subscriptions.push('*');
603 if ((user.siteadmin & 2) != 0) subscriptions.push('server-users');
604 }
598 - if (user.links != undefined) {
605 + if (user.links != null) {
606 for (var i in user.links) { subscriptions.push(i); }
607 }
608 obj.parent.RemoveAllEventDispatch(target);
@@ -607,12 +614,27 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
614 function handleRelayWebSocket(ws, req) {
615 var node, domain = getDomain(req);
616 // Check if this is a logged in user
610 - if (!req.session || !req.session.userid) { return; } // Web socket attempt without login, disconnect.
611 - if (req.session.domainid != domain.id) { console.log('ERR: Invalid domain'); return; }
612 - var user = obj.users[req.session.userid];
617 + var user, peering = true;
618 + if (req.query.auth == null) {
619 + // Use ExpressJS session
620 + if (!req.session || !req.session.userid) { return; } // Web socket attempt without login, disconnect.
621 + if (req.session.domainid != domain.id) { console.log('ERR: Invalid domain'); return; }
622 + user = obj.users[req.session.userid];
623 + } else {
624 + // Get the session from the cookie
625 + if (obj.parent.multiServer == null) { return; }
626 + var session = obj.parent.multiServer.decodeCookie(req.query.auth);
627 + if (session == null) { console.log('ERR: Invalid cookie'); return; }
628 + if (session.domainid != domain.id) { console.log('ERR: Invalid domain'); return; }
629 + user = obj.users[session.userid];
630 + peering = false; // Don't allow the connection to jump again to a different server
631 + }
632 if (!user) { console.log('ERR: Not a user'); return; }
633 Debug(1, 'Websocket relay connected from ' + user.name + ' for ' + req.query.host + '.');
615 -
634 +
635 + // Hold this socket until we are ready.
636 + ws.pause();
637 +
638 // Fetch information about the target
639 obj.db.Get(req.query.host, function (err, docs) {
640 if (docs.length == 0) { console.log('ERR: Node not found'); return; }
@@ -627,19 +649,33 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
649 // Check what connectivity is available for this node
650 var state = parent.GetConnectivityState(req.query.host);
651 var conn = 0;
630 - if (!state || state.connectivity == 0) {
631 - conn = 4; // DEBUG: Allow local connections for now... change this later when we can monitor Intel AMT machines and confirm routing before connections.
632 - //Debug(1, 'ERR: No routing possible (1)');
633 - //try { ws.close(); } catch (e) { }
634 - //return;
635 - } else {
636 - conn = state.connectivity;
652 + if (!state || state.connectivity == 0) { Debug(1, 'ERR: No routing possible (1)'); try { ws.close(); } catch (e) { } return; } else { conn = state.connectivity; }
653 +
654 + // Check what server needs to handle this connection
655 + if ((obj.parent.multiServer != null) && (peering == true)) {
656 + var server = obj.parent.GetRoutingServerId(req.query.host, 2); // Check for Intel CIRA connection
657 + if (server != null) {
658 + if (server.serverid != obj.parent.serverId) {
659 + // Do local Intel CIRA routing using a different server
660 + Debug(1, 'Route Intel AMT CIRA connection to peer server: ' + server.serverid);
661 + obj.parent.multiServer.createPeerRelay(ws, req, server.serverid, user);
662 + return;
663 + }
664 + } else {
665 + server = obj.parent.GetRoutingServerId(req.query.host, 4); // Check for local Intel AMT connection
666 + if ((server != null) && (server.serverid != obj.parent.serverId)) {
667 + // Do local Intel AMT routing using a different server
668 + Debug(1, 'Route Intel AMT direct connection to peer server: ' + server.serverid);
669 + obj.parent.multiServer.createPeerRelay(ws, req, server.serverid, user);
670 + return;
671 + }
672 + }
673 }
638 -
674 +
675 // If Intel AMT CIRA connection is available, use it
640 - if (((conn & 2) != 0) && (parent.mpsserver.ciraConnections[req.query.host] != undefined)) {
676 + if (((conn & 2) != 0) && (parent.mpsserver.ciraConnections[req.query.host] != null)) {
677 var ciraconn = parent.mpsserver.ciraConnections[req.query.host];
642 -
678 +
679 // Compute target port, look at the CIRA port mappings, if non-TLS is allowed, use that, if not use TLS
680 var port = 16993;
681 //if (node.intelamt.tls == 0) port = 16992; // DEBUG: Allow TLS flag to set TLS mode within CIRA
@@ -679,7 +715,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
715 var TLSSocket = require('tls').TLSSocket;
716 var tlsock = new TLSSocket(ser, { secureProtocol: 'SSLv23_method', rejectUnauthorized: false }); // TLSv1_2_method
717 tlsock.on('error', function (err) { Debug(1, "CIRA TLS Connection Error ", err); });
682 - tlsock.on('secureConnect', function () { Debug(2, "CIRA Secure TLS Connection"); });
718 + tlsock.on('secureConnect', function () { Debug(2, "CIRA Secure TLS Connection"); ws.resume(); });
719
720 // Decrypted tunnel from TLS communcation to be forwarded to websocket
721 tlsock.on('data', function (data) {
@@ -699,6 +735,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
735 // Without TLS
736 ws.forwardclient = parent.mpsserver.SetupCiraChannel(ciraconn, port);
737 ws.forwardclient.xtls = 0;
738 + ws.resume();
739 }
740
741 // When data is received from the web socket, forward the data into the associated CIRA cahnnel.
@@ -753,7 +790,26 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
790 // If Intel AMT direct connection is possible, option a direct socket
791 if ((conn & 4) != 0) { // We got a new web socket connection, initiate a TCP connection to the target Intel AMT host/port.
792 Debug(2, 'Opening relay TCP socket connection to ' + req.query.host + '.');
756 -
793 +
794 + // When data is received from the web socket, forward the data into the associated TCP connection.
795 + ws.on('message', function (msg) {
796 + Debug(1, 'TCP relay data to ' + node.host + ', ' + msg.length + ' bytes'); // DEBUG
797 + // Convert a buffer into a string, "msg = msg.toString('ascii');" does not work
798 + var msg2 = "";
799 + for (var i = 0; i < msg.length; i++) { msg2 += String.fromCharCode(msg[i]); }
800 + if (ws.interceptor) { msg2 = ws.interceptor.processBrowserData(msg2); } // Run data thru interceptor
801 + ws.forwardclient.write(new Buffer(msg2, "ascii")); // Forward data to the associated TCP connection.
802 + });
803 +
804 + // If error, do nothing
805 + ws.on('error', function (err) { console.log(err); });
806 +
807 + // If the web socket is closed, close the associated TCP connection.
808 + ws.on('close', function (req) {
809 + Debug(1, 'Closing relay web socket connection to ' + ws.upgradeReq.query.host + '.');
810 + if (ws.forwardclient) { try { ws.forwardclient.destroy(); } catch (e) { } }
811 + });
812 +
813 // Compute target port
814 var port = 16992;
815 if (node.intelamt.tls > 0) port = 16993; // This is a direct connection, use TLS when possible
@@ -765,55 +821,25 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
821 ws.forwardclient.setEncoding('binary');
822 ws.forwardclient.xstate = 0;
823 ws.forwardclient.forwardwsocket = ws;
824 + ws.resume();
825 } else {
826 // If TLS is going to be used, setup a TLS socket
827 ws.forwardclient = obj.tls.connect(port, node.host, { secureProtocol: 'TLSv1_method', rejectUnauthorized: false }, function () {
828 // The TLS connection method is the same as TCP, but located a bit differently.
829 Debug(2, 'TLS connected to ' + node.host + ':' + port + '.');
773 - if (ws.xpendingdata && ws.xpendingdata.length > 0) {
774 - //console.log('TLS sending pending data: ' + ws.xpendingdata.length);
775 - ws.forwardclient.write(ws.xpendingdata);
776 - delete ws.xpendingdata;
777 - }
830 ws.forwardclient.xstate = 1;
831 + ws.resume();
832 });
833 ws.forwardclient.setEncoding('binary');
834 ws.forwardclient.xstate = 0;
835 ws.forwardclient.forwardwsocket = ws;
783 - ws.xpendingdata = '';
836 }
837
786 - // When data is received from the web socket, forward the data into the associated TCP connection.
787 - // If the TCP connection is pending, buffer up the data until it connects.
788 - ws.on('message', function (msg) {
789 - // Debug(1, 'TCP relay data to ' + node.host + ', ' + msg.length + ' bytes'); // DEBUG
790 - // Convert a buffer into a string, "msg = msg.toString('ascii');" does not work
791 - var msg2 = "";
792 - for (var i = 0; i < msg.length; i++) { msg2 += String.fromCharCode(msg[i]); }
793 - if (ws.interceptor) { msg2 = ws.interceptor.processBrowserData(msg2); } // Run data thru interceptor
794 - if (ws.forwardclient == undefined || ws.forwardclient.xstate == 0) {
795 - // TCP connection is pending, buffer up the data.
796 - if (ws.xpendingdata) { ws.xpendingdata += msg2; } else { ws.xpendingdata = msg2; }
797 - } else {
798 - // Forward data to the associated TCP connection.
799 - ws.forwardclient.write(new Buffer(msg2, "ascii"));
800 - }
801 - });
802 -
803 - // If error, do nothing
804 - ws.on('error', function (err) { console.log(err); });
805 -
806 - // If the web socket is closed, close the associated TCP connection.
807 - ws.on('close', function (req) {
808 - Debug(1, 'Closing relay web socket connection to ' + ws.upgradeReq.query.host + '.');
809 - if (ws.forwardclient) { try { ws.forwardclient.destroy(); } catch (e) { } }
810 - });
811 -
838 // When we receive data on the TCP connection, forward it back into the web socket connection.
839 ws.forwardclient.on('data', function (data) {
814 - //Debug(1, 'TCP relay data from ' + node.host + ', ' + data.length + ' bytes.'); // DEBUG
840 + Debug(1, 'TCP relay data from ' + node.host + ', ' + data.length + ' bytes.'); // DEBUG
841 if (ws.interceptor) { data = ws.interceptor.processAmtData(data); } // Run data thru interceptor
816 - try { ws.send(data); } catch (e) { }
842 + try { ws.send(new Buffer(data, 'binary')); } catch (e) { }
843 });
844
845 // If the TCP connection closes, disconnect the associated web socket.
@@ -833,15 +859,11 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
859 else if (req.query.p == 2) { ws.interceptor = obj.interceptor.CreateRedirInterceptor({ user: node.intelamt.user, pass: node.intelamt.pass }); }
860
861 if (node.intelamt.tls == 0) {
836 - // A TCP connection to Intel AMT just connected, send any pending data and start forwarding.
862 + // A TCP connection to Intel AMT just connected, start forwarding.
863 ws.forwardclient.connect(port, node.host, function () {
864 Debug(1, 'TCP relay connected to ' + node.host + ':' + port + '.');
839 - if (ws.xpendingdata && ws.xpendingdata.length > 0) {
840 - //console.log('TCP sending pending data: ' + ws.xpendingdata.length);
841 - ws.forwardclient.write(new Buffer(ws.xpendingdata, "ascii"));
842 - delete ws.xpendingdata;
843 - }
865 ws.forwardclient.xstate = 1;
866 + ws.resume();
867 });
868 }
869 return;
@@ -911,7 +933,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
933 req.session.ws.userid = req.session.userid;
934 req.session.ws.domainid = domain.id;
935 var user = obj.users[req.session.userid];
914 - if (user == undefined || user == null) { try { ws.close(); } catch (e) { } return; }
936 + if (user == null) { try { ws.close(); } catch (e) { } return; }
937
938 // Add this web socket session to session list
939 ws.sessionId = user._id + '/' + ('' + Math.random()).substring(2);
@@ -962,8 +984,8 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
984 if (state) {
985 docs[i].conn = state.connectivity;
986 docs[i].pwr = state.powerState;
965 - if ((state.connectivity & 1) != 0) { var agent = obj.wsagents[docs[i]._id]; if (agent != undefined) { docs[i].agct = agent.connectTime; } }
966 - if ((state.connectivity & 2) != 0) { var cira = obj.parent.mpsserver.ciraConnections[docs[i]._id]; if (cira != undefined) { docs[i].cict = cira.tag.connectTime; } }
987 + if ((state.connectivity & 1) != 0) { var agent = obj.wsagents[docs[i]._id]; if (agent != null) { docs[i].agct = agent.connectTime; } }
988 + if ((state.connectivity & 2) != 0) { var cira = obj.parent.mpsserver.ciraConnections[docs[i]._id]; if (cira != null) { docs[i].cict = cira.tag.connectTime; } }
989 }
990 // Compress the meshid's
991 var meshid = docs[i].meshid;
@@ -1018,7 +1040,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1040 } else {
1041 // No records found, send current state if we have it
1042 var state = obj.parent.GetConnectivityState(command.nodeid);
1021 - if (state != undefined) { ws.send(JSON.stringify({ action: 'powertimeline', nodeid: command.nodeid, timeline: [state.powerState, Date.now(), state.powerState] })); }
1043 + if (state != null) { ws.send(JSON.stringify({ action: 'powertimeline', nodeid: command.nodeid, timeline: [state.powerState, Date.now(), state.powerState] })); }
1044 }
1045 });
1046 break;
@@ -1034,7 +1056,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1056 // Check permissions
1057 if ((user.siteadmin & 8) != 0) {
1058 // Perform a file operation (Create Folder, Delete Folder, Delete File...)
1037 - if ((command.path != undefined) && (typeof command.path == 'object') && command.path.length > 0) {
1059 + if ((command.path != null) && (typeof command.path == 'object') && command.path.length > 0) {
1060 var rootfolder = command.path[0];
1061 var rootfoldersplit = rootfolder.split('/'), domainx = 'domain';
1062 if (rootfoldersplit[1].length > 0) domainx = 'domain-' + rootfoldersplit[1];
@@ -1055,21 +1077,33 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1077 {
1078 // Route a message.
1079 // This this command has a nodeid, that is the target.
1058 - if (command.nodeid != undefined) {
1080 + if (command.nodeid != null) {
1081 var splitnodeid = command.nodeid.split('/');
1082 // Check that we are in the same domain and the user has rights over this node.
1083 if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domain.id)) {
1084 // See if the node is connected
1085 var agent = obj.wsagents[command.nodeid];
1064 - if (agent != undefined) {
1086 + if (agent != null) {
1087 // Check if we have permission to send a message to that node
1088 var rights = user.links[agent.dbMeshKey];
1067 - if (rights != undefined || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
1089 + if (rights != null || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
1090 command.sessionid = ws.sessionId; // Set the session id, required for responses.
1091 command.rights = rights.rights; // Add user rights flags to the message
1092 delete command.nodeid; // Remove the nodeid since it's implyed.
1093 agent.send(JSON.stringify(command));
1094 }
1095 + } else {
1096 + // Check if a peer server is connected to this agent
1097 + var routing = obj.parent.GetRoutingServerId(command.nodeid, 1); // 1 = MeshAgent routing type
1098 + if (routing != null) {
1099 + // Check if we have permission to send a message to that node
1100 + var rights = user.links[routing.meshid];
1101 + if (rights != null || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
1102 + command.fromSessionid = ws.sessionId; // Set the session id, required for responses.
1103 + command.rights = rights.rights; // Add user rights flags to the message
1104 + parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
1105 + }
1106 + }
1107 }
1108 }
1109 }
@@ -1112,7 +1146,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1146 // Delete a user account
1147 if ((user.siteadmin & 2) == 0) break;
1148 var delusername = command.username, deluserid = command.userid, deluser = obj.users[deluserid];
1115 - if ((deluser.siteadmin != undefined) && (deluser.siteadmin > 0) && (user.siteadmin != 0xFFFFFFFF)) break; // Need full admin to remote another administrator
1149 + if ((deluser.siteadmin != null) && (deluser.siteadmin > 0) && (user.siteadmin != 0xFFFFFFFF)) break; // Need full admin to remote another administrator
1150 if ((deluserid.split('/').length != 3) || (deluserid.split('/')[1] != domain.id)) break; // Invalid domain, operation only valid for current domain
1151
1152 // Delete all files on the server for this account
@@ -1159,8 +1193,8 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1193 var chguserid = 'user/' + domain.id + '/' + command.name.toLowerCase(), chguser = obj.users[chguserid], change = 0;
1194 if (chguser) {
1195 if (command.email && chguser.email != command.email) { chguser.email = command.email; change = 1; }
1162 - if (command.quota != chguser.quota) { chguser.quota = command.quota; if (chguser.quota == undefined) { delete chguser.quota; } change = 1; }
1163 - if ((user.siteadmin == 0xFFFFFFFF) && (command.siteadmin != undefined) && (chguser.siteadmin != command.siteadmin)) { chguser.siteadmin = command.siteadmin; change = 1 }
1196 + if (command.quota != chguser.quota) { chguser.quota = command.quota; if (chguser.quota == null) { delete chguser.quota; } change = 1; }
1197 + if ((user.siteadmin == 0xFFFFFFFF) && (command.siteadmin != null) && (chguser.siteadmin != command.siteadmin)) { chguser.siteadmin = command.siteadmin; change = 1 }
1198 if (change == 1) {
1199 obj.db.Set(chguser);
1200 obj.parent.DispatchEvent([chguser._id], obj, 'resubscribe');
@@ -1201,7 +1235,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1235 obj.db.Set(mesh);
1236 obj.meshes[meshid] = mesh;
1237 obj.parent.AddEventDispatch([meshid], ws);
1204 - if (user.links == undefined) user.links = {};
1238 + if (user.links == null) user.links = {};
1239 user.links[meshid] = { rights: 0xFFFFFFFF };
1240 user.subscriptions = obj.subscribe(user._id, ws);
1241 obj.db.SetUser(user);
@@ -1218,7 +1252,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1252 var mesh = meshes[0];
1253
1254 // Check if this user has rights to do this
1221 - if (mesh.links[user._id] == undefined || mesh.links[user._id].rights != 0xFFFFFFFF) return;
1255 + if (mesh.links[user._id] == null || mesh.links[user._id].rights != 0xFFFFFFFF) return;
1256 if ((command.meshid.split('/').length != 3) || (command.meshid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1257
1258 // Fire the removal event first, because after this, the event will not route
@@ -1253,11 +1287,11 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1287 var mesh = obj.meshes[command.meshid], change = '';
1288 if (mesh) {
1289 // Check if this user has rights to do this
1256 - if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 1) == 0)) return;
1290 + if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 1) == 0)) return;
1291 if ((command.meshid.split('/').length != 3) || (command.meshid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1292
1293 if (command.meshname && command.meshname != '' && command.meshname != mesh.name) { change = 'Mesh name changed from "' + mesh.name + '" to "' + command.meshname + '"'; mesh.name = command.meshname; }
1260 - if (command.desc != undefined && command.desc != mesh.desc) { if (change != '') change += ' and description changed'; else change += 'Mesh "' + mesh.name + '" description changed'; mesh.desc = command.desc; }
1294 + if (command.desc != null && command.desc != mesh.desc) { if (change != '') change += ' and description changed'; else change += 'Mesh "' + mesh.name + '" description changed'; mesh.desc = command.desc; }
1295 if (change != '') { obj.db.Set(mesh); obj.parent.DispatchEvent(['*', mesh._id, user._id], obj, { etype: 'mesh', username: user.name, meshid: mesh._id, name: mesh.name, mtype: mesh.mtype, desc: mesh.desc, action: 'meshchange', links: mesh.links, msg: change, domain: domain.id }) }
1296 }
1297 break;
@@ -1266,7 +1300,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1300 {
1301 // Check if the user exists
1302 var newuserid = 'user/' + domain.id + '/' + command.username.toLowerCase(), newuser = obj.users[newuserid];
1269 - if (newuser == undefined) {
1303 + if (newuser == null) {
1304 // TODO: Send error back, user not found.
1305 break;
1306 }
@@ -1275,11 +1309,11 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1309 var mesh = obj.meshes[command.meshid], change = '';
1310 if (mesh) {
1311 // Check if this user has rights to do this
1278 - if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 2) == 0)) return;
1312 + if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 2) == 0)) return;
1313 if ((command.meshid.split('/').length != 3) || (command.meshid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1314
1315 // Add mesh to user
1282 - if (newuser.links == undefined) newuser.links = {};
1316 + if (newuser.links == null) newuser.links = {};
1317 newuser.links[command.meshid] = { rights: command.meshadmin };
1318 obj.db.Set(newuser);
1319 obj.parent.DispatchEvent([newuser._id], obj, 'resubscribe');
@@ -1300,7 +1334,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1334
1335 // Check if the user exists
1336 var deluserid = command.userid, deluser = obj.users[deluserid];
1303 - if (deluser == undefined) {
1337 + if (deluser == null) {
1338 // TODO: Send error back, user not found.
1339 break;
1340 }
@@ -1309,10 +1343,10 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1343 var mesh = obj.meshes[command.meshid];
1344 if (mesh) {
1345 // Check if this user has rights to do this
1312 - if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 2) == 0)) return;
1346 + if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 2) == 0)) return;
1347
1348 // Remove mesh from user
1315 - if (deluser.links != undefined && deluser.links[command.meshid] != undefined) {
1349 + if (deluser.links != null && deluser.links[command.meshid] != null) {
1350 var delmeshrights = deluser.links[command.meshid].rights;
1351 if ((delmeshrights == 0xFFFFFFFF) && (mesh.links[user._id].rights != 0xFFFFFFFF)) return; // A non-admin can't kick out an admin
1352 delete deluser.links[command.meshid];
@@ -1321,7 +1355,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1355 }
1356
1357 // Remove user from the mesh
1324 - if (mesh.links[command.userid] != undefined) {
1358 + if (mesh.links[command.userid] != null) {
1359 delete mesh.links[command.userid];
1360 obj.db.Set(mesh);
1361 }
@@ -1344,7 +1378,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1378 if (mesh.mtype != 1) return; // This operation is only allowed for mesh type 1, Intel AMT agentless mesh.
1379
1380 // Check if this user has rights to do this
1347 - if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 4) == 0)) return;
1381 + if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 4) == 0)) return;
1382
1383 // Create a new nodeid
1384 obj.crypto.randomBytes(32, function (err, buf) {
@@ -1389,7 +1423,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1423 var mesh = obj.meshes[node.meshid];
1424 if (mesh) {
1425 // Check if this user has rights to do this
1392 - if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 4) == 0)) return;
1426 + if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 4) == 0)) return;
1427
1428 // Delete this node including network interface information and events
1429 obj.db.Remove(node._id);
@@ -1401,7 +1435,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1435
1436 // Disconnect all connections if needed
1437 var state = obj.parent.GetConnectivityState(command.nodeid);
1404 - if ((state != undefined) && (state.connectivity != undefined)) {
1438 + if ((state != null) && (state.connectivity != null)) {
1439 if ((state.connectivity & 1) != 0) { obj.wsagents[command.nodeid].close(); } // Disconnect mesh agent
1440 if ((state.connectivity & 2) != 0) { obj.parent.mpsserver.close(obj.parent.mpsserver.ciraConnections[command.nodeid]); } // Disconnect CIRA connection
1441 }
@@ -1430,7 +1464,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1464 if (mesh) {
1465
1466 // Check if this user has rights to do this
1433 - if (mesh.links[user._id] != undefined && ((mesh.links[user._id].rights & 64) != 0)) {
1467 + if (mesh.links[user._id] != null && ((mesh.links[user._id].rights & 64) != 0)) {
1468
1469 // Get the device interface information
1470 obj.db.Get('if' + node._id, function (err, nodeifs) {
@@ -1484,7 +1518,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1518 if (mesh) {
1519
1520 // Check if this user has rights to do this
1487 - if (mesh.links[user._id] != undefined && ((mesh.links[user._id].rights & 8) != 0)) { // "Remote Control permission"
1521 + if (mesh.links[user._id] != null && ((mesh.links[user._id].rights & 8) != 0)) { // "Remote Control permission"
1522
1523 // Get this device
1524 var agent = obj.wsagents[node._id];
@@ -1505,7 +1539,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1539 case 'getnetworkinfo':
1540 {
1541 // Argument validation
1508 - if ((command.nodeid == undefined) || (typeof command.nodeid != 'string') || (command.nodeid.split('/').length != 3) || (command.nodeid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1542 + if ((command.nodeid == null) || (typeof command.nodeid != 'string') || (command.nodeid.split('/').length != 3) || (command.nodeid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1543
1544 // Get the device
1545 obj.db.Get(command.nodeid, function (err, nodes) {
@@ -1516,7 +1550,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1550 var mesh = obj.meshes[node.meshid];
1551 if (mesh) {
1552 // Check if this user has rights to do this
1519 - if (mesh.links[user._id] == undefined || (mesh.links[user._id].rights == 0)) { ws.send(JSON.stringify({ action: 'getnetworkinfo', nodeid: command.nodeid, netif: null })); return; }
1553 + if (mesh.links[user._id] == null || (mesh.links[user._id].rights == 0)) { ws.send(JSON.stringify({ action: 'getnetworkinfo', nodeid: command.nodeid, netif: null })); return; }
1554
1555 // Get network information about this node
1556 obj.db.Get('if' + command.nodeid, function (err, netinfos) {
@@ -1531,7 +1565,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1565 case 'changedevice':
1566 {
1567 // Argument validation
1534 - if ((command.nodeid == undefined) || (typeof command.nodeid != 'string') || (command.nodeid.split('/').length != 3) || (command.nodeid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1568 + if ((command.nodeid == null) || (typeof command.nodeid != 'string') || (command.nodeid.split('/').length != 3) || (command.nodeid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
1569
1570 // Change the device
1571 obj.db.Get(command.nodeid, function (err, nodes) {
@@ -1542,7 +1576,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1576 var mesh = obj.meshes[node.meshid];
1577 if (mesh) {
1578 // Check if this user has rights to do this
1545 - if (mesh.links[user._id] == undefined || ((mesh.links[user._id].rights & 4) == 0)) return;
1579 + if (mesh.links[user._id] == null || ((mesh.links[user._id].rights & 4) == 0)) return;
1580
1581 // Ready the node change event
1582 var changes = [], change = 0, event = { etype: 'node', username: user.name, action: 'changenode', nodeid: node._id, domain: domain.id };
@@ -1552,9 +1586,9 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1586 if (command.icon && (command.icon != node.icon)) { change = 1; node.icon = command.icon; changes.push('icon'); }
1587 if (command.name && (command.name != node.name)) { change = 1; node.name = command.name; changes.push('name'); }
1588 if (command.host && (command.host != node.host)) { change = 1; node.host = command.host; changes.push('host'); }
1555 - if (command.desc != undefined && (command.desc != node.desc)) { change = 1; node.desc = command.desc; changes.push('description'); }
1556 - if ((command.intelamt != undefined) && (node.intelamt != undefined)) {
1557 - if ((command.intelamt.user != undefined) && (command.intelamt.pass != undefined) && ((command.intelamt.user != node.intelamt.user) || (command.intelamt.pass != node.intelamt.pass))) { change = 1; node.intelamt.user = command.intelamt.user; node.intelamt.pass = command.intelamt.pass; changes.push('Intel AMT credentials'); }
1589 + if (command.desc != null && (command.desc != node.desc)) { change = 1; node.desc = command.desc; changes.push('description'); }
1590 + if (command.intelamt != null) {
1591 + if ((command.intelamt.user != null) && (command.intelamt.pass != undefined) && ((command.intelamt.user != node.intelamt.user) || (command.intelamt.pass != node.intelamt.pass))) { change = 1; node.intelamt.user = command.intelamt.user; node.intelamt.pass = command.intelamt.pass; changes.push('Intel AMT credentials'); }
1592 if (command.intelamt.tls && (command.intelamt.tls != node.intelamt.tls)) { change = 1; node.intelamt.tls = command.intelamt.tls; changes.push('Intel AMT TLS'); }
1593 }
1594
@@ -1775,16 +1809,16 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1809
1810 // Handle a request to download a mesh agent
1811 obj.handleMeshAgentRequest = function (req, res) {
1778 - if (req.query.id != undefined) {
1812 + if (req.query.id != null) {
1813 // Send a specific mesh agent back
1814 var argentInfo = obj.parent.meshAgentBinaries[req.query.id];
1781 - if (argentInfo == undefined) { res.sendStatus(404); return; }
1815 + if (argentInfo == null) { res.sendStatus(404); return; }
1816 res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=' + argentInfo.rname });
1817 res.sendFile(argentInfo.path);
1784 - } else if (req.query.script != undefined) {
1818 + } else if (req.query.script != null) {
1819 // Send a specific mesh install script back
1820 var scriptInfo = obj.parent.meshAgentInstallScripts[req.query.script];
1787 - if (scriptInfo == undefined) { res.sendStatus(404); return; }
1821 + if (scriptInfo == null) { res.sendStatus(404); return; }
1822 res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename=' + scriptInfo.rname });
1823 res.sendFile(scriptInfo.path);
1824 } else {
@@ -1814,7 +1848,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
1848
1849 // Check if this user has rights to do this
1850 //var user = obj.users[req.session.userid];
1817 - //if ((user == undefined) || (mesh.links[user._id] == undefined) || ((mesh.links[user._id].rights & 1) == 0)) { res.sendStatus(401); return; }
1851 + //if ((user == null) || (mesh.links[user._id] == null) || ((mesh.links[user._id].rights & 1) == 0)) { res.sendStatus(401); return; }
1852 //if (domain.id != mesh.domain) { res.sendStatus(401); return; }
1853
1854 var xdomain = domain.id;
@@ -1971,29 +2005,29 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
2005
2006 // Force mesh agent disconnection
2007 function forceMeshAgentDisconnect(user, domain, nodeid, disconnectMode) {
1974 - if ((nodeid == undefined) || (nodeid == null)) return;
2008 + if (nodeid == null) return;
2009 var splitnode = nodeid.split('/');
2010 if ((splitnode.length != 3) || (splitnode[1] != domain.id)) return; // Check that nodeid is valid and part of our domain
2011 var agent = obj.wsagents[nodeid];
1978 - if (agent == undefined) return;
2012 + if (agent == null) return;
2013
2014 // Check we have agent rights
2015 var rights = user.links[agent.dbMeshKey].rights;
1982 - if ((rights != undefined) && ((rights & 16) != 0) && (user.siteadmin == 0xFFFFFFFF)) { agent.close(disconnectMode); }
2016 + if ((rights != null) && ((rights & 16) != 0) && (user.siteadmin == 0xFFFFFFFF)) { agent.close(disconnectMode); }
2017 }
2018
2019 // Send the core module to the mesh agent
2020 function sendMeshAgentCore(user, domain, nodeid, core) {
1987 - if ((nodeid == undefined) || (nodeid == null)) return;
2021 + if (nodeid == null) return;
2022 var splitnode = nodeid.split('/');
2023 if ((splitnode.length != 3) || (splitnode[1] != domain.id)) return; // Check that nodeid is valid and part of our domain
2024 var agent = obj.wsagents[nodeid];
1991 - if (agent == undefined) return;
2025 + if (agent == null) return;
2026
2027 // Check we have agent rights
2028 var rights = user.links[agent.dbMeshKey].rights;
1995 - if ((rights != undefined) && ((rights & 16) != 0) && (user.siteadmin == 0xFFFFFFFF)) {
1996 - if ((core == null) || (core == undefined)) {
2029 + if ((rights != null) && ((rights & 16) != 0) && (user.siteadmin == 0xFFFFFFFF)) {
2030 + if (core == null) {
2031 // Clear the mesh agent core
2032 agent.agentCoreCheck = 1000; // Tell the agent object we are not using a custom core.
2033 agent.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0));
@@ -2016,18 +2050,18 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
2050
2051 // Return the maximum number of bytes allowed in the user account "My Files".
2052 function getQuota(objid, domain) {
2019 - if ((objid == undefined) || (objid == null)) return 0;
2053 + if (objid == null) return 0;
2054 if (objid.startsWith('user/')) {
2055 var user = obj.users[objid];
2022 - if (user == undefined) return 0;
2023 - if ((user.quota != undefined) && (typeof user.quota == 'number')) { return user.quota; }
2024 - if ((domain != undefined) && (domain.userQuota != undefined) && (typeof domain.userQuota == 'number')) { return domain.userQuota; }
2056 + if (user == null) return 0;
2057 + if ((user.quota != null) && (typeof user.quota == 'number')) { return user.quota; }
2058 + if ((domain != null) && (domain.userQuota != null) && (typeof domain.userQuota == 'number')) { return domain.userQuota; }
2059 return 1048576; // By default, the server will have a 1 meg limit on user accounts
2060 } else if (objid.startsWith('mesh/')) {
2061 var mesh = obj.meshes[objid];
2028 - if (mesh == undefined) return 0;
2029 - if ((mesh.quota != undefined) && (typeof mesh.quota == 'number')) { return mesh.quota; }
2030 - if ((domain != undefined) && (domain.meshQuota != undefined) && (typeof domain.meshQuota == 'number')) { return domain.meshQuota; }
2062 + if (mesh == null) return 0;
2063 + if ((mesh.quota != null) && (typeof mesh.quota == 'number')) { return mesh.quota; }
2064 + if ((domain != null) && (domain.meshQuota != null) && (typeof domain.meshQuota == 'number')) { return domain.meshQuota; }
2065 return 1048576; // By default, the server will have a 1 meg limit on mesh accounts
2066 }
2067 return 0;
@@ -2035,7 +2069,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
2069
2070 // Get the server path of a user or mesh object
2071 function getServerRootFilePath(obj) {
2038 - if ((typeof obj != 'object') || (obj.domain == undefined) || (obj._id == undefined)) return null;
2072 + if ((typeof obj != 'object') || (obj.domain == null) || (obj._id == null)) return null;
2073 var domainname = 'domain', splitname = obj._id.split('/');
2074 if (splitname.length != 3) return null;
2075 if (obj.domain !== '') domainname = 'domain-' + obj.domain;
@@ -2048,7 +2082,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
2082 if ((splitpath.length < 3) || (splitpath[0] != 'user' && splitpath[0] != 'mesh') || (splitpath[1] != domain.id)) return null; // Basic validation
2083 var objid = splitpath[0] + '/' + splitpath[1] + '/' + splitpath[2];
2084 if (splitpath[0] == 'user' && (objid != user._id)) return null; // User validation, only self allowed
2051 - if (splitpath[0] == 'mesh') { var link = user.links[objid]; if ((link == undefined) || (link.rights == undefined) || ((link.rights & 32) == 0)) { return null; } } // Check mesh server file rights
2085 + if (splitpath[0] == 'mesh') { var link = user.links[objid]; if ((link == null) || (link.rights == null) || ((link.rights & 32) == 0)) { return null; } } // Check mesh server file rights
2086 if (splitpath[1] != '') { serverpath += '-' + splitpath[1]; } // Add the domain if needed
2087 serverpath += ('/' + splitpath[0] + '-' + splitpath[2]);
2088 for (var i = 3; i < splitpath.length; i++) { if (obj.common.IsFilenameValid(splitpath[i]) == true) { serverpath += '/' + splitpath[i]; filename = splitpath[i]; } else { return null; } } // Check that each folder is correct