Remove extra command handlers/table

This commit is contained in:
Noah Zalev 2021-07-08 10:24:11 -04:00
parent b05f65d819
commit 939088bae4
1 changed files with 0 additions and 603 deletions

View File

@ -544,609 +544,6 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
}); });
} catch (e) { console.log(e); } } catch (e) { console.log(e); }
var consoleCommands = {};
consoleCommands['help'] = helpConsoleCommand;
consoleCommands['certexpire'] = certexpireConsoleCommand;
consoleCommands['webpush'] = webpushConsoleCommand;
consoleCommands['amtmanager'] = amtmanagerConsoleCommand;
consoleCommands['certhashes'] = certhashesConsoleCommand;
consoleCommands['amtacm'] = amtacmConsoleCommand;
consoleCommands['heapdump'] = heapdumpConsoleCommand;
consoleCommands['heapdump2'] = heapdump2ConsoleCommand;
consoleCommands['sms'] = smsConsoleCommand;
consoleCommands['email'] = emailConsoleCommand;
consoleCommands['le'] = leConsoleCommand;
consoleCommands['lecheck'] = lecheckConsoleCommand;
consoleCommands['leevents'] = leeventsConsoleCommand;
consoleCommands['badlogins'] = badloginsConsoleCommand;
consoleCommands['dispatchtable'] = dispatchtableConsoleCommand;
consoleCommands['dupagents'] = dupagentsConsoleCommand;
consoleCommands['agentstats'] = agentstatsConsoleCommand;
consoleCommands['agentissues'] = agentissuesConsoleCommand;
consoleCommands['webstats'] = webstatsConsoleCommand;
consoleCommands['trafficstats'] = trafficstatsConsoleCommand;
consoleCommands['trafficdelta'] = trafficdeltaConsoleCommand;
consoleCommands['watchdog'] = watchdogConsoleCommand;
consoleCommands['acceleratorsstats'] = acceleratorsstatsConsoleCommand;
consoleCommands['mpsstats'] = mpsstatsConsoleCommand;
consoleCommands['mps'] = mpsConsoleCommand;
consoleCommands['dbstats'] = dbstatsConsoleCommand;
consoleCommands['dbcounters'] = dbcountersConsoleCommand;
consoleCommands['serverupdate'] = serverupdateConsoleCommand;
consoleCommands['print'] = printConsoleCommand;
consoleCommands['amtpasswords'] = amtpasswordsConsoleCommand;
consoleCommands['updatecheck'] = updatecheckConsoleCommand;
consoleCommands['maintenance'] = maintenanceConsoleCommand;
consoleCommands['info'] = infoConsoleCommand;
consoleCommands['nodeconfig'] = nodeconfigConsoleCommand;
consoleCommands['versions'] = versionsConsoleCommand;
consoleCommands['args'] = argsConsoleCommand;
consoleCommands['usersessions'] = usersessionsConsoleCommand;
consoleCommands['closeusersessions'] = closeusersessionsConsoleCommand;
consoleCommands['resetserver'] = resetserverConsoleCommand;
consoleCommands['tasklimiter'] = tasklimiterConsoleCommand;
consoleCommands['setmaxtasks'] = setmaxtasksConsoleCommand;
consoleCommands['cores'] = coresConsoleCommand;
consoleCommands['showpaths'] = showpathsConsoleCommand;
consoleCommands['migrationagents'] = migrationagentsConsoleCommand;
consoleCommands['swarmstats'] = swarmstatsConsoleCommand;
consoleCommands['relays'] = relaysConsoleCommand;
consoleCommands['autobackup'] = autobackupConsoleCommand;
consoleCommands['backupconfig'] = backupconfigConsoleCommand;
consoleCommands['firebase'] = firebaseConsoleCommand;
function helpConsoleCommand(cmdData) {
var fin = '', f = '', availcommands = 'help,maintenance,info,versions,resetserver,usersessions,closeusersessions,tasklimiter,setmaxtasks,cores,migrationagents,agentstats,agentissues,webstats,trafficstats,trafficdelta,mpsstats,swarmstats,acceleratorsstats,updatecheck,serverupdate,nodeconfig,heapdump,relays,autobackup,backupconfig,dupagents,dispatchtable,badlogins,showpaths,le,lecheck,leevents,dbstats,dbcounters,sms,amtacm,certhashes,watchdog,amtmanager,amtpasswords,certexpire,email';
if (parent.parent.config.settings.heapdump === true) { availcommands += ',heapdump'; }
availcommands = availcommands.split(',').sort();
while (availcommands.length > 0) { if (f.length > 80) { fin += (f + ',\r\n'); f = ''; } f += (((f != '') ? ', ' : ' ') + availcommands.shift()); }
if (f != '') { fin += f; }
if (cmdData.cmdargs['_'].length == 0) {
cmdData.result = 'Available commands: \r\n' + fin + '\r\nType help <command> for details.';
} else {
var cmd2 = cmdData.cmdargs['_'][0].toLowerCase();
switch (cmd2) {
case 'info': { cmdData.result = "info: Returns the most immidiatly useful information about this server, including MeshCentral and NodeJS versions. This is often information required to file a bug."; break; }
case 'versions': { cmdData.result = "versions: Returns all internal versions for NodeJS running this server."; break; }
case 'resetserver': { cmdData.result = "resetserver: Causes the server to reset, this is sometimes useful is the config.json file was changed."; break; }
case 'usersessions': { cmdData.result = "usersessions: Returns a list of active sessions grouped by user."; break; }
case 'closeusersessions': { cmdData.result = "closeusersessions: Disconnects all sessions for a specified user."; break; }
case 'tasklimiter': { cmdData.result = "tasklimiter: Returns the internal status of the tasklimiter. This is a system used to smooth out work done by the server. It's used by, for example, agent updates so that not all agents are updated at the same time."; break; }
case 'serverupdate': { cmdData.result = "serverupdate: Updates server to latest version. Optional version argument to install specific version. Example: serverupdate 0.8.49"; break; }
default: { cmdData.result = 'No help information about this command.'; break; }
}
}
}
function certexpireConsoleCommand(cmdData) {
const now = Date.now();
for (var i in parent.webCertificateExpire) {
const domainName = (i == '') ? '[Default]' : i;
cmdData.result += domainName + ', expires in ' + Math.floor((parent.webCertificateExpire[i] - now) / 86400000) + ' day(s)\r\n';
}
}
function webpushConsoleCommand(cmdData) {
if (parent.parent.webpush == null) {
cmdData.result = "Web push not supported.";
} else {
if (cmdData.cmdargs['_'].length != 1) {
cmdData.result = "Usage: WebPush \"Message\"";
} else {
const pushSubscription = { "endpoint": "https://updates.push.services.mozilla.com/wpush/v2/gAAAAABgIkO9hjXHWhMPiuk-ppNRw7r_pUZitddwCEK4ykdzeIxOIjFnYhIt_nr-qUca2mpZziwQsSEhYTUCiuYrhWnVDRweMtiUj16yJJq8V5jneaEaUYjEIe5jp3DOMNpoTm1aHgX74gCR8uTXSITcM97bNi-hRxcQ4f6Ie4WSAmoXpd89B_g", "keys": { "auth": "UB2sbLVK7ALnSHw5P1dahg", "p256dh": "BIoRbcNSxBuTjN39CCCUCHo1f4NxBJ1YDdu_k4MbPW_q3NK1_RufnydUzLPDp8ibBVItSI72-s48QJvOjQ_S8Ok" } }
parent.parent.webpush.sendNotification(pushSubscription, cmdData.cmdargs['_'][0]).then(
function (value) { try { ws.send(JSON.stringify({ action: 'OK', value: cmdData.result, tag: cmdData.command.tag })); } catch (ex) { } },
function (error) { try { ws.send(JSON.stringify({ action: 'Error', value: cmdData.result, tag: cmdData.command.tag })); } catch (ex) { } }
);
}
}
}
function amtmanagerConsoleCommand(cmdData) {
if (parent.parent.amtManager == null) {
cmdData.result = 'Intel AMT Manager not active.';
} else {
cmdData.result = parent.parent.amtManager.getStatusString();
}
}
function certhashesConsoleCommand(cmdData) {
cmdData.result += 'AgentCertHash: ' + parent.agentCertificateHashHex;
for (var i in parent.webCertificateHashs) { cmdData.result += '\r\nwebCertificateHash (' + i + '): ' + common.rstr2hex(parent.webCertificateHashs[i]); }
for (var i in parent.webCertificateFullHashs) { cmdData.result += '\r\nwebCertificateFullHash (' + i + '): ' + common.rstr2hex(parent.webCertificateFullHashs[i]); }
cmdData.result += '\r\ndefaultWebCertificateHash: ' + common.rstr2hex(parent.defaultWebCertificateHash);
cmdData.result += '\r\ndefaultWebCertificateFullHash: ' + common.rstr2hex(parent.defaultWebCertificateFullHash);
}
function amtacmConsoleCommand(cmdData) {
if ((domain.amtacmactivation == null) || (domain.amtacmactivation.acmmatch == null) || (domain.amtacmactivation.acmmatch.length == 0)) {
cmdData.result = 'No Intel AMT activation certificates.';
} else {
if (domain.amtacmactivation.log != null) { cmdData.result += '--- Activation Log ---\r\nFile : ' + domain.amtacmactivation.log + '\r\n'; }
for (var i in domain.amtacmactivation.acmmatch) {
var acmcert = domain.amtacmactivation.acmmatch[i];
cmdData.result += '--- Activation Certificate ' + (parseInt(i) + 1) + ' ---\r\nName : ' + acmcert.cn + '\r\nSHA1 : ' + acmcert.sha1 + '\r\nSHA256: ' + acmcert.sha256 + '\r\n';
}
}
}
function heapdumpConsoleCommand(cmdData) {
// Heapdump support, see example at:
// https://www.arbazsiddiqui.me/a-practical-guide-to-memory-leaks-in-nodejs/
if (parent.parent.config.settings.heapdump === true) {
var dumpFileName = parent.path.join(parent.parent.datapath, `heapDump-${Date.now()}.heapsnapshot`);
try { ws.send(JSON.stringify({ action: 'serverconsole', value: "Generating dump file at: " + dumpFileName, tag: cmdData.command.tag })); } catch (ex) { }
require('heapdump').writeSnapshot(dumpFileName, (err, filename) => {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: "Done.", tag: cmdData.command.tag })); } catch (ex) { }
});
} else {
cmdData.result = "Heapdump not supported, add \"heapdump\":true to settings section of config.json.";
}
}
function heapdump2ConsoleCommand(cmdData) {
var heapdump = null;
try { heapdump = require('heapdump'); } catch (ex) { }
if (heapdump == null) {
cmdData.result = 'Heapdump module not installed, run "npm install heapdump".';
} else {
heapdump.writeSnapshot(function (err, filename) {
if (err != null) {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: 'Unable to write heapdump: ' + err })); } catch (ex) { }
} else {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: 'Wrote heapdump at ' + filename })); } catch (ex) { }
}
});
}
}
function smsConsoleCommand(cmdData) {
if (parent.parent.smsserver == null) {
cmdData.result = "No SMS gateway in use.";
} else {
if (cmdData.cmdargs['_'].length != 2) {
cmdData.result = "Usage: SMS \"PhoneNumber\" \"Message\".";
} else {
parent.parent.smsserver.sendSMS(cmdData.cmdargs['_'][0], cmdData.cmdargs['_'][1], function (status, msg) {
if (typeof msg == 'string') {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: status ? ('Success: ' + msg) : ('Failed: ' + msg), tag: cmdData.command.tag })); } catch (ex) { }
} else {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: status ? 'Success' : 'Failed', tag: cmdData.command.tag })); } catch (ex) { }
}
});
}
}
}
function emailConsoleCommand(cmdData) {
if (domain.mailserver == null) {
cmdData.result = "No email service enabled.";
} else {
if (cmdData.cmdargs['_'].length != 3) {
cmdData.result = "Usage: email \"user@sample.com\" \"Subject\" \"Message\".";
} else {
domain.mailserver.sendMail(cmdData.cmdargs['_'][0], cmdData.cmdargs['_'][1], cmdData.cmdargs['_'][2]);
cmdData.result = "Done.";
}
}
}
function leConsoleCommand(cmdData) {
if (parent.parent.letsencrypt == null) {
cmdData.result = "Let's Encrypt not in use.";
} else {
cmdData.result = JSON.stringify(parent.parent.letsencrypt.getStats(), null, 4);
}
}
function lecheckConsoleCommand(cmdData) {
if (parent.parent.letsencrypt == null) {
cmdData.result = "Let's Encrypt not in use.";
} else {
cmdData.result = ["CertOK", "Request:NoCert", "Request:Expire", "Request:MissingNames"][parent.parent.letsencrypt.checkRkenewCertificate()];
}
}
function leeventsConsoleCommand(cmdData) {
if (parent.parent.letsencrypt == null) {
cmdData.result = "Let's Encrypt not in use.";
} else {
cmdData.result = parent.parent.letsencrypt.events.join('\r\n');
}
}
function badloginsConsoleCommand(cmdData) {
if (parent.parent.config.settings.maxinvalidlogin == false) {
cmdData.result = 'Bad login filter is disabled.';
} else {
if (cmdData.cmdargs['_'] == 'reset') {
// Reset bad login table
parent.badLoginTable = {};
parent.badLoginTableLastClean = 0;
cmdData.result = 'Done.'
} else if (cmdData.cmdargs['_'] == '') {
// Show current bad login table
if (typeof parent.parent.config.settings.maxinvalidlogin.coolofftime == 'number') {
cmdData.result = "Max is " + parent.parent.config.settings.maxinvalidlogin.count + " bad login(s) in " + parent.parent.config.settings.maxinvalidlogin.time + " minute(s), " + parent.parent.config.settings.maxinvalidlogin.coolofftime + " minute(s) cooloff.\r\n";
} else {
cmdData.result = "Max is " + parent.parent.config.settings.maxinvalidlogin.count + " bad login(s) in " + parent.parent.config.settings.maxinvalidlogin.time + " minute(s).\r\n";
}
var badLoginCount = 0;
parent.cleanBadLoginTable();
for (var i in parent.badLoginTable) {
badLoginCount++;
if (typeof parent.badLoginTable[i] == 'number') {
cmdData.result += "Cooloff for " + Math.floor((parent.badLoginTable[i] - Date.now()) / 60000) + " minute(s)\r\n";
} else {
if (parent.badLoginTable[i].length > 1) {
cmdData.result += (i + ' - ' + parent.badLoginTable[i].length + " records\r\n");
} else {
cmdData.result += (i + ' - ' + parent.badLoginTable[i].length + " record\r\n");
}
}
}
if (badLoginCount == 0) { cmdData.result += 'No bad logins.'; }
} else {
cmdData.result = 'Usage: badlogin [reset]';
}
}
}
function dispatchtableConsoleCommand(cmdData) {
for (var i in parent.parent.eventsDispatch) {
cmdData.result += (i + ', ' + parent.parent.eventsDispatch[i].length + '\r\n');
}
}
function dupagentsConsoleCommand(cmdData) {
for (var i in parent.duplicateAgentsLog) {
cmdData.result += JSON.stringify(parent.duplicateAgentsLog[i]) + '\r\n';
}
if (cmdData.result == '') { cmdData.result = 'No duplicate agents in log.'; }
}
function agentstatsConsoleCommand(cmdData) {
var stats = parent.getAgentStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { cmdData.result += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { cmdData.result += (i + ': ' + stats[i] + '\r\n'); }
}
}
function agentissuesConsoleCommand(cmdData) {
var stats = parent.getAgentIssues();
if (stats.length == 0) {
cmdData.result = "No agent issues.";
} else {
for (var i in stats) { cmdData.result += stats[i].join(', ') + '\r\n'; }
}
}
function webstatsConsoleCommand(cmdData) {
var stats = parent.getStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { cmdData.result += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { cmdData.result += (i + ': ' + stats[i] + '\r\n'); }
}
}
function trafficstatsConsoleCommand(cmdData) {
var stats = parent.getTrafficStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { cmdData.result += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { cmdData.result += (i + ': ' + stats[i] + '\r\n'); }
}
}
function trafficdeltaConsoleCommand(cmdData) {
const stats = parent.getTrafficDelta(obj.trafficStats);
obj.trafficStats = stats.current;
for (var i in stats.delta) {
if (typeof stats.delta[i] == 'object') { cmdData.result += (i + ': ' + JSON.stringify(stats.delta[i]) + '\r\n'); } else { cmdData.result += (i + ': ' + stats.delta[i] + '\r\n'); }
}
}
function watchdogConsoleCommand(cmdData) {
if (parent.parent.watchdog == null) {
cmdData.result = 'Server watchdog not active.';
} else {
cmdData.result = 'Server watchdog active.\r\n';
if (parent.parent.watchdogmaxtime != null) { cmdData.result += 'Largest timeout was ' + parent.parent.watchdogmax + 'ms on ' + parent.parent.watchdogmaxtime + '\r\n'; }
for (var i in parent.parent.watchdogtable) { cmdData.result += parent.parent.watchdogtable[i] + '\r\n'; }
}
}
function acceleratorsstatsConsoleCommand(cmdData) {
var stats = parent.parent.certificateOperations.getAcceleratorStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { cmdData.result += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { cmdData.result += (i + ': ' + stats[i] + '\r\n'); }
}
}
function mpsstatsConsoleCommand(cmdData) {
if (parent.parent.mpsserver == null) {
cmdData.result = 'MPS not enabled.';
} else {
var stats = parent.parent.mpsserver.getStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { cmdData.result += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { cmdData.result += (i + ': ' + stats[i] + '\r\n'); }
}
}
}
function mpsConsoleCommand(cmdData) {
if (parent.parent.mpsserver == null) {
cmdData.result = 'MPS not enabled.';
} else {
const connectionTypes = ['CIRA', 'Relay', 'LMS'];
for (var nodeid in parent.parent.mpsserver.ciraConnections) {
cmdData.result += nodeid;
var connections = parent.parent.mpsserver.ciraConnections[nodeid];
for (var i in connections) { cmdData.result += ', ' + connectionTypes[connections[i].tag.connType]; }
cmdData.result += '\r\n';
}
if (cmdData.result == '') { cmdData.result = 'MPS has not connections.'; }
}
}
function dbstatsConsoleCommand(cmdData) {
parent.parent.db.getStats(function (stats) {
var r2 = '';
for (var i in stats) { r2 += (i + ': ' + stats[i] + '\r\n'); }
try { ws.send(JSON.stringify({ action: 'serverconsole', value: r2, tag: cmdData.command.tag })); } catch (ex) { }
});
}
function dbcountersConsoleCommand(cmdData) {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: JSON.stringify(parent.parent.db.dbCounters, null, 2), tag: cmdData.command.tag })); } catch (ex) { }
}
function serverupdateConsoleCommand(cmdData) {
cmdData.result = 'Performing server update...';
var version = null;
if (cmdData.cmdargs['_'].length > 0) {
version = cmdData.cmdargs['_'][0];
// This call is SLOW. We only want to validate version if we have to
if (version != 'stable' && version != 'latest') {
parent.parent.getServerVersions((data) => {
var versions = JSON.parse(data);
if (versions.includes(version)) {
if (parent.parent.performServerUpdate(version) == false) {
try {
ws.send(JSON.stringify({ action: 'serverconsole',
value: 'Server self-update not possible.'}));
} catch (ex) { }
}
} else {
try {
ws.send(JSON.stringify({ action: 'serverconsole',
value: 'Invalid version. Aborting update'}));
} catch (ex) { }
}
});
} else {
if (parent.parent.performServerUpdate(version) == false) {
cmdData.result = 'Server self-update not possible.';
}
}
} else {
if (parent.parent.performServerUpdate(version) == false) {
cmdData.result = 'Server self-update not possible.';
}
}
}
function printConsoleCommand(cmdData) {
console.log(cmdData.cmdargs['_'][0]);
}
function amtpasswordsConsoleCommand(cmdData) {
if (parent.parent.amtPasswords == null) {
cmdData.result = "No Intel AMT password table."
} else {
for (var i in parent.parent.amtPasswords) { cmdData.result += (i + ' - ' + parent.parent.amtPasswords[i].join(', ') + '\r\n'); }
}
}
function updatecheckConsoleCommand(cmdData) {
parent.parent.getServerTags(function (tags, error) {
var r2 = '';
if (error != null) { r2 += 'Exception: ' + error + '\r\n'; }
else { for (var i in tags) { r2 += i + ': ' + tags[i] + '\r\n'; } }
try { ws.send(JSON.stringify({ action: 'serverconsole', value: r2, tag: cmdData.command.tag })); } catch (ex) { }
});
cmdData.result = "Checking server update...";
}
function maintenanceConsoleCommand(cmdData) {
var arg = null, changed = false;
if ((cmdData.cmdargs['_'] != null) && (cmdData.cmdargs['_'][0] != null)) { arg = cmdData.cmdargs['_'][0].toLowerCase(); }
if (arg == 'enabled') { parent.parent.config.settings.maintenancemode = 1; changed = true; }
else if (arg == 'disabled') { delete parent.parent.config.settings.maintenancemode; changed = true; }
cmdData.result = 'Maintenance mode: ' + ((parent.parent.config.settings.maintenancemode == null) ? 'Disabled' : 'Enabled');
if (changed == false) { cmdData.result += '\r\nTo change type: maintenance [enabled|disabled]'; }
}
function infoConsoleCommand(cmdData) {
var info = process.memoryUsage();
info.dbType = ['None', 'NeDB', 'MongoJS', 'MongoDB'][parent.db.databaseType];
try { if (parent.parent.multiServer != null) { info.serverId = parent.parent.multiServer.serverid; } } catch (ex) { }
if (parent.db.databaseType == 3) { info.dbChangeStream = parent.db.changeStream; }
if (parent.parent.pluginHandler != null) { info.plugins = []; for (var i in parent.parent.pluginHandler.plugins) { info.plugins.push(i); } }
try { info.nodeVersion = process.version; } catch (ex) { }
try { info.meshVersion = parent.parent.currentVer; } catch (ex) { }
try { info.platform = process.platform; } catch (ex) { }
try { info.arch = process.arch; } catch (ex) { }
try { info.pid = process.pid; } catch (ex) { }
try { info.uptime = process.uptime(); } catch (ex) { }
try { info.cpuUsage = process.cpuUsage(); } catch (ex) { }
try { info.warnings = parent.parent.getServerWarnings(); } catch (ex) { }
try { info.database = ["Unknown", "NeDB", "MongoJS", "MongoDB", "MariaDB", "MySQL"][parent.parent.db.databaseType]; } catch (ex) { }
try { info.productionMode = ((process.env.NODE_ENV != null) && (process.env.NODE_ENV == 'production')); } catch (ex) { }
try { info.allDevGroupManagers = parent.parent.config.settings.managealldevicegroups; } catch (ex) { }
cmdData.result = JSON.stringify(info, null, 4);
}
function nodeconfigConsoleCommand(cmdData) {
cmdData.result = JSON.stringify(process.config, null, 4);
}
function versionsConsoleCommand(cmdData) {
cmdData.result = JSON.stringify(process.versions, null, 4);
}
function argsConsoleCommand(cmdData) {
cmdData.result = 'args: ' + JSON.stringify(cmdData.cmdargs);
}
function usersessionsConsoleCommand(cmdData) {
var userSessionCount = 0;
var filter = null;
var arg = cmdData.cmdargs['_'][0];
if (typeof arg == 'string') { if (arg.indexOf('/') >= 0) { filter = arg; } else { filter = ('user/' + domain.id + '/' + arg); } }
for (var i in parent.wssessions) {
if ((filter == null) || (filter == i)) {
userSessionCount++;
cmdData.result += (i + ', ' + parent.wssessions[i].length + ' session' + ((parent.wssessions[i].length > 1) ? 's' : '') + '.\r\n');
for (var j in parent.wssessions[i]) {
cmdData.result += ' ' + parent.wssessions[i][j].clientIp + ' --> ' + parent.wssessions[i][j].sessionId + '\r\n';
}
}
}
if (userSessionCount == 0) { cmdData.result = 'None.'; }
}
function closeusersessionsConsoleCommand(cmdData) {
var userSessionCount = 0;
var filter = null;
var arg = cmdData.cmdargs['_'][0];
if (typeof arg == 'string') { if (arg.indexOf('/') >= 0) { filter = arg; } else { filter = ('user/' + domain.id + '/' + arg); } }
if (filter == null) {
cmdData.result += "Usage: closeusersessions <username>";
} else {
cmdData.result += "Closing user sessions for: " + filter + '\r\n';
for (var i in parent.wssessions) {
if (filter == i) {
userSessionCount++;
for (var j in parent.wssessions[i]) {
parent.wssessions[i][j].send(JSON.stringify({ action: 'stopped', msg: "Administrator forced disconnection" }));
parent.wssessions[i][j].close();
}
}
}
if (userSessionCount < 2) { cmdData.result += 'Disconnected ' + userSessionCount + ' session.'; } else { cmdData.result += 'Disconnected ' + userSessionCount + ' sessions.'; };
}
}
function resetserverConsoleCommand(cmdData) {
console.log("Server restart...");
process.exit(0);
}
function tasklimiterConsoleCommand(cmdData) {
if (parent.parent.taskLimiter != null) {
//var obj = { maxTasks: maxTasks, maxTaskTime: (maxTaskTime * 1000), nextTaskId: 0, currentCount: 0, current: {}, pending: [[], [], []], timer: null };
const tl = parent.parent.taskLimiter;
cmdData.result += 'MaxTasks: ' + tl.maxTasks + ', NextTaskId: ' + tl.nextTaskId + '\r\n';
cmdData.result += 'MaxTaskTime: ' + (tl.maxTaskTime / 1000) + ' seconds, Timer: ' + (tl.timer != null) + '\r\n';
var c = [];
for (var i in tl.current) { c.push(i); }
cmdData.result += 'Current (' + tl.currentCount + '): [' + c.join(', ') + ']\r\n';
cmdData.result += 'Pending (High/Med/Low): ' + tl.pending[0].length + ', ' + tl.pending[1].length + ', ' + tl.pending[2].length + '\r\n';
}
}
function setmaxtasksConsoleCommand(cmdData) {
if ((cmdData.cmdargs["_"].length != 1) || (parseInt(cmdData.cmdargs["_"][0]) < 1) || (parseInt(cmdData.cmdargs["_"][0]) > 1000)) {
cmdData.result = 'Usage: setmaxtasks [1 to 1000]';
} else {
parent.parent.taskLimiter.maxTasks = parseInt(cmdData.cmdargs["_"][0]);
cmdData.result = 'MaxTasks set to ' + parent.parent.taskLimiter.maxTasks + '.';
}
}
function coresConsoleCommand(cmdData) {
if (parent.parent.defaultMeshCores != null) {
for (var i in parent.parent.defaultMeshCores) {
cmdData.result += i + ': ' + parent.parent.defaultMeshCores[i].length + ' bytes\r\n';
}
}
}
function showpathsConsoleCommand(cmdData) {
cmdData.result = 'Parent: ' + parent.parent.parentpath + '\r\n';
cmdData.result += 'Data: ' + parent.parent.datapath + '\r\n';
cmdData.result += 'Files: ' + parent.parent.filespath + '\r\n';
cmdData.result += 'Backup: ' + parent.parent.backuppath + '\r\n';
cmdData.result += 'Record: ' + parent.parent.recordpath + '\r\n';
cmdData.result += 'WebPublic: ' + parent.parent.webPublicPath + '\r\n';
cmdData.result += 'WebViews: ' + parent.parent.webViewsPath + '\r\n';
if (parent.parent.webViewsOverridePath) { cmdData.result += 'XWebPublic: ' + parent.parent.webViewsOverridePath + '\r\n'; }
if (parent.parent.webViewsOverridePath) { cmdData.result += 'XWebViews: ' + parent.parent.webPublicOverridePath + '\r\n'; }
}
function migrationagentsConsoleCommand(cmdData) {
if (parent.parent.swarmserver == null) {
cmdData.result = 'Swarm server not running.';
} else {
for (var i in parent.parent.swarmserver.migrationAgents) {
var arch = parent.parent.swarmserver.migrationAgents[i];
for (var j in arch) { var agent = arch[j]; cmdData.result += 'Arch ' + agent.arch + ', Ver ' + agent.ver + ', Size ' + ((agent.binary == null) ? 0 : agent.binary.length) + '<br />'; }
}
}
}
function swarmstatsConsoleCommand(cmdData) {
if (parent.parent.swarmserver == null) {
cmdData.result = 'Swarm server not running.';
} else {
for (var i in parent.parent.swarmserver.stats) {
if (typeof parent.parent.swarmserver.stats[i] == 'object') {
cmdData.result += i + ': ' + JSON.stringify(parent.parent.swarmserver.stats[i]) + '\r\n';
} else {
cmdData.result += i + ': ' + parent.parent.swarmserver.stats[i] + '\r\n';
}
}
}
}
function relaysConsoleCommand(cmdData) {
for (var i in parent.wsrelays) {
cmdData.result += 'id: ' + i + ', ' + ((parent.wsrelays[i].state == 2) ? 'connected' : 'pending');
if (parent.wsrelays[i].peer1 != null) {
cmdData.result += ', ' + cleanRemoteAddr(parent.wsrelays[i].peer1.req.clientIp);
if (parent.wsrelays[i].peer1.user) { cmdData.result += ' (User:' + parent.wsrelays[i].peer1.user.name + ')' }
}
if (parent.wsrelays[i].peer2 != null) {
cmdData.result += ' to ' + cleanRemoteAddr(parent.wsrelays[i].peer2.req.clientIp);
if (parent.wsrelays[i].peer2.user) { cmdData.result += ' (User:' + parent.wsrelays[i].peer2.user.name + ')' }
}
cmdData.result += '\r\n';
}
if (cmdData.result == '') { cmdData.result = 'No relays.'; }
}
function autobackupConsoleCommand(cmdData) {
var backupResult = parent.db.performBackup(function (msg) {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: msg, tag: cmdData.command.tag })); } catch (ex) { }
});
if (backupResult == 0) { cmdData.result = 'Starting auto-backup...'; } else { cmdData.result = 'Backup alreay in progress.'; }
}
function backupconfigConsoleCommand(cmdData) {
cmdData.result = parent.db.getBackupConfig();
}
function firebaseConsoleCommand(cmdData) {
if (parent.parent.firebase == null) {
cmdData.result = "Firebase push messaging not supported";
} else {
cmdData.result = JSON.stringify(parent.parent.firebase.stats, null, 2);
}
}
// Process incoming web socket data from the browser // Process incoming web socket data from the browser
function processWebSocketData(msg) { function processWebSocketData(msg) {
var command, i = 0, mesh = null, meshid = null, nodeid = null, meshlinks = null, change = 0; var command, i = 0, mesh = null, meshid = null, nodeid = null, meshlinks = null, change = 0;