1
0
Fork 0
mirror of https://github.com/Ylianst/MeshCentral.git synced 2025-02-14 20:11:52 +00:00

Worked on meshcore.js minification.

This commit is contained in:
Ylian Saint-Hilaire 2022-01-16 13:37:26 -08:00
parent 169a198efb
commit c029a82ae6
3 changed files with 5175 additions and 250 deletions

5017
agents/meshcore-org.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -46,16 +46,12 @@ var MESHRIGHT_CHATNOTIFY = 16384;
var MESHRIGHT_UNINSTALL = 32768; var MESHRIGHT_UNINSTALL = 32768;
var MESHRIGHT_NODESKTOP = 65536; var MESHRIGHT_NODESKTOP = 65536;
try try {
{
Object.defineProperty(Array.prototype, 'findIndex', { Object.defineProperty(Array.prototype, 'findIndex', {
value: function (func) value: function (func) {
{
var i = 0; var i = 0;
for (i = 0; i < this.length; ++i) for (i = 0; i < this.length; ++i) {
{ if (func(this[i], i, this)) {
if (func(this[i], i, this))
{
return (i); return (i);
} }
} }
@ -63,8 +59,7 @@ try
} }
}); });
} }
catch (x) catch (x) {
{
} }
if (require('MeshAgent').ARCHID == null) { if (require('MeshAgent').ARCHID == null) {
@ -88,18 +83,14 @@ if (require('MeshAgent').ARCHID == null) {
if (id != null) { Object.defineProperty(require('MeshAgent'), 'ARCHID', { value: id }); } if (id != null) { Object.defineProperty(require('MeshAgent'), 'ARCHID', { value: id }); }
} }
function setDefaultCoreTranslation(obj, field, value) function setDefaultCoreTranslation(obj, field, value) {
{
if (obj[field] == null || obj[field] == '') { obj[field] = value; } if (obj[field] == null || obj[field] == '') { obj[field] = value; }
} }
function getCoreTranslation() function getCoreTranslation() {
{
var ret = {}; var ret = {};
if (global.coretranslations != null) if (global.coretranslations != null) {
{ try {
try
{
var lang = require('util-language').current; var lang = require('util-language').current;
if (coretranslations[lang] == null) { lang = lang.split('-')[0]; } if (coretranslations[lang] == null) { lang = lang.split('-')[0]; }
if (coretranslations[lang] == null) { lang = 'en'; } if (coretranslations[lang] == null) { lang = 'en'; }
@ -123,13 +114,10 @@ function getCoreTranslation()
} }
var currentTranslation = getCoreTranslation(); var currentTranslation = getCoreTranslation();
function lockDesktop(uid) function lockDesktop(uid) {
{ switch (process.platform) {
switch (process.platform)
{
case 'linux': case 'linux':
if (uid != null) if (uid != null) {
{
var name = require('user-sessions').getUsername(uid); var name = require('user-sessions').getUsername(uid);
var child = require('child_process').execFile('/bin/sh', ['sh']); var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (chunk) { this.str += chunk.toString(); }); child.stdout.str = ''; child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
@ -141,8 +129,7 @@ function lockDesktop(uid)
child.stdin.write("}'\nexit\n"); child.stdin.write("}'\nexit\n");
child.waitExit(); child.waitExit();
} }
else else {
{
var child = require('child_process').execFile('/bin/sh', ['sh']); var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (chunk) { this.str += chunk.toString(); }); child.stdout.str = ''; child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (chunk) { this.str += chunk.toString(); }); child.stderr.str = ''; child.stderr.on('data', function (chunk) { this.str += chunk.toString(); });
@ -162,25 +149,20 @@ function lockDesktop(uid)
} }
} }
var writable = require('stream').Writable; var writable = require('stream').Writable;
function destopLockHelper_pipe(httprequest) function destopLockHelper_pipe(httprequest) {
{
if (process.platform != 'linux' && process.platform != 'freebsd') { return; } if (process.platform != 'linux' && process.platform != 'freebsd') { return; }
if (httprequest.unlockerHelper == null && httprequest.desktop != null && httprequest.desktop.kvm != null) if (httprequest.unlockerHelper == null && httprequest.desktop != null && httprequest.desktop.kvm != null) {
{
httprequest.unlockerHelper = new writable( httprequest.unlockerHelper = new writable(
{ {
'write': function (chunk, flush) 'write': function (chunk, flush) {
{ if (chunk.readUInt16BE(0) == 65) {
if (chunk.readUInt16BE(0) == 65)
{
delete this.request.autolock; delete this.request.autolock;
} }
flush(); flush();
return (true); return (true);
}, },
'final': function (flush) 'final': function (flush) {
{
flush(); flush();
} }
}); });
@ -217,14 +199,11 @@ if (process.platform == 'win32' && require('user-sessions').isRoot()) {
} catch (e) { } } catch (e) { }
} }
if (process.platform != 'win32') if (process.platform != 'win32') {
{
var ch = require('child_process'); var ch = require('child_process');
ch._execFile = ch.execFile; ch._execFile = ch.execFile;
ch.execFile = function execFile(path, args, options) ch.execFile = function execFile(path, args, options) {
{ if (options && options.type && options.type == ch.SpawnTypes.TERM && options.env) {
if(options && options.type && options.type == ch.SpawnTypes.TERM && options.env)
{
options.env['TERM'] = 'xterm-256color'; options.env['TERM'] = 'xterm-256color';
} }
return (this._execFile(path, args, options)); return (this._execFile(path, args, options));
@ -444,7 +423,7 @@ function updateRegisteredAppsToServer() {
if ((obj.DAIPC == null) || (obj.DAIPC._daipc == null)) return; if ((obj.DAIPC == null) || (obj.DAIPC._daipc == null)) return;
var apps = {}; var apps = {};
for (var i in obj.DAIPC._daipc) { if (apps[obj.DAIPC._daipc[i]._registered] == null) { apps[obj.DAIPC._daipc[i]._registered] = 1; } else { apps[obj.DAIPC._daipc[i]._registered]++; } } for (var i in obj.DAIPC._daipc) { if (apps[obj.DAIPC._daipc[i]._registered] == null) { apps[obj.DAIPC._daipc[i]._registered] = 1; } else { apps[obj.DAIPC._daipc[i]._registered]++; } }
try { mesh.SendCommand({ action: 'sessions', type: 'app', value: apps }); } catch (e) { } try { mesh.SendCommand({ action: 'sessions', type: 'app', value: apps }); } catch (ex) { }
} }
// Remove a registered app // Remove a registered app
@ -455,16 +434,14 @@ function removeRegisteredApp(pipe) {
function diagnosticAgent_uninstall() { function diagnosticAgent_uninstall() {
require('service-manager').manager.uninstallService('meshagentDiagnostic'); require('service-manager').manager.uninstallService('meshagentDiagnostic');
require('task-scheduler').delete('meshagentDiagnostic/periodicStart'); require('task-scheduler').delete('meshagentDiagnostic/periodicStart'); // TODO: Using "delete" here breaks the minifier since this is a reserved keyword
} }
function diagnosticAgent_installCheck(install) { function diagnosticAgent_installCheck(install) {
try { try {
var diag = require('service-manager').manager.getService('meshagentDiagnostic'); var diag = require('service-manager').manager.getService('meshagentDiagnostic');
return (diag); return (diag);
} } catch (ex) { }
catch (e) { if (!install) { return null; }
}
if (!install) { return (null); }
var svc = null; var svc = null;
try { try {
@ -479,9 +456,7 @@ function diagnosticAgent_installCheck(install) {
}); });
svc = require('service-manager').manager.getService('meshagentDiagnostic'); svc = require('service-manager').manager.getService('meshagentDiagnostic');
} }
catch (e) { catch (ex) { return null; }
return (null);
}
var proxyConfig = require('global-tunnel').proxyConfig; var proxyConfig = require('global-tunnel').proxyConfig;
var cert = require('MeshAgent').GenerateAgentCertificate('CN=MeshNodeDiagnosticCertificate'); var cert = require('MeshAgent').GenerateAgentCertificate('CN=MeshNodeDiagnosticCertificate');
var nodeid = require('tls').loadCertificate(cert.root).getKeyHash().toString('base64'); var nodeid = require('tls').loadCertificate(cert.root).getKeyHash().toString('base64');
@ -494,8 +469,7 @@ function diagnosticAgent_installCheck(install) {
if (cert.tls) { ddb.Put('SelfNodeTlsCert', cert.tls.pfx); } if (cert.tls) { ddb.Put('SelfNodeTlsCert', cert.tls.pfx); }
if (proxyConfig) { if (proxyConfig) {
ddb.Put('WebProxy', proxyConfig.host + ':' + proxyConfig.port); ddb.Put('WebProxy', proxyConfig.host + ':' + proxyConfig.port);
} } else {
else {
ddb.Put('ignoreProxyFile', '1'); ddb.Put('ignoreProxyFile', '1');
} }
@ -520,7 +494,7 @@ if ((require('fs').existsSync(process.cwd() + 'batterystate.txt')) && (require('
try { try {
require('MeshAgent')._batteryFileTimer = null; require('MeshAgent')._batteryFileTimer = null;
var data = null; var data = null;
try { data = require('fs').readFileSync(process.cwd() + 'batterystate.txt').toString(); } catch (e) { } try { data = require('fs').readFileSync(process.cwd() + 'batterystate.txt').toString(); } catch (ex) { }
if ((data != null) && (data.length < 10)) { if ((data != null) && (data.length < 10)) {
data = data.split(','); data = data.split(',');
if ((data.length == 2) && ((data[0] == 'ac') || (data[0] == 'dc'))) { if ((data.length == 2) && ((data[0] == 'ac') || (data[0] == 'dc'))) {
@ -528,14 +502,12 @@ if ((require('fs').existsSync(process.cwd() + 'batterystate.txt')) && (require('
if ((level >= 0) && (level <= 100)) { require('MeshAgent').SendCommand({ action: 'battery', state: data[0], level: level }); } if ((level >= 0) && (level <= 100)) { require('MeshAgent').SendCommand({ action: 'battery', state: data[0], level: level }); }
} }
} }
} catch (e) { } } catch (ex) { }
}, 1000); }, 1000);
}); });
} }
else else {
{ try {
try
{
// Setup normal battery monitoring // Setup normal battery monitoring
if (require('identifiers').isBatteryPowered && require('identifiers').isBatteryPowered()) { if (require('identifiers').isBatteryPowered && require('identifiers').isBatteryPowered()) {
require('MeshAgent')._battLevelChanged = function _battLevelChanged(val) { require('MeshAgent')._battLevelChanged = function _battLevelChanged(val) {
@ -559,17 +531,15 @@ else
}); });
} }
} }
catch(e) catch (ex) { }
{
}
} }
// MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent. // MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
var meshCoreObj = { action: 'coreinfo', value: (require('MeshAgent').coreHash ? ((process.versions.compileTime?process.versions.compileTime:'').split(', ')[1].replace(' ', ' ') + ', ' + crc32c(require('MeshAgent').coreHash)) : ('MeshCore v6')), caps: 14, root: require('user-sessions').isRoot() }; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript, 32 = Temporary Agent, 64 = Recovery Agent var meshCoreObj = { action: 'coreinfo', value: (require('MeshAgent').coreHash ? ((process.versions.compileTime ? process.versions.compileTime : '').split(', ')[1].replace(' ', ' ') + ', ' + crc32c(require('MeshAgent').coreHash)) : ('MeshCore v6')), caps: 14, root: require('user-sessions').isRoot() }; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript, 32 = Temporary Agent, 64 = Recovery Agent
// Get the operating system description string // Get the operating system description string
try { require('os').name().then(function (v) { meshCoreObj.osdesc = v; meshCoreObjChanged(); }); } catch (e) { } try { require('os').name().then(function (v) { meshCoreObj.osdesc = v; meshCoreObjChanged(); }); } catch (ex) { }
// Setup logged in user monitoring (THIS IS BROKEN IN WIN7) // Setup logged in user monitoring (THIS IS BROKEN IN WIN7)
@ -600,7 +570,7 @@ try {
userSession.emit('changed'); userSession.emit('changed');
//userSession.on('locked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has LOCKED the desktop'); }); //userSession.on('locked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has LOCKED the desktop'); });
//userSession.on('unlocked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has UNLOCKED the desktop'); }); //userSession.on('unlocked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has UNLOCKED the desktop'); });
} catch (e) { } } catch (ex) { }
var meshServerConnectionState = 0; var meshServerConnectionState = 0;
var tunnels = {}; var tunnels = {};
@ -661,7 +631,7 @@ if (mesh.hasKVM == 1) { // if the agent is compiled with KVM support
} else if (process.platform == 'linux' || process.platform == 'freebsd') { } else if (process.platform == 'linux' || process.platform == 'freebsd') {
require('monitor-info').on('kvmSupportDetected', function (value) { meshCoreObj.caps |= 1; meshCoreObjChanged(); }); require('monitor-info').on('kvmSupportDetected', function (value) { meshCoreObj.caps |= 1; meshCoreObjChanged(); });
} }
} catch (e) { } } catch (ex) { }
} }
mesh.DAIPC = obj.DAIPC; mesh.DAIPC = obj.DAIPC;
@ -672,7 +642,7 @@ try {
networkMonitor.on('change', function () { sendNetworkUpdateNagle(); }); networkMonitor.on('change', function () { sendNetworkUpdateNagle(); });
networkMonitor.on('add', function (addr) { sendNetworkUpdateNagle(); }); networkMonitor.on('add', function (addr) { sendNetworkUpdateNagle(); });
networkMonitor.on('remove', function (addr) { sendNetworkUpdateNagle(); }); networkMonitor.on('remove', function (addr) { sendNetworkUpdateNagle(); });
} catch (e) { networkMonitor = null; } } catch (ex) { networkMonitor = null; }
*/ */
// Fetch the SMBios Tables // Fetch the SMBios Tables
@ -680,7 +650,7 @@ var SMBiosTables = null;
var SMBiosTablesRaw = null; var SMBiosTablesRaw = null;
try { try {
var SMBiosModule = null; var SMBiosModule = null;
try { SMBiosModule = require('smbios'); } catch (e) { } try { SMBiosModule = require('smbios'); } catch (ex) { }
if (SMBiosModule != null) { if (SMBiosModule != null) {
SMBiosModule.get(function (data) { SMBiosModule.get(function (data) {
if (data != null) { if (data != null) {
@ -700,14 +670,14 @@ try {
} }
}); });
} }
} catch (e) { sendConsoleText("ex1: " + e); } } catch (ex) { sendConsoleText("ex1: " + ex); }
// Try to load up the WIFI scanner // Try to load up the WIFI scanner
try { try {
var wifiScannerLib = require('wifi-scanner'); var wifiScannerLib = require('wifi-scanner');
wifiScanner = new wifiScannerLib(); wifiScanner = new wifiScannerLib();
wifiScanner.on('accessPoint', function (data) { sendConsoleText("wifiScanner: " + data); }); wifiScanner.on('accessPoint', function (data) { sendConsoleText("wifiScanner: " + data); });
} catch (e) { wifiScannerLib = null; wifiScanner = null; } } catch (ex) { wifiScannerLib = null; wifiScanner = null; }
// Get our location (lat/long) using our public IP address // Get our location (lat/long) using our public IP address
var getIpLocationDataExInProgress = false; var getIpLocationDataExInProgress = false;
@ -730,7 +700,7 @@ function getIpLocationDataEx(func) {
var result = JSON.parse(geoData); var result = JSON.parse(geoData);
if (result.ip && result.loc) { location = result; } if (result.ip && result.loc) { location = result; }
} }
} catch (e) { } } catch (ex) { }
if (func) { getIpLocationDataExCounts[1]++; func(location); } if (func) { getIpLocationDataExCounts[1]++; func(location); }
} }
} else } else
@ -739,7 +709,7 @@ function getIpLocationDataEx(func) {
}).end(); }).end();
return true; return true;
} }
catch (e) { return false; } catch (ex) { return false; }
} }
// Setup script task. Allows running scripts at scheduled intervals // Setup script task. Allows running scripts at scheduled intervals
@ -949,7 +919,7 @@ function sendWakeOnLanEx(hexMacList) {
require('MeshAgent').wakesockets.sockets.push(socket); require('MeshAgent').wakesockets.sockets.push(socket);
++ret; ++ret;
} }
catch (e) { } catch (ex) { }
} }
} }
} }
@ -963,43 +933,32 @@ function sendWakeOnLanEx(hexMacList) {
ret = require('MeshAgent').wakesockets.sockets.length; ret = require('MeshAgent').wakesockets.sockets.length;
} }
return (ret); return ret;
} }
function server_promise_default(res, rej) function server_promise_default(res, rej) {
{
this.resolve = res; this.resolve = res;
this.reject = rej; this.reject = rej;
} }
function server_getUserImage(userid) function server_getUserImage(userid) {
{ var xpromise = require('promise');
var promise = require('promise'); var ret = new xpromise(server_promise_default);
var ret = new promise(server_promise_default);
if (require('MeshAgent')._promises == null) { require('MeshAgent')._promises = {}; } if (require('MeshAgent')._promises == null) { require('MeshAgent')._promises = {}; }
require('MeshAgent')._promises[ret._hashCode()] = ret; require('MeshAgent')._promises[ret._hashCode()] = ret;
require('MeshAgent').SendCommand({ action: 'getUserImage', userid: userid, promise: ret._hashCode(), default: true }); require('MeshAgent').SendCommand({ action: 'getUserImage', userid: userid, promise: ret._hashCode(), sentDefault: true });
return (ret); return ret;
} }
require('MeshAgent')._consentTimers = {}; require('MeshAgent')._consentTimers = {};
function server_set_consentTimer(id) function server_set_consentTimer(id) {
{
require('MeshAgent')._consentTimers[id] = new Date(); require('MeshAgent')._consentTimers[id] = new Date();
} }
function server_check_consentTimer(id) function server_check_consentTimer(id) {
{ if (require('MeshAgent')._consentTimers[id] != null) {
if (require('MeshAgent')._consentTimers[id] != null) if ((new Date()) - require('MeshAgent')._consentTimers[id] < (60000 * 5)) return true;
{
if((new Date()) - require('MeshAgent')._consentTimers[id] < (60000*5))
{
return (true);
}
else
{
require('MeshAgent')._consentTimers[id] = null; require('MeshAgent')._consentTimers[id] = null;
} }
} return false;
return (false);
} }
// Handle a mesh agent command // Handle a mesh agent command
@ -1068,8 +1027,7 @@ function handleServerCommand(data) {
tunnel.guestname = data.guestname; tunnel.guestname = data.guestname;
tunnel.userid = data.userid; tunnel.userid = data.userid;
if (server_check_consentTimer(tunnel.userid)) if (server_check_consentTimer(tunnel.userid)) {
{
sendConsoleText('Deleting Consent Requirement'); sendConsoleText('Deleting Consent Requirement');
tunnel.consent = (tunnel.consent & -57); tunnel.consent = (tunnel.consent & -57);
} }
@ -1122,7 +1080,7 @@ function handleServerCommand(data) {
// Display a message box // Display a message box
if (data.title && data.msg) { if (data.title && data.msg) {
MeshServerLogEx(18, [data.title, data.msg], "Displaying message box, title=" + data.title + ", message=" + data.msg, data); MeshServerLogEx(18, [data.title, data.msg], "Displaying message box, title=" + data.title + ", message=" + data.msg, data);
try { require('message-box').create(data.title, data.msg, 120).then(function () { }).catch(function () { }); } catch (e) { } try { require('message-box').create(data.title, data.msg, 120).then(function () { }).catch(function () { }); } catch (ex) { }
} }
break; break;
} }
@ -1171,14 +1129,14 @@ function handleServerCommand(data) {
// Kill a process // Kill a process
if (data.value) { if (data.value) {
MeshServerLogEx(19, [data.value], "Killing process " + data.value, data); MeshServerLogEx(19, [data.value], "Killing process " + data.value, data);
try { process.kill(data.value); } catch (e) { sendConsoleText("pskill: " + JSON.stringify(e)); } try { process.kill(data.value); } catch (ex) { sendConsoleText("pskill: " + JSON.stringify(e)); }
} }
break; break;
} }
case 'services': { case 'services': {
// Return the list of installed services // Return the list of installed services
var services = null; var services = null;
try { services = require('service-manager').manager.enumerateService(); } catch (e) { } try { services = require('service-manager').manager.enumerateService(); } catch (ex) { }
if (services != null) { mesh.SendCommand({ action: 'msg', type: 'services', value: JSON.stringify(services), sessionid: data.sessionid }); } if (services != null) { mesh.SendCommand({ action: 'msg', type: 'services', value: JSON.stringify(services), sessionid: data.sessionid }); }
break; break;
} }
@ -1187,7 +1145,7 @@ function handleServerCommand(data) {
try { try {
var service = require('service-manager').manager.getService(data.serviceName); var service = require('service-manager').manager.getService(data.serviceName);
if (service != null) { service.stop(); } if (service != null) { service.stop(); }
} catch (e) { } } catch (ex) { }
break; break;
} }
case 'serviceStart': { case 'serviceStart': {
@ -1195,7 +1153,7 @@ function handleServerCommand(data) {
try { try {
var service = require('service-manager').manager.getService(data.serviceName); var service = require('service-manager').manager.getService(data.serviceName);
if (service != null) { service.start(); } if (service != null) { service.start(); }
} catch (e) { } } catch (ex) { }
break; break;
} }
case 'serviceRestart': { case 'serviceRestart': {
@ -1203,7 +1161,7 @@ function handleServerCommand(data) {
try { try {
var service = require('service-manager').manager.getService(data.serviceName); var service = require('service-manager').manager.getService(data.serviceName);
if (service != null) { service.restart(); } if (service != null) { service.restart(); }
} catch (e) { } } catch (ex) { }
break; break;
} }
case 'deskBackground': case 'deskBackground':
@ -1236,7 +1194,7 @@ function handleServerCommand(data) {
if (current != '/dev/null') { require('MeshAgent')._wallpaper = current; } if (current != '/dev/null') { require('MeshAgent')._wallpaper = current; }
require('linux-gnome-helpers').setDesktopWallpaper(id, current != '/dev/null' ? undefined : require('MeshAgent')._wallpaper); require('linux-gnome-helpers').setDesktopWallpaper(id, current != '/dev/null' ? undefined : require('MeshAgent')._wallpaper);
} }
} catch (e) { } catch (ex) {
sendConsoleText(e); sendConsoleText(e);
} }
break; break;
@ -1363,7 +1321,7 @@ function handleServerCommand(data) {
// data.runAsUser: 0=Agent,1=UserOrAgent,2=UserOnly // data.runAsUser: 0=Agent,1=UserOrAgent,2=UserOnly
var options = {}; var options = {};
if (data.runAsUser > 0) { if (data.runAsUser > 0) {
try { options.uid = require('user-sessions').consoleUid(); } catch (e) { } try { options.uid = require('user-sessions').consoleUid(); } catch (ex) { }
options.type = require('child_process').SpawnTypes.TERM; options.type = require('child_process').SpawnTypes.TERM;
} }
if (data.runAsUser == 2) { if (data.runAsUser == 2) {
@ -1410,7 +1368,7 @@ function handleServerCommand(data) {
} }
if (require('service-manager').manager.getService(agentName).isMe()) { if (require('service-manager').manager.getService(agentName).isMe()) {
try { diagnosticAgent_uninstall(); } catch (e) { } try { diagnosticAgent_uninstall(); } catch (ex) { }
var js = "require('service-manager').manager.getService('" + agentName + "').stop(); require('service-manager').manager.uninstallService('" + agentName + "'); process.exit();"; var js = "require('service-manager').manager.getService('" + agentName + "').stop(); require('service-manager').manager.uninstallService('" + agentName + "'); process.exit();";
this.child = require('child_process').execFile(process.execPath, [process.platform == 'win32' ? (process.execPath.split('\\').pop()) : (process.execPath.split('/').pop()), '-b64exec', Buffer.from(js).toString('base64')], { type: 4, detached: true }); this.child = require('child_process').execFile(process.execPath, [process.platform == 'win32' ? (process.execPath.split('\\').pop()) : (process.execPath.split('/').pop()), '-b64exec', Buffer.from(js).toString('base64')], { type: 4, detached: true });
} }
@ -1438,7 +1396,7 @@ function handleServerCommand(data) {
if (data.title && data.msg) { if (data.title && data.msg) {
MeshServerLogEx(26, [data.title, data.msg], "Displaying toast message, title=" + data.title + ", message=" + data.msg, data); MeshServerLogEx(26, [data.title, data.msg], "Displaying toast message, title=" + data.title + ", message=" + data.msg, data);
data.msg = data.msg.split('\r').join('\\r').split('\n').join('\\n'); data.msg = data.msg.split('\r').join('\\r').split('\n').join('\\n');
try { require('toaster').Toast(data.title, data.msg); } catch (e) { } try { require('toaster').Toast(data.title, data.msg); } catch (ex) { }
} }
break; break;
} }
@ -1492,7 +1450,7 @@ function handleServerCommand(data) {
case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; } case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; }
case 'pong': { break; } case 'pong': { break; }
case 'plugin': { case 'plugin': {
try { require(data.plugin).consoleaction(data, data.rights, data.sessionid, this); } catch (e) { throw e; } try { require(data.plugin).consoleaction(data, data.rights, data.sessionid, this); } catch (ex) { throw ex; }
break; break;
} }
case 'coredump': case 'coredump':
@ -1544,8 +1502,7 @@ function handleServerCommand(data) {
case 'getUserImage': case 'getUserImage':
if (data.pipe == true) { delete data.pipe; delete data.action; data.cmd = 'getUserImage'; broadcastToRegisteredApps(data); } if (data.pipe == true) { delete data.pipe; delete data.action; data.cmd = 'getUserImage'; broadcastToRegisteredApps(data); }
if (data.tag == 'info') { sendConsoleText(JSON.stringify(data, null, 2)); } if (data.tag == 'info') { sendConsoleText(JSON.stringify(data, null, 2)); }
if (data.promise != null && require('MeshAgent')._promises[data.promise] != null) if (data.promise != null && require('MeshAgent')._promises[data.promise] != null) {
{
var p = require('MeshAgent')._promises[data.promise]; var p = require('MeshAgent')._promises[data.promise];
delete require('MeshAgent')._promises[data.promise]; delete require('MeshAgent')._promises[data.promise];
p.resolve(data.image); p.resolve(data.image);
@ -1614,7 +1571,7 @@ function downloadFile(downloadoptions) {
function handleApfJsonControl(data) { function handleApfJsonControl(data) {
if (data.action == 'console') { addAmtEvent(data.msg); } // Add console message to AMT event log if (data.action == 'console') { addAmtEvent(data.msg); } // Add console message to AMT event log
if (data.action == 'mestate') { amt.getMeiState(15, function (state) { apftunnel.updateMeiState(state); }); } // Update the MEI state if (data.action == 'mestate') { amt.getMeiState(15, function (state) { apftunnel.updateMeiState(state); }); } // Update the MEI state
if (data.action == 'close') { try { apftunnel.disconnect(); } catch (e) { } apftunnel = null; } // Close the CIRA-LMS connection if (data.action == 'close') { try { apftunnel.disconnect(); } catch (ex) { } apftunnel = null; } // Close the CIRA-LMS connection
if (amt.amtMei != null) { if (amt.amtMei != null) {
if (data.action == 'deactivate') { // Request CCM deactivation if (data.action == 'deactivate') { // Request CCM deactivation
amt.amtMei.unprovision(1, function (status) { if (apftunnel) apftunnel.sendMeiDeactivationState(status); }); // 0 = Success amt.amtMei.unprovision(1, function (status) { if (apftunnel) apftunnel.sendMeiDeactivationState(status); }); // 0 = Success
@ -1683,18 +1640,18 @@ function getSystemInformation(func) {
if (results.hardware && results.hardware.windows) { if (results.hardware && results.hardware.windows) {
// Remove extra entries and things that change quickly // Remove extra entries and things that change quickly
var x = results.hardware.windows.osinfo; var x = results.hardware.windows.osinfo;
try { delete x.FreePhysicalMemory; } catch (e) { } try { delete x.FreePhysicalMemory; } catch (ex) { }
try { delete x.FreeSpaceInPagingFiles; } catch (e) { } try { delete x.FreeSpaceInPagingFiles; } catch (ex) { }
try { delete x.FreeVirtualMemory; } catch (e) { } try { delete x.FreeVirtualMemory; } catch (ex) { }
try { delete x.LocalDateTime; } catch (e) { } try { delete x.LocalDateTime; } catch (ex) { }
try { delete x.MaxProcessMemorySize; } catch (e) { } try { delete x.MaxProcessMemorySize; } catch (ex) { }
try { delete x.TotalVirtualMemorySize; } catch (e) { } try { delete x.TotalVirtualMemorySize; } catch (ex) { }
try { delete x.TotalVisibleMemorySize; } catch (e) { } try { delete x.TotalVisibleMemorySize; } catch (ex) { }
try { try {
if (results.hardware.windows.memory) { for (var i in results.hardware.windows.memory) { delete results.hardware.windows.memory[i].Node; } } if (results.hardware.windows.memory) { for (var i in results.hardware.windows.memory) { delete results.hardware.windows.memory[i].Node; } }
if (results.hardware.windows.osinfo) { delete results.hardware.windows.osinfo.Node; } if (results.hardware.windows.osinfo) { delete results.hardware.windows.osinfo.Node; }
if (results.hardware.windows.partitions) { for (var i in results.hardware.windows.partitions) { delete results.hardware.windows.partitions[i].Node; } } if (results.hardware.windows.partitions) { for (var i in results.hardware.windows.partitions) { delete results.hardware.windows.partitions[i].Node; } }
} catch (e) { } } catch (ex) { }
} }
results.hardware.agentvers = process.versions; results.hardware.agentvers = process.versions;
var hasher = require('SHA384Stream').create(); var hasher = require('SHA384Stream').create();
@ -1735,7 +1692,7 @@ function getSystemInformation(func) {
func(results); func(results);
} }
*/ */
} catch (e) { func(null, e); } } catch (ex) { func(null, e); }
} }
// Get a formated response for a given directory path // Get a formated response for a given directory path
@ -1744,7 +1701,7 @@ function getDirectoryInfo(reqpath) {
if (((reqpath == undefined) || (reqpath == '')) && (process.platform == 'win32')) { if (((reqpath == undefined) || (reqpath == '')) && (process.platform == 'win32')) {
// List all the drives in the root, or the root itself // List all the drives in the root, or the root itself
var results = null; var results = null;
try { results = fs.readDrivesSync(); } catch (e) { } // TODO: Anyway to get drive total size and free space? Could draw a progress bar. try { results = fs.readDrivesSync(); } catch (ex) { } // TODO: Anyway to get drive total size and free space? Could draw a progress bar.
if (results != null) { if (results != null) {
for (var i = 0; i < results.length; ++i) { for (var i = 0; i < results.length; ++i) {
var drive = { n: results[i].name, t: 1 }; var drive = { n: results[i].name, t: 1 };
@ -1757,14 +1714,14 @@ function getDirectoryInfo(reqpath) {
if (reqpath == '') { reqpath = '/'; } if (reqpath == '') { reqpath = '/'; }
var results = null, xpath = obj.path.join(reqpath, '*'); var results = null, xpath = obj.path.join(reqpath, '*');
//if (process.platform == "win32") { xpath = xpath.split('/').join('\\'); } //if (process.platform == "win32") { xpath = xpath.split('/').join('\\'); }
try { results = fs.readdirSync(xpath); } catch (e) { } try { results = fs.readdirSync(xpath); } catch (ex) { }
try { if ((results != null) && (results.length == 0) && (fs.existsSync(reqpath) == false)) { results = null; } } catch (e) { } try { if ((results != null) && (results.length == 0) && (fs.existsSync(reqpath) == false)) { results = null; } } catch (ex) { }
if (results != null) { if (results != null) {
for (var i = 0; i < results.length; ++i) { for (var i = 0; i < results.length; ++i) {
if ((results[i] != '.') && (results[i] != '..')) { if ((results[i] != '.') && (results[i] != '..')) {
var stat = null, p = obj.path.join(reqpath, results[i]); var stat = null, p = obj.path.join(reqpath, results[i]);
//if (process.platform == "win32") { p = p.split('/').join('\\'); } //if (process.platform == "win32") { p = p.split('/').join('\\'); }
try { stat = fs.statSync(p); } catch (e) { } // TODO: Get file size/date try { stat = fs.statSync(p); } catch (ex) { } // TODO: Get file size/date
if ((stat != null) && (stat != undefined)) { if ((stat != null) && (stat != undefined)) {
if (stat.isDirectory() == true) { if (stat.isDirectory() == true) {
response.dir.push({ n: results[i], t: 2, d: stat.mtime }); response.dir.push({ n: results[i], t: 2, d: stat.mtime });
@ -1812,7 +1769,7 @@ function onTunnelUpgrade(response, s, head) {
if (s.httprequest.userid != null) { if (s.httprequest.userid != null) {
var userid = getUserIdAndGuestNameFromHttpRequest(s.httprequest); var userid = getUserIdAndGuestNameFromHttpRequest(s.httprequest);
if (tunnelUserCount.tcp[userid] == null) { tunnelUserCount.tcp[userid] = 1; } else { tunnelUserCount.tcp[userid]++; } if (tunnelUserCount.tcp[userid] == null) { tunnelUserCount.tcp[userid] = 1; } else { tunnelUserCount.tcp[userid]++; }
try { mesh.SendCommand({ action: 'sessions', type: 'tcp', value: tunnelUserCount.tcp }); } catch (e) { } try { mesh.SendCommand({ action: 'sessions', type: 'tcp', value: tunnelUserCount.tcp }); } catch (ex) { }
broadcastSessionsToRegisteredApps(); broadcastSessionsToRegisteredApps();
} }
} if (this.udpport != null) { } if (this.udpport != null) {
@ -1830,7 +1787,7 @@ function onTunnelUpgrade(response, s, head) {
if (s.httprequest.userid != null) { if (s.httprequest.userid != null) {
var userid = getUserIdAndGuestNameFromHttpRequest(s.httprequest); var userid = getUserIdAndGuestNameFromHttpRequest(s.httprequest);
if (tunnelUserCount.udp[userid] == null) { tunnelUserCount.udp[userid] = 1; } else { tunnelUserCount.udp[userid]++; } if (tunnelUserCount.udp[userid] == null) { tunnelUserCount.udp[userid] = 1; } else { tunnelUserCount.udp[userid]++; }
try { mesh.SendCommand({ action: 'sessions', type: 'udp', value: tunnelUserCount.tcp }); } catch (e) { } try { mesh.SendCommand({ action: 'sessions', type: 'udp', value: tunnelUserCount.tcp }); } catch (ex) { }
broadcastSessionsToRegisteredApps(); broadcastSessionsToRegisteredApps();
} }
} else { } else {
@ -1896,18 +1853,17 @@ function onTunnelClosed() {
if (this.httprequest.tcpport != null) { if (this.httprequest.tcpport != null) {
var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest); var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest);
if (tunnelUserCount.tcp[userid] != null) { tunnelUserCount.tcp[userid]--; if (tunnelUserCount.tcp[userid] <= 0) { delete tunnelUserCount.tcp[userid]; } } if (tunnelUserCount.tcp[userid] != null) { tunnelUserCount.tcp[userid]--; if (tunnelUserCount.tcp[userid] <= 0) { delete tunnelUserCount.tcp[userid]; } }
try { mesh.SendCommand({ action: 'sessions', type: 'tcp', value: tunnelUserCount.tcp }); } catch (e) { } try { mesh.SendCommand({ action: 'sessions', type: 'tcp', value: tunnelUserCount.tcp }); } catch (ex) { }
broadcastSessionsToRegisteredApps(); broadcastSessionsToRegisteredApps();
} else if (this.httprequest.udpport != null) { } else if (this.httprequest.udpport != null) {
var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest); var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest);
if (tunnelUserCount.udp[userid] != null) { tunnelUserCount.udp[userid]--; if (tunnelUserCount.udp[userid] <= 0) { delete tunnelUserCount.udp[userid]; } } if (tunnelUserCount.udp[userid] != null) { tunnelUserCount.udp[userid]--; if (tunnelUserCount.udp[userid] <= 0) { delete tunnelUserCount.udp[userid]; } }
try { mesh.SendCommand({ action: 'sessions', type: 'udp', value: tunnelUserCount.udp }); } catch (e) { } try { mesh.SendCommand({ action: 'sessions', type: 'udp', value: tunnelUserCount.udp }); } catch (ex) { }
broadcastSessionsToRegisteredApps(); broadcastSessionsToRegisteredApps();
} }
} }
try try {
{
// Sent tunnel statistics to the server, only send this if compression was used. // Sent tunnel statistics to the server, only send this if compression was used.
if ((this.bytesSent_uncompressed) && (this.bytesSent_uncompressed.toString() != this.bytesSent_actual.toString())) { if ((this.bytesSent_uncompressed) && (this.bytesSent_uncompressed.toString() != this.bytesSent_actual.toString())) {
mesh.SendCommand({ mesh.SendCommand({
@ -1925,8 +1881,7 @@ function onTunnelClosed() {
}); });
} }
} }
catch(z) catch (z) {
{
} }
//sendConsoleText("Tunnel #" + this.httprequest.index + " closed. Sent -> " + this.bytesSent_uncompressed + ' bytes (uncompressed), ' + this.bytesSent_actual + ' bytes (actual), ' + this.bytesSent_ratio + '% compression', this.httprequest.sessionid); //sendConsoleText("Tunnel #" + this.httprequest.index + " closed. Sent -> " + this.bytesSent_uncompressed + ' bytes (uncompressed), ' + this.bytesSent_actual + ' bytes (actual), ' + this.bytesSent_ratio + '% compression', this.httprequest.sessionid);
@ -1947,9 +1902,9 @@ function onTunnelClosed() {
// Clean up WebRTC // Clean up WebRTC
if (this.webrtc != null) { if (this.webrtc != null) {
if (this.webrtc.rtcchannel) { try { this.webrtc.rtcchannel.close(); } catch (e) { } this.webrtc.rtcchannel.removeAllListeners('data'); this.webrtc.rtcchannel.removeAllListeners('end'); delete this.webrtc.rtcchannel; } if (this.webrtc.rtcchannel) { try { this.webrtc.rtcchannel.close(); } catch (ex) { } this.webrtc.rtcchannel.removeAllListeners('data'); this.webrtc.rtcchannel.removeAllListeners('end'); delete this.webrtc.rtcchannel; }
if (this.webrtc.websocket) { delete this.webrtc.websocket; } if (this.webrtc.websocket) { delete this.webrtc.websocket; }
try { this.webrtc.close(); } catch (e) { } try { this.webrtc.close(); } catch (ex) { }
this.webrtc.removeAllListeners('connected'); this.webrtc.removeAllListeners('connected');
this.webrtc.removeAllListeners('disconnected'); this.webrtc.removeAllListeners('disconnected');
this.webrtc.removeAllListeners('dataChannel'); this.webrtc.removeAllListeners('dataChannel');
@ -1970,11 +1925,11 @@ function onTunnelData(data) {
if (data[0] == 0) { if (data[0] == 0) {
// If data starts with zero, skip the first byte. This is used to escape binary file data from JSON. // If data starts with zero, skip the first byte. This is used to escape binary file data from JSON.
this.httprequest.uploadFileSize += (data.length - 1); this.httprequest.uploadFileSize += (data.length - 1);
try { fs.writeSync(this.httprequest.uploadFile, data, 1, data.length - 1); } catch (e) { sendConsoleText('FileUpload Error'); this.write(Buffer.from(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out. try { fs.writeSync(this.httprequest.uploadFile, data, 1, data.length - 1); } catch (ex) { sendConsoleText('FileUpload Error'); this.write(Buffer.from(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out.
} else { } else {
// If data does not start with zero, save as-is. // If data does not start with zero, save as-is.
this.httprequest.uploadFileSize += data.length; this.httprequest.uploadFileSize += data.length;
try { fs.writeSync(this.httprequest.uploadFile, data); } catch (e) { sendConsoleText('FileUpload Error'); this.write(Buffer.from(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out. try { fs.writeSync(this.httprequest.uploadFile, data); } catch (ex) { sendConsoleText('FileUpload Error'); this.write(Buffer.from(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out.
} }
this.write(Buffer.from(JSON.stringify({ action: 'uploadack', reqid: this.httprequest.uploadFileid }))); // Ask for more data. this.write(Buffer.from(JSON.stringify({ action: 'uploadack', reqid: this.httprequest.uploadFileid }))); // Ask for more data.
return; return;
@ -2000,8 +1955,8 @@ function onTunnelData(data) {
// //
var stats = null; var stats = null;
if ((process.platform != 'win32') && (this.httprequest.xoptions.file.startsWith('/') == false)) { this.httprequest.xoptions.file = '/' + this.httprequest.xoptions.file; } if ((process.platform != 'win32') && (this.httprequest.xoptions.file.startsWith('/') == false)) { this.httprequest.xoptions.file = '/' + this.httprequest.xoptions.file; }
try { stats = require('fs').statSync(this.httprequest.xoptions.file) } catch (e) { } try { stats = require('fs').statSync(this.httprequest.xoptions.file) } catch (ex) { }
try { if (stats) { this.httprequest.downloadFile = fs.createReadStream(this.httprequest.xoptions.file, { flags: 'rbN' }); } } catch (e) { } try { if (stats) { this.httprequest.downloadFile = fs.createReadStream(this.httprequest.xoptions.file, { flags: 'rbN' }); } } catch (ex) { }
if (this.httprequest.downloadFile) { if (this.httprequest.downloadFile) {
MeshServerLogEx(106, [this.httprequest.xoptions.file, stats.size], 'Download: \"' + this.httprequest.xoptions.file + '\", Size: ' + stats.size, this.httprequest); MeshServerLogEx(106, [this.httprequest.xoptions.file, stats.size], 'Download: \"' + this.httprequest.xoptions.file + '\", Size: ' + stats.size, this.httprequest);
//sendConsoleText('BasicFileTransfer, ok, ' + this.httprequest.xoptions.file + ', ' + JSON.stringify(stats)); //sendConsoleText('BasicFileTransfer, ok, ' + this.httprequest.xoptions.file + ', ' + JSON.stringify(stats));
@ -2050,7 +2005,7 @@ function onTunnelData(data) {
if (this.httprequest.userid != null) { if (this.httprequest.userid != null) {
var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest); var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest);
if (tunnelUserCount.terminal[userid] != null) { tunnelUserCount.terminal[userid]--; if (tunnelUserCount.terminal[userid] <= 0) { delete tunnelUserCount.terminal[userid]; } } if (tunnelUserCount.terminal[userid] != null) { tunnelUserCount.terminal[userid]--; if (tunnelUserCount.terminal[userid] <= 0) { delete tunnelUserCount.terminal[userid]; } }
try { mesh.SendCommand({ action: 'sessions', type: 'terminal', value: tunnelUserCount.terminal }); } catch (e) { } try { mesh.SendCommand({ action: 'sessions', type: 'terminal', value: tunnelUserCount.terminal }); } catch (ex) { }
broadcastSessionsToRegisteredApps(); broadcastSessionsToRegisteredApps();
} }
@ -2077,49 +2032,40 @@ function onTunnelData(data) {
var consentMessage = currentTranslation['terminalConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); var consentMessage = currentTranslation['terminalConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username);
var consentTitle = 'MeshCentral'; var consentTitle = 'MeshCentral';
if (this.httprequest.soptions != null) if (this.httprequest.soptions != null) {
{
if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; } if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; }
if (this.httprequest.soptions.consentMsgTerminal != null) { consentMessage = this.httprequest.soptions.consentMsgTerminal.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } if (this.httprequest.soptions.consentMsgTerminal != null) { consentMessage = this.httprequest.soptions.consentMsgTerminal.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); }
} }
if (process.platform == 'win32') if (process.platform == 'win32') {
{
var enhanced = false; var enhanced = false;
try try {
{
require('win-userconsent'); require('win-userconsent');
enhanced = true; enhanced = true;
} }
catch (z) catch (z) {
{
} }
if (enhanced) if (enhanced) {
{
var ipr = server_getUserImage(this.httprequest.userid); var ipr = server_getUserImage(this.httprequest.userid);
ipr.consentTitle = consentTitle; ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage; ipr.consentMessage = consentMessage;
ipr.username = this.httprequest.realname; ipr.username = this.httprequest.realname;
ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage }; ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
this.httprequest.tpromise._consent = ipr.then(function (img) this.httprequest.tpromise._consent = ipr.then(function (img) {
{
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), timeout: 30000, translations: this.translations }); this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), timeout: 30000, translations: this.translations });
this.__childPromise.close = this.consent.close.bind(this.consent); this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent); return (this.consent);
}); });
} }
else else {
{
this.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, 30); this.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, 30);
} }
} }
else else {
{
this.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, 30); this.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, 30);
} }
this.httprequest.tpromise._consent.retPromise = this.httprequest.tpromise; this.httprequest.tpromise._consent.retPromise = this.httprequest.tpromise;
this.httprequest.tpromise._consent.then( this.httprequest.tpromise._consent.then(
function (always) function (always) {
{
if (always) { server_set_consentTimer(this.retPromise.httprequest.userid); } if (always) { server_set_consentTimer(this.retPromise.httprequest.userid); }
// Success // Success
@ -2194,8 +2140,8 @@ function onTunnelData(data) {
}); });
} }
} }
catch (e) { catch (ex) {
this.httprequest.connectionPromise._rej('Failed to start remote terminal session, ' + e.toString()); this.httprequest.connectionPromise._rej('Failed to start remote terminal session, ' + ex.toString());
} }
} }
else { else {
@ -2207,8 +2153,7 @@ function onTunnelData(data) {
var env = { HISTCONTROL: 'ignoreboth' }; var env = { HISTCONTROL: 'ignoreboth' };
if (process.env['LANG']) { env['LANG'] = process.env['LANG']; } if (process.env['LANG']) { env['LANG'] = process.env['LANG']; }
if (process.env['PATH']) { env['PATH'] = process.env['PATH']; } if (process.env['PATH']) { env['PATH'] = process.env['PATH']; }
if (this.httprequest.xoptions) if (this.httprequest.xoptions) {
{
if (this.httprequest.xoptions.rows) { env.LINES = ('' + this.httprequest.xoptions.rows); } if (this.httprequest.xoptions.rows) { env.LINES = ('' + this.httprequest.xoptions.rows); }
if (this.httprequest.xoptions.cols) { env.COLUMNS = ('' + this.httprequest.xoptions.cols); } if (this.httprequest.xoptions.cols) { env.COLUMNS = ('' + this.httprequest.xoptions.cols); }
} }
@ -2237,8 +2182,8 @@ function onTunnelData(data) {
this.httprequest.connectionPromise._rej('Failed to start remote terminal session, no shell found'); this.httprequest.connectionPromise._rej('Failed to start remote terminal session, no shell found');
} }
} }
catch (e) { catch (ex) {
this.httprequest.connectionPromise._rej('Failed to start remote terminal session, ' + e.toString()); this.httprequest.connectionPromise._rej('Failed to start remote terminal session, ' + ex.toString());
} }
} }
@ -2279,13 +2224,11 @@ function onTunnelData(data) {
} }
// Toast Notification, if required // Toast Notification, if required
if (this.ws.httprequest.consent && (this.ws.httprequest.consent & 2)) if (this.ws.httprequest.consent && (this.ws.httprequest.consent & 2)) {
{
// User Notifications is required // User Notifications is required
var notifyMessage = currentTranslation['terminalNotify'].replace('{0}', this.ws.httprequest.username); var notifyMessage = currentTranslation['terminalNotify'].replace('{0}', this.ws.httprequest.username);
var notifyTitle = "MeshCentral"; var notifyTitle = "MeshCentral";
if (this.ws.httprequest.soptions != null) if (this.ws.httprequest.soptions != null) {
{
if (this.ws.httprequest.soptions.notifyTitle != null) { notifyTitle = this.ws.httprequest.soptions.notifyTitle; } if (this.ws.httprequest.soptions.notifyTitle != null) { notifyTitle = this.ws.httprequest.soptions.notifyTitle; }
if (this.ws.httprequest.soptions.notifyMsgTerminal != null) { notifyMessage = this.ws.httprequest.soptions.notifyMsgTerminal.replace('{0}', this.ws.httprequest.realname).replace('{1}', this.ws.httprequest.username); } if (this.ws.httprequest.soptions.notifyMsgTerminal != null) { notifyMessage = this.ws.httprequest.soptions.notifyMsgTerminal.replace('{0}', this.ws.httprequest.realname).replace('{1}', this.ws.httprequest.username); }
} }
@ -2447,80 +2390,66 @@ function onTunnelData(data) {
} }
// Perform notification if needed. Toast messages may not be supported on all platforms. // Perform notification if needed. Toast messages may not be supported on all platforms.
if (this.httprequest.consent && (this.httprequest.consent & 8)) if (this.httprequest.consent && (this.httprequest.consent & 8)) {
{
// User Consent Prompt is required // User Consent Prompt is required
// Send a console message back using the console channel, "\n" is supported. // Send a console message back using the console channel, "\n" is supported.
this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 })); this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 }));
var consentMessage = currentTranslation['desktopConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); var consentMessage = currentTranslation['desktopConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username);
var consentTitle = 'MeshCentral'; var consentTitle = 'MeshCentral';
if (this.httprequest.soptions != null) if (this.httprequest.soptions != null) {
{
if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; } if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; }
if (this.httprequest.soptions.consentMsgDesktop != null) { consentMessage = this.httprequest.soptions.consentMsgDesktop.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } if (this.httprequest.soptions.consentMsgDesktop != null) { consentMessage = this.httprequest.soptions.consentMsgDesktop.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); }
} }
var pr; var pr;
if (process.platform == 'win32') if (process.platform == 'win32') {
{
var enhanced = false; var enhanced = false;
try try {
{
require('win-userconsent'); require('win-userconsent');
enhanced = true; enhanced = true;
} }
catch(z) catch (z) {
{
} }
if (enhanced) if (enhanced) {
{
var ipr = server_getUserImage(this.httprequest.userid); var ipr = server_getUserImage(this.httprequest.userid);
ipr.consentTitle = consentTitle; ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage; ipr.consentMessage = consentMessage;
ipr.tsid = tsid; ipr.tsid = tsid;
ipr.username = this.httprequest.realname; ipr.username = this.httprequest.realname;
ipr.translation = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage }; ipr.translation = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
pr = ipr.then(function (img) pr = ipr.then(function (img) {
{
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), uid: this.tsid, timeout: 30000, translations: this.translation }); this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), uid: this.tsid, timeout: 30000, translations: this.translation });
this.__childPromise.close = this.consent.close.bind(this.consent); this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent); return (this.consent);
}); });
} }
else else {
{
pr = require('message-box').create(consentTitle, consentMessage, 30, null, tsid); pr = require('message-box').create(consentTitle, consentMessage, 30, null, tsid);
} }
} }
else else {
{
pr = require('message-box').create(consentTitle, consentMessage, 30, null, tsid); pr = require('message-box').create(consentTitle, consentMessage, 30, null, tsid);
} }
pr.ws = this; pr.ws = this;
this.pause(); this.pause();
this._consentpromise = pr; this._consentpromise = pr;
this.prependOnceListener('end', function () this.prependOnceListener('end', function () {
{ if (this._consentpromise && this._consentpromise.close) {
if (this._consentpromise && this._consentpromise.close)
{
this._consentpromise.close(); this._consentpromise.close();
} }
}); });
pr.then( pr.then(
function (always) function (always) {
{
if (always) { server_set_consentTimer(this.ws.httprequest.userid); } if (always) { server_set_consentTimer(this.ws.httprequest.userid); }
// Success // Success
this.ws._consentpromise = null; this.ws._consentpromise = null;
MeshServerLogEx(30, null, "Starting remote desktop after local user accepted (" + this.ws.httprequest.remoteaddr + ")", this.ws.httprequest); MeshServerLogEx(30, null, "Starting remote desktop after local user accepted (" + this.ws.httprequest.remoteaddr + ")", this.ws.httprequest);
this.ws.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: null, msgid: 0 })); this.ws.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: null, msgid: 0 }));
if (this.ws.httprequest.consent && (this.ws.httprequest.consent & 1)) if (this.ws.httprequest.consent && (this.ws.httprequest.consent & 1)) {
{
// User Notifications is required // User Notifications is required
var notifyMessage = currentTranslation['desktopNotify'].replace('{0}', this.ws.httprequest.realname); var notifyMessage = currentTranslation['desktopNotify'].replace('{0}', this.ws.httprequest.realname);
var notifyTitle = "MeshCentral"; var notifyTitle = "MeshCentral";
if (this.ws.httprequest.soptions != null) if (this.ws.httprequest.soptions != null) {
{
if (this.ws.httprequest.soptions.notifyTitle != null) { notifyTitle = this.ws.httprequest.soptions.notifyTitle; } if (this.ws.httprequest.soptions.notifyTitle != null) { notifyTitle = this.ws.httprequest.soptions.notifyTitle; }
if (this.ws.httprequest.soptions.notifyMsgDesktop != null) { notifyMessage = this.ws.httprequest.soptions.notifyMsgDesktop.replace('{0}', this.ws.httprequest.realname).replace('{1}', this.ws.httprequest.username); } if (this.ws.httprequest.soptions.notifyMsgDesktop != null) { notifyMessage = this.ws.httprequest.soptions.notifyMsgDesktop.replace('{0}', this.ws.httprequest.realname).replace('{1}', this.ws.httprequest.username); }
} }
@ -2553,8 +2482,7 @@ function onTunnelData(data) {
} }
} }
this.ws.httprequest.desktop.kvm.pipe(this.ws, { dataTypeSkip: 1 }); this.ws.httprequest.desktop.kvm.pipe(this.ws, { dataTypeSkip: 1 });
if (this.ws.httprequest.autolock) if (this.ws.httprequest.autolock) {
{
destopLockHelper_pipe(this.ws.httprequest); destopLockHelper_pipe(this.ws.httprequest);
} }
this.ws.resume(); this.ws.resume();
@ -2605,8 +2533,7 @@ function onTunnelData(data) {
} }
} }
this.httprequest.desktop.kvm.pipe(this, { dataTypeSkip: 1 }); this.httprequest.desktop.kvm.pipe(this, { dataTypeSkip: 1 });
if (this.httprequest.autolock) if (this.httprequest.autolock) {
{
destopLockHelper_pipe(this.httprequest); destopLockHelper_pipe(this.httprequest);
} }
} }
@ -2650,52 +2577,43 @@ function onTunnelData(data) {
}; };
// Perform notification if needed. Toast messages may not be supported on all platforms. // Perform notification if needed. Toast messages may not be supported on all platforms.
if (this.httprequest.consent && (this.httprequest.consent & 32)) if (this.httprequest.consent && (this.httprequest.consent & 32)) {
{
// User Consent Prompt is required // User Consent Prompt is required
// Send a console message back using the console channel, "\n" is supported. // Send a console message back using the console channel, "\n" is supported.
this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 })); this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 }));
var consentMessage = currentTranslation['fileConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); var consentMessage = currentTranslation['fileConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username);
var consentTitle = 'MeshCentral'; var consentTitle = 'MeshCentral';
if (this.httprequest.soptions != null) if (this.httprequest.soptions != null) {
{
if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; } if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; }
if (this.httprequest.soptions.consentMsgFiles != null) { consentMessage = this.httprequest.soptions.consentMsgFiles.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } if (this.httprequest.soptions.consentMsgFiles != null) { consentMessage = this.httprequest.soptions.consentMsgFiles.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); }
} }
var pr; var pr;
if (process.platform == 'win32') if (process.platform == 'win32') {
{
var enhanced = false; var enhanced = false;
try try {
{
require('win-userconsent'); require('win-userconsent');
enhanced = true; enhanced = true;
} }
catch (z) catch (z) {
{
} }
if (enhanced) if (enhanced) {
{
var ipr = server_getUserImage(this.httprequest.userid); var ipr = server_getUserImage(this.httprequest.userid);
ipr.consentTitle = consentTitle; ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage; ipr.consentMessage = consentMessage;
ipr.username = this.httprequest.realname; ipr.username = this.httprequest.realname;
ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage }; ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
pr = ipr.then(function (img) pr = ipr.then(function (img) {
{
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), timeout: 30000, translations: this.translations }); this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), timeout: 30000, translations: this.translations });
this.__childPromise.close = this.consent.close.bind(this.consent); this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent); return (this.consent);
}); });
} }
else else {
{
pr = require('message-box').create(consentTitle, consentMessage, 30, null); pr = require('message-box').create(consentTitle, consentMessage, 30, null);
} }
} }
else else {
{
pr = require('message-box').create(consentTitle, consentMessage, 30, null); pr = require('message-box').create(consentTitle, consentMessage, 30, null);
} }
pr.ws = this; pr.ws = this;
@ -2703,8 +2621,7 @@ function onTunnelData(data) {
this._consentpromise = pr; this._consentpromise = pr;
this.prependOnceListener('end', function () { if (this._consentpromise && this._consentpromise.close) { this._consentpromise.close(); } }); this.prependOnceListener('end', function () { if (this._consentpromise && this._consentpromise.close) { this._consentpromise.close(); } });
pr.then( pr.then(
function (always) function (always) {
{
if (always) { server_set_consentTimer(this.ws.httprequest.userid); } if (always) { server_set_consentTimer(this.ws.httprequest.userid); }
// Success // Success
@ -2715,8 +2632,7 @@ function onTunnelData(data) {
// User Notifications is required // User Notifications is required
var notifyMessage = currentTranslation['fileNotify'].replace('{0}', this.ws.httprequest.realname); var notifyMessage = currentTranslation['fileNotify'].replace('{0}', this.ws.httprequest.realname);
var notifyTitle = "MeshCentral"; var notifyTitle = "MeshCentral";
if (this.ws.httprequest.soptions != null) if (this.ws.httprequest.soptions != null) {
{
if (this.ws.httprequest.soptions.notifyTitle != null) { notifyTitle = this.ws.httprequest.soptions.notifyTitle; } if (this.ws.httprequest.soptions.notifyTitle != null) { notifyTitle = this.ws.httprequest.soptions.notifyTitle; }
if (this.ws.httprequest.soptions.notifyMsgFiles != null) { notifyMessage = this.ws.httprequest.soptions.notifyMsgFiles.replace('{0}', this.ws.httprequest.realname).replace('{1}', this.ws.httprequest.username); } if (this.ws.httprequest.soptions.notifyMsgFiles != null) { notifyMessage = this.ws.httprequest.soptions.notifyMsgFiles.replace('{0}', this.ws.httprequest.realname).replace('{1}', this.ws.httprequest.username); }
} }
@ -2731,17 +2647,14 @@ function onTunnelData(data) {
this.ws.end(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: e.toString(), msgid: 2 })); this.ws.end(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: e.toString(), msgid: 2 }));
}); });
} }
else else {
{
// User Consent Prompt is not required // User Consent Prompt is not required
if (this.httprequest.consent && (this.httprequest.consent & 4)) if (this.httprequest.consent && (this.httprequest.consent & 4)) {
{
// User Notifications is required // User Notifications is required
MeshServerLogEx(42, null, "Started remote files with toast notification (" + this.httprequest.remoteaddr + ")", this.httprequest); MeshServerLogEx(42, null, "Started remote files with toast notification (" + this.httprequest.remoteaddr + ")", this.httprequest);
var notifyMessage = currentTranslation['fileNotify'].replace('{0}', this.ws.httprequest.realname); var notifyMessage = currentTranslation['fileNotify'].replace('{0}', this.ws.httprequest.realname);
var notifyTitle = "MeshCentral"; var notifyTitle = "MeshCentral";
if (this.httprequest.soptions != null) if (this.httprequest.soptions != null) {
{
if (this.httprequest.soptions.notifyTitle != null) { notifyTitle = this.httprequest.soptions.notifyTitle; } if (this.httprequest.soptions.notifyTitle != null) { notifyTitle = this.httprequest.soptions.notifyTitle; }
if (this.httprequest.soptions.notifyMsgFiles != null) { notifyMessage = this.httprequest.soptions.notifyMsgFiles.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } if (this.httprequest.soptions.notifyMsgFiles != null) { notifyMessage = this.httprequest.soptions.notifyMsgFiles.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); }
} }
@ -3083,16 +2996,13 @@ function onTunnelControlData(data, ws) {
} }
case 'autolock': { case 'autolock': {
// Set the session to auto lock on disconnect // Set the session to auto lock on disconnect
if (obj.value === true) if (obj.value === true) {
{
ws.httprequest.autolock = true; ws.httprequest.autolock = true;
if (ws.httprequest.unlockerHelper == null) if (ws.httprequest.unlockerHelper == null) {
{
destopLockHelper_pipe(ws.httprequest); destopLockHelper_pipe(ws.httprequest);
} }
} }
else else {
{
delete ws.httprequest.autolock; delete ws.httprequest.autolock;
} }
break; break;
@ -3107,11 +3017,9 @@ function onTunnelControlData(data, ws) {
if ((obj != null) && (typeof obj.consent == 'number')) { ws.httprequest.consent |= obj.consent; } if ((obj != null) && (typeof obj.consent == 'number')) { ws.httprequest.consent |= obj.consent; }
// Set autolock // Set autolock
if ((obj != null) && (obj.autolock === true)) if ((obj != null) && (obj.autolock === true)) {
{
ws.httprequest.autolock = true; ws.httprequest.autolock = true;
if (ws.httprequest.unlockerHelper == null) if (ws.httprequest.unlockerHelper == null) {
{
destopLockHelper_pipe(ws.httprequest); destopLockHelper_pipe(ws.httprequest);
} }
} }

View file

@ -1675,7 +1675,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
command.image = images[0].image; command.image = images[0].image;
} else { } else {
// Send back the default image if required // Send back the default image if required
if (command.default) { if ((command.default) || (command.sentDefault)) {
try { command.image = 'data:image/png;base64,' + Buffer.from(parent.fs.readFileSync(parent.parent.path.join(__dirname, 'public', 'images', 'user-128.png')), 'binary').toString('base64'); } catch (ex) { } try { command.image = 'data:image/png;base64,' + Buffer.from(parent.fs.readFileSync(parent.parent.path.join(__dirname, 'public', 'images', 'user-128.png')), 'binary').toString('base64'); } catch (ex) { }
} }
} }