From 9bb2b70341d3598b2d37a89b9182c8bee25e36c1 Mon Sep 17 00:00:00 2001 From: Ylian Saint-Hilaire Date: Sat, 16 Feb 2019 21:16:39 -0800 Subject: [PATCH] Database performance fix + Server side clipboard support. --- agents/meshcore.js | 25 ++- agents/meshcore.min.js | 2 +- agents/modules_meshcore/clipboard.js | 178 +++++++++++++++++++ agents/modules_meshcore_min/clipboard.min.js | 1 + db.js | 4 +- meshcentral.js | 28 ++- meshuser.js | 45 ++++- package.json | 2 +- views/default-min.handlebars | 2 +- views/default.handlebars | 34 +++- 10 files changed, 307 insertions(+), 14 deletions(-) create mode 100644 agents/modules_meshcore/clipboard.js create mode 100644 agents/modules_meshcore_min/clipboard.min.js diff --git a/agents/meshcore.js b/agents/meshcore.js index 7b228cc2..112055d8 100644 --- a/agents/meshcore.js +++ b/agents/meshcore.js @@ -466,6 +466,21 @@ function createMeshCore(agent) { if (data.url) { mesh.SendCommand({ "action": "msg", "type":"openUrl", "url": data.url, "sessionid": data.sessionid, "success": (openUserDesktopUrl(data.url) != null) }); } break; } + case 'getclip': { + // Send the load clipboard back to the user + sendConsoleText('getClip: ' + JSON.stringify(data)); + require("clipboard").read().then(function (str) { mesh.SendCommand({ "action": "msg", "type": "getclip", "sessionid": data.sessionid, "data": str }); }); + break; + } + case 'setclip': { + // Set the load clipboard to a user value + sendConsoleText('setClip: ' + JSON.stringify(data)); + if (typeof data.data == 'string') { + require("clipboard")(data.data); // Set the clipboard + mesh.SendCommand({ "action": "msg", "type": "setclip", "sessionid": data.sessionid, "success": true }); + } + break; + } default: // Unknown action, ignore it. break; @@ -1108,7 +1123,7 @@ function createMeshCore(agent) { var response = null; switch (cmd) { case 'help': { // Displays available commands - response = 'Available commands: help, info, osinfo,args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, sendcaps, openurl, amtreset, amtccm, amtdeactivate,\r\namtpolicy, getscript.'; + response = 'Available commands: help, info, osinfo,args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, sendcaps, openurl, amtreset, amtccm, amtdeactivate,\r\namtpolicy, getscript, getclip, setclip.'; break; } /* @@ -1130,6 +1145,14 @@ function createMeshCore(agent) { } break; */ + case 'getclip': { + require("clipboard").read().then(function (str) { sendConsoleText(str, sessionid); }); + break; + } + case 'setclip': { + if (args['_'].length != 1) { response = 'Proper usage: setclip (text)'; } else { require("clipboard")(args['_'][0]); response = 'Setting clipboard to: ' + args['_'][0]; } + break; + } case 'amtreset': { resetMei(); resetMicroLms(); diff --git a/agents/meshcore.min.js b/agents/meshcore.min.js index 3a22104c..bb4307ef 100644 --- a/agents/meshcore.min.js +++ b/agents/meshcore.min.js @@ -1 +1 @@ -process.on("uncaughtException",function(a){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException1: "+a})});var MESHRIGHT_EDITMESH=1;var MESHRIGHT_MANAGEUSERS=2;var MESHRIGHT_MANAGECOMPUTERS=4;var MESHRIGHT_REMOTECONTROL=8;var MESHRIGHT_AGENTCONSOLE=16;var MESHRIGHT_SERVERFILES=32;var MESHRIGHT_WAKEDEVICE=64;var MESHRIGHT_SETNOTES=128;var MESHRIGHT_REMOTEVIEW=256;function createMeshCore(agent){var obj={};var meshCoreObj={action:"coreinfo",value:"MeshCore v6",caps:14};try{require("os").name().then(function(v){meshCoreObj.osdesc=v})}catch(ex){}var meshServerConnectionState=0;var tunnels={};var lastMeInfo=null;var lastNetworkInfo=null;var lastPublicLocationInfo=null;var selfInfoUpdateTimer=null;var http=require("http");var net=require("net");var fs=require("fs");var rtc=require("ILibWebRTC");var processManager=require("process-manager");var amtMei=null,amtLms=null,amtLmsState=0;var amtMeiConnected=0,amtMeiTmpState=null;var wifiScannerLib=null;var wifiScanner=null;var networkMonitor=null;var amtscanner=null;var nextTunnelIndex=1;var oswsstack=null;var osamtstack=null;var amtPolicy=null;if(agent==null){db=require("SimpleDataStore").Shared();sha=require("SHA256Stream");mesh=require("MeshAgent");childProcess=require("child_process");if(mesh.hasKVM==1){try{if((process.platform=="win32")||(process.platform=="darwin")||(require("monitor-info").kvm_x11_support)){meshCoreObj.caps|=1}}catch(ex){}}}else{meshCoreObj.value+="-NodeJS";meshCoreObj.caps=8;mesh=agent.getMeshApi()}try{var AMTScannerModule=require("amt-scanner");amtscanner=new AMTScannerModule()}catch(ex){amtscanner=null}var SMBiosTables=null;var SMBiosTablesRaw=null;try{var SMBiosModule=null;try{SMBiosModule=require("smbios")}catch(ex){}if(SMBiosModule!=null){SMBiosModule.get(function(data){if(data!=null){SMBiosTablesRaw=data;SMBiosTables=require("smbios").parse(data);if(mesh.isControlChannelConnected){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}if(SMBiosTables.amtInfo&&(SMBiosTables.amtInfo.AMT==true)){resetMei()}}})}}catch(ex){sendConsoleText(ex)}try{var wifiScannerLib=require("wifi-scanner");wifiScanner=new wifiScannerLib();wifiScanner.on("accessPoint",function(data){sendConsoleText(data)})}catch(ex){wifiScannerLib=null;wifiScanner=null}try{amtPolicy=JSON.parse(db.Get("amtPolicy"))}catch(ex){amtPolicy=null}function resetMei(){try{var amtMeiLib=require("amt-mei");amtMei=new amtMeiLib();amtMei.on("error",function(e){amtMeiLib=null;amtMei=null;amtMeiConnected=-1;sendConsoleText("MEI Error.")});amtMeiConnected=2;sendPeriodicServerUpdate(1)}catch(ex){amtMeiLib=null;amtMei=null;amtMeiConnected=-1}}var getIpLocationDataExInProgress=false;var getIpLocationDataExCounts=[0,0];function getIpLocationDataEx(func){if(getIpLocationDataExInProgress==true){return false}try{getIpLocationDataExInProgress=true;getIpLocationDataExCounts[0]++;var options=http.parseUri("http://ipinfo.io/json");options.method="GET";http.request(options,function(resp){if(resp.statusCode==200){var geoData="";resp.data=function(geoipdata){geoData+=geoipdata};resp.end=function(){var location=null;try{if(typeof geoData=="string"){var result=JSON.parse(geoData);if(result.ip&&result.loc){location=result}}}catch(e){}if(func){getIpLocationDataExCounts[1]++;func(location)}}}else{func(null)}getIpLocationDataExInProgress=false}).end();return true}catch(e){return false}}function clearGatewayMac(str){if(str==null){return null}var x=JSON.parse(str);for(var i in x.netif){if(x.netif[i].gatewaymac){delete x.netif[i].gatewaymac}}return JSON.stringify(x)}function getIpLocationData(func){var publicLocationInfo=db.Get("publicLocationInfo");if(publicLocationInfo!=null){publicLocationInfo=JSON.parse(publicLocationInfo)}if(publicLocationInfo==null){getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(null)}}})}else{if(clearGatewayMac(publicLocationInfo.netInfoStr)==clearGatewayMac(lastNetworkInfo)){if(func){func(publicLocationInfo.locationData)}}else{getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(publicLocationInfo.locationData)}}})}}}if(!String.prototype.endsWith){String.prototype.endsWith=function(searchString,position){var subjectString=this.toString();if(typeof position!=="number"||!isFinite(position)||Math.floor(position)!==position||position>subjectString.length){position=subjectString.length}position-=searchString.length;var lastIndex=subjectString.lastIndexOf(searchString,position);return lastIndex!==-1&&lastIndex===position}}obj.path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};function toNumberIfNumber(x){if((typeof x=="string")&&(+parseInt(x)===x)){x=parseInt(x)}return x}function char2hex(i){return(i+256).toString(16).substr(-2).toUpperCase()}function rstr2hex(input){var r="",i;for(i=0;i8){return"[...]"}if(x==undefined){return"[undefined]"}if(typeof x=="string"){if(p==0){return x}return'"'+x+'"'}if(typeof x=="buffer"){return"[buffer]"}if(typeof x!="object"){return x}var r="{"+(ret?"\r\n":" ");for(var i in x){if(i!="_ObjectID"){r+=(addPad(p+2,pad)+i+": "+objToString(x[i],p+2,pad,ret)+(ret?"\r\n":" "))}}return r+addPad(p,pad)+"}"}function addPad(p,ret){var r="";for(var i=0;i2&&x[0]=="-"&&x[1]=="-"){if(current!=null){results[current]=true}current=x.substring(2)}else{if(current!=null){results[current]=toNumberIfNumber(x);current=null}else{results._.push(toNumberIfNumber(x))}}}if(current!=null){results[current]=true}return results}function getServerTargetUrl(path){var x=mesh.ServerUrl;if(x==null){return null}if(path==null){path=""}x=http.parseUri(x);if(x==null){return null}return x.protocol+"//"+x.host+":"+x.port+"/"+path}function getServerTargetUrlEx(url){if(url.substring(0,2)=="*/"){return getServerTargetUrl(url.substring(2))}return url}function sendWakeOnLan(hexMac){var count=0;try{var interfaces=require("os").networkInterfaces();var magic="FFFFFFFFFFFF";for(var x=1;x<=16;++x){magic+=hexMac}var magicbin=Buffer.from(magic,"hex");for(var adapter in interfaces){if(interfaces.hasOwnProperty(adapter)){for(var i=0;i0){sendNextBlock--;var buf=new Buffer(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}this.write(buf.slice(0,len+4))}break;case"upload":if(this.httprequest.uploadFile!=undefined){fs.closeSync(this.httprequest.uploadFile);this.httprequest.uploadFile=undefined}if(cmd.path==undefined){break}var filepath=cmd.name?obj.path.join(cmd.path,cmd.name):cmd.path;try{this.httprequest.uploadFile=fs.openSync(filepath,"wbN")}catch(e){this.write(new Buffer(JSON.stringify({action:"uploaderror",reqid:cmd.reqid})));break}this.httprequest.uploadFileid=cmd.reqid;if(this.httprequest.uploadFile){this.write(new Buffer(JSON.stringify({action:"uploadstart",reqid:this.httprequest.uploadFileid})))}break;case"copy":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:break}}}}}}}function onTunnelWebRTCControlData(data){if(typeof data!="string"){return}var obj;try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON on WebRTC: "+data);return}if(obj.type=="close"){try{this.close()}catch(e){}try{this.xrtc.close()}catch(e){}}}function onTunnelControlData(data,ws){var obj;if(ws==null){ws=this}if(typeof data=="string"){try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON: "+data);return}}else{if(typeof data=="object"){obj=data}else{return}}if(obj.action){switch(obj.action){case"lock":try{if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}}catch(e){}break;default:break}return}if(obj.type=="close"){try{ws.close()}catch(e){}}else{if(obj.type=="webrtc0"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.unpipe(ws)}else{ws.httprequest.process.stdout.unpipe(ws);ws.httprequest.process.stderr.unpipe(ws)}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.unpipe(ws)}else{ws.rtcchannel.httprequest=ws.httprequest;ws.rtcchannel.removeAllListeners("data");ws.rtcchannel.on("data",onTunnelData)}}ws.write('{"ctrlChannel":"102938","type":"webrtc1"}')}else{if(obj.type=="webrtc1"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.unpipe(ws.httprequest._term);ws.rtcchannel.pipe(ws.httprequest._term,{dataTypeSkip:1})}else{ws.unpipe(ws.httprequest.process.stdin);ws.rtcchannel.pipe(ws.httprequest.process.stdin,{dataTypeSkip:1})}ws.resume()}else{if(ws.httprequest.protocol==2){ws.unpipe(ws.httprequest.desktop.kvm);try{ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm,{dataTypeSkip:1,end:false})}catch(e){sendConsoleText("EX2")}ws.resume()}}ws.write('{"ctrlChannel":"102938","type":"webrtc2"}')}else{if(obj.type=="webrtc2"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}else{ws.httprequest.process.stdout.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false});ws.httprequest.process.stderr.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1})}}}else{if(obj.type=="offer"){if(ws.httprequest.protocol==1){return}ws.webrtc=rtc.createConnection();ws.webrtc.websocket=ws;ws.webrtc.on("connected",function(){});ws.webrtc.on("disconnected",function(){});ws.webrtc.on("dataChannel",function(rtcchannel){rtcchannel.xrtc=this;rtcchannel.websocket=this.websocket;this.rtcchannel=rtcchannel;this.websocket.rtcchannel=rtcchannel;this.websocket.rtcchannel.on("data",onTunnelWebRTCControlData);this.websocket.rtcchannel.on("end",function(){if(this.websocket.desktop&&this.websocket.desktop.kvm){this.unpipe(this.websocket.desktop.kvm);this.websocket.httprequest.desktop.kvm.unpipe(this)}});this.websocket.write('{"ctrlChannel":"102938","type":"webrtc0"}')});var sdp=null;try{sdp=ws.webrtc.setOffer(obj.sdp)}catch(ex){}if(sdp!=null){ws.write({type:"answer",ctrlChannel:"102938",sdp:sdp})}}}}}}}var consoleWebSockets={};var consoleHttpRequest=null;function consoleHttpResponse(response){response.data=function(data){sendConsoleText(rstr2hex(buf2rstr(data)),this.sessionid);consoleHttpRequest=null};response.close=function(){sendConsoleText("httprequest.response.close",this.sessionid);consoleHttpRequest=null}}function openUserDesktopUrl(url){var child=null;try{switch(process.platform){case"win32":child=require("child_process").execFile(process.env.windir+"\\system32\\cmd.exe",["/c","start",url],{type:childProcess.SpawnTypes.USER});break;case"linux":child=require("child_process").execFile("/usr/bin/xdg-open",["xdg-open",url],{uid:require("user-sessions").consoleUid()});break;case"darwin":child=require("child_process").execFile("/usr/bin/open",["open",url],{uid:require("user-sessions").consoleUid()});break;default:break}}catch(ex){}return child}function processConsoleCommand(cmd,args,rights,sessionid){try{var response=null;switch(cmd){case"help":response="Available commands: help, info, osinfo,args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, sendcaps, openurl, amtreset, amtccm, amtdeactivate,\r\namtpolicy, getscript.";break;case"amtreset":resetMei();resetMicroLms();response="Done.";break;case"amtccm":if(amtMei==null){response="Intel AMT not supported."}else{if(args._.length!=1){response="Proper usage: amtccm (adminPassword)"}else{activeToCCM(args._[0])}}break;case"amtdeactivate":if(amtMei==null){response="Intel AMT not supported."}else{deactivateCCM()}break;case"amtpolicy":if(amtPolicy==null){response="No Intel(R) AMT policy."}else{response=JSON.stringify(amtPolicy)}break;case"openurl":if(args._.length!=1){response="Proper usage: openurl (url)"}else{if(openUserDesktopUrl(args._[0])==null){response="Failed."}else{response="Success."}}break;case"users":if(meshCoreObj.users==null){response="Active users are unknown."}else{response="Active Users: "+meshCoreObj.users.join(", ")+"."}require("user-sessions").enumerateUsers().then(function(u){for(var i in u){sendConsoleText(u[i])}});break;case"toast":if(process.platform=="win32"){if(args._.length<1){response='Proper usage: toast "message"'}else{require("toaster").Toast("MeshCentral",args._[0]);response="ok"}}else{response="Only supported on Windows."}break;case"setdebug":if(args._.length<1){response="Proper usage: setdebug (target), 0 = Disabled, 1 = StdOut, 2 = This Console, * = All Consoles, 4 = WebLog, 8 = Logfile"}else{if(args._[0]=="*"){console.setDestination(2)}else{console.setDestination(parseInt(args._[0]),sessionid)}}break;case"ps":processManager.getProcesses(function(plist){var x="";for(var i in plist){x+=i+", "+plist[i].cmd+((plist[i].user)?(", "+plist[i].user):"")+"\r\n"}sendConsoleText(x,sessionid)});break;case"kill":if((args._.length<1)){response="Proper usage: kill [pid]"}else{process.kill(parseInt(args._[0]));response="Killed process "+args._[0]+"."}break;case"smbios":if(SMBiosTables==null){response="SMBios tables not available."}else{response=objToString(SMBiosTables,0," ",true)}break;case"rawsmbios":if(SMBiosTablesRaw==null){response="SMBios tables not available."}else{response="";for(var i in SMBiosTablesRaw){var header=false;for(var j in SMBiosTablesRaw[i]){if(SMBiosTablesRaw[i][j].length>0){if(header==false){response+=("Table type #"+i+((require("smbios").smTableTypes[i]==null)?"":(", "+require("smbios").smTableTypes[i])))+"\r\n";header=true}response+=(" "+SMBiosTablesRaw[i][j].toString("hex"))+"\r\n"}}}}break;case"eval":if(args._.length<1){response='Proper usage: eval "JavaScript code"'}else{response=JSON.stringify(mesh.eval(args._[0]))}break;case"notify":if(args._.length!=1){response='Proper usage: notify "message" [--session]'}else{var notification={action:"msg",type:"notify",value:args._[0],tag:"console"};if(args.session){notification.sessionid=sessionid}mesh.SendCommand(notification);response="ok"}break;case"info":response="Current Core: "+meshCoreObj.value+".\r\nAgent Time: "+Date()+".\r\nUser Rights: 0x"+rights.toString(16)+".\r\nPlatform: "+process.platform+".\r\nCapabilities: "+meshCoreObj.caps+".\r\nServer URL: "+mesh.ServerUrl+".";if(amtLmsState>=0){response+="\r\nBuilt-in LMS: "+["Disabled","Connecting..","Connected"][amtLmsState]+"."}if(meshCoreObj.osdesc){response+="\r\nOS: "+meshCoreObj.osdesc+"."}response+="\r\nModules: "+addedModules.join(", ")+".";response+="\r\nServer Connection: "+mesh.isControlChannelConnected+", State: "+meshServerConnectionState+".";response+="\rlastMeInfo: "+lastMeInfo+".";var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){response+="\r\nOldNodeID: "+oldNodeId+"."}if(process.platform!="win32"){response+="\r\nX11 support: "+require("monitor-info").kvm_x11_support+"."}break;case"osinfo":var i=1;if(args._.length>0){i=parseInt(args._[0]);if(i>8){i=8}response="Calling "+i+" times."}for(var j=0;j0){meshCoreObj.osdesc=args._[0];mesh.SendCommand(meshCoreObj);response=JSON.stringify(meshCoreObj)}else{response="Proper usage: sendosdesc [os description]"}break;case"args":response="args "+objToString(args,0," ",true);break;case"print":var r=[];for(var i in args._){r.push(args._[i])}console.log(r.join(" "));response="Message printed on agent console.";break;case"type":if(args._.length==0){response="Proper usage: type (filepath) [maxlength]"}else{var max=4096;if((args._.length>1)&&(typeof args._[1]=="number")){max=args._[1]}if(max>4096){max=4096}var buf=Buffer.alloc(max),fd=fs.openSync(args._[0],"r"),r=fs.readSync(fd,buf,0,max);response=buf.toString();var i=response.indexOf("\n");if((i>0)&&(response[i-1]!="\r")){response=response.split("\n").join("\r\n")}if(r==max){response+="..."}fs.closeSync(fd)}break;case"dbkeys":response=JSON.stringify(db.Keys);break;case"dbget":if(db==null){response="Database not accessible.";break}if(args._.length!=1){response="Proper usage: dbget (key)"}else{response=db.Get(args._[0])}break;case"dbset":if(db==null){response="Database not accessible.";break}if(args._.length!=2){response="Proper usage: dbset (key) (value)"}else{var r=db.Put(args._[0],args._[1]);response="Key set: "+r}break;case"dbcompact":if(db==null){response="Database not accessible.";break}var r=db.Compact();response="Database compacted: "+r;break;case"httpget":if(consoleHttpRequest!=null){response="HTTP operation already in progress."}else{if(args._.length!=1){response="Proper usage: httpget (url)"}else{var options=http.parseUri(args._[0]);options.method="GET";if(options==null){response="Invalid url."}else{try{consoleHttpRequest=http.request(options,consoleHttpResponse)}catch(e){response="Invalid HTTP GET request"}consoleHttpRequest.sessionid=sessionid;if(consoleHttpRequest!=null){consoleHttpRequest.end();response="HTTPGET "+options.protocol+"//"+options.host+":"+options.port+options.path}}}}break;case"wslist":response="";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}if(response==""){response="no websocket sessions."}break;case"wsconnect":if(args._.length==0){response="Proper usage: wsconnect (url)\r\nFor example: wsconnect wss://localhost:443/meshrelay.ashx?id=abc"}else{var httprequest=null;try{var options=http.parseUri(args._[0]);options.rejectUnauthorized=0;httprequest=http.request(options)}catch(e){response="Invalid HTTP websocket request"}if(httprequest!=null){httprequest.upgrade=onWebSocketUpgrade;httprequest.onerror=function(e){sendConsoleText("ERROR: "+JSON.stringify(e))};var index=1;while(consoleWebSockets[index]){index++}httprequest.sessionid=sessionid;httprequest.index=index;httprequest.url=args._[0];consoleWebSockets[index]=httprequest;response="New websocket session #"+index}}break;case"wssend":if(args._.length==0){response="Proper usage: wssend (socketnumber)\r\n";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){httprequest.s.write(args._[1]);response="ok"}else{response="Invalid web socket number"}}break;case"wsclose":if(args._.length==0){response="Proper usage: wsclose (socketnumber)"}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){if(httprequest.s!=null){httprequest.s.end()}else{httprequest.end()}response="ok"}else{response="Invalid web socket number"}}break;case"tunnels":response="";for(var i in tunnels){response+="Tunnel #"+i+", "+tunnels[i].url+"\r\n"}if(response==""){response="No websocket sessions."}break;case"ls":response="";var xpath="*";if(args._.length>0){xpath=obj.path.join(args._[0],"*")}response="List of "+xpath+"\r\n";var results=fs.readdirSync(xpath);for(var i=0;i0){var r="",pstates=["NotActivated","InActivation","Activated"];for(var i in data){var x=data[i];if(r!=""){r+="\r\n"}r+=x.address+" - Intel AMT v"+x.majorVersion+"."+x.minorVersion;if(x.provisioningState<3){r+=(", "+pstates[x.provisioningState])}if(x.provisioningState==2){r+=(", "+x.openPorts.join(", "))}r+="."}}else{r="No Intel AMT found."}sendConsoleText(r)})}}else{response="Intel AMT scanner module not present."}break;case"modules":response=JSON.stringify(addedModules);break;case"getscript":if(args._.length!=1){response="Proper usage: getscript [scriptNumber]."}else{mesh.SendCommand({action:"getScript",type:args._[0]})}break;default:response='Unknown command "'+cmd+'", type "help" for list of avaialble commands.';break}}catch(e){response="Command returned an exception error: "+e;console.log(e)}if(response!=null){sendConsoleText(response,sessionid)}}function sendConsoleText(text,sessionid){if(typeof text=="object"){text=JSON.stringify(text)}mesh.SendCommand({action:"msg",type:"console",value:text,sessionid:sessionid})}function handleServerConnection(state){meshServerConnectionState=state;if(meshServerConnectionState==0){if(selfInfoUpdateTimer!=null){clearInterval(selfInfoUpdateTimer);selfInfoUpdateTimer=null}lastSelfInfo=null}else{var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){mesh.SendCommand({action:"mc1migration",oldnodeid:oldNodeId})}mesh.SendCommand(meshCoreObj);if(SMBiosTablesRaw!=null){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}meInfoStr=null;sendPeriodicServerUpdate()}}var sendNetworkUpdateNagleTimer=null;function sendNetworkUpdateNagle(){if(sendNetworkUpdateNagleTimer!=null){clearTimeout(sendNetworkUpdateNagleTimer);sendNetworkUpdateNagleTimer=null}sendNetworkUpdateNagleTimer=setTimeout(sendNetworkUpdate,5000)}function sendNetworkUpdate(force){sendNetworkUpdateNagleTimer=null;var netInfo=mesh.NetInfo;netInfo.action="netinfo";var netInfoStr=JSON.stringify(netInfo);if((force==true)||(clearGatewayMac(netInfoStr)!=clearGatewayMac(lastNetworkInfo))){mesh.SendCommand(netInfo);lastNetworkInfo=netInfoStr}}function sendPeriodicServerUpdate(flags){if(meshServerConnectionState==0){return}if(!flags){flags=4294967295}if(flags&1){getAmtInfo(function(meinfo){try{if(meinfo==null){return}var intelamt={},p=false;if(meinfo.Versions&&meinfo.Versions.AMT){intelamt.ver=meinfo.Versions.AMT;p=true}if(meinfo.ProvisioningState){intelamt.state=meinfo.ProvisioningState;p=true}if(meinfo.Flags){intelamt.flags=meinfo.Flags;p=true}if(meinfo.OsHostname){intelamt.host=meinfo.OsHostname;p=true}if(meinfo.UUID){intelamt.uuid=meinfo.UUID;p=true}if(p==true){var meInfoStr=JSON.stringify(intelamt);if(meInfoStr!=lastMeInfo){meshCoreObj.intelamt=intelamt;mesh.SendCommand(meshCoreObj);lastMeInfo=meInfoStr}}}catch(ex){}})}if(flags&2){sendNetworkUpdateNagle(false)}}function getAmtInfo(func){if(amtMei==null||amtMeiConnected!=2){if(func!=null){func(null)}return}try{amtMeiTmpState={Flags:0};amtMei.getProtocolVersion(function(result){if(result!=null){amtMeiTmpState.MeiVersion=result}});amtMei.getVersion(function(result){if(result){amtMeiTmpState.Versions={};for(var version in result.Versions){amtMeiTmpState.Versions[result.Versions[version].Description]=result.Versions[version].Version}}});amtMei.getProvisioningMode(function(result){if(result){amtMeiTmpState.ProvisioningMode=result.mode}});amtMei.getProvisioningState(function(result){if(result){amtMeiTmpState.ProvisioningState=result.state}});amtMei.getEHBCState(function(result){if((result!=null)&&(result.EHBC==true)){amtMeiTmpState.Flags+=1}});amtMei.getControlMode(function(result){if(result!=null){if(result.controlMode==1){amtMeiTmpState.Flags+=2}if(result.controlMode==2){amtMeiTmpState.Flags+=4}}});amtMei.getLanInterfaceSettings(0,function(result){if(result){amtMeiTmpState.net0=result}});amtMei.getLanInterfaceSettings(1,function(result){if(result){amtMeiTmpState.net1=result}});amtMei.getUuid(function(result){if((result!=null)&&(result.uuid!=null)){amtMeiTmpState.UUID=result.uuid}});amtMei.getDnsSuffix(function(result){if(result!=null){amtMeiTmpState.dns=result}if(func!=null){func(amtMeiTmpState)}})}catch(e){if(func!=null){func(null)}return}}function handleAmtNotification(notifyMsg){if((notifyMsg==null)||(notifyMsg.Body==null)||(notifyMsg.Body.MessageID==null)||(notifyMsg.Body.MessageArguments==null)){return null}var amtMessage=notifyMsg.Body.MessageID,amtMessageArg=notifyMsg.Body.MessageArguments[0],notify=null;switch(amtMessage){case"iAMT0050":if(amtMessageArg=="48"){notify="Intel® AMT Serial-over-LAN connected"}else{if(amtMessageArg=="49"){notify="Intel® AMT Serial-over-LAN disconnected"}}break;case"iAMT0052":if(amtMessageArg=="1"){notify="Intel® AMT KVM connected"}else{if(amtMessageArg=="2"){notify="Intel® AMT KVM disconnected"}}break;default:break}if(notify!=null){mesh.SendCommand({action:"msg",type:"notify",value:notify,tag:"general"})}}function resetMicroLms(){try{var lme_heci=require("amt-lme");amtLmsState=1;amtLms=new lme_heci();amtLms.on("error",function(e){amtLmsState=0;amtLms=null;sendConsoleText("LMS Error.");obj.setupMeiOsAdmin(null,1)});amtLms.on("connect",function(){amtLmsState=2;obj.setupMeiOsAdmin(null,2)});amtLms.on("notify",function(data,options,str,code){if(code=="iAMT0052-3"){obj.kvmGetData()}else{handleAmtNotification(data)}})}catch(e){amtLmsState=-1;amtLms=null}}obj.start=function(){mesh.AddCommandHandler(handleServerCommand);mesh.AddConnectHandler(handleServerConnection);resetMicroLms();try{var userSession=require("user-sessions");userSession.on("changed",function onUserSessionChanged(){userSession.enumerateUsers().then(function(users){var u=[],a=users.Active;for(var i=0;i=12)){obj.kvmGetData("skip");obj.kvmTempTimer=setInterval(function(){obj.kvmGetData()},2000);obj.kvmSetData(JSON.stringify({action:"restart",ver:1}))}})})};obj.kvmGetData=function(tag){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(obj.kvmDataGetResponse,tag)};obj.kvmDataGetResponse=function(stack,name,response,status,tag){if((tag!="skip")&&(status==200)&&(response.Body.ReturnValue==0)){var val=null;try{val=Buffer.from(response.Body.DataMessage,"base64").toString()}catch(e){return}if(val!=null){obj.kvmProcessData(response.Body.RealmsBitmap,response.Body.MessageId,val)}}};var webRtcDesktop=null;obj.kvmProcessData=function(realms,messageId,val){var data=null;try{data=JSON.parse(val)}catch(e){}if((data!=null)&&(data.action)){if(data.action=="present"){obj.kvmSetData(JSON.stringify({action:"present",ver:1,platform:process.platform}))}if(data.action=="offer"){webRtcDesktop={};var rtc=require("ILibWebRTC");webRtcDesktop.webrtc=rtc.createConnection();webRtcDesktop.webrtc.on("connected",function(){});webRtcDesktop.webrtc.on("disconnected",function(){obj.webRtcCleanUp()});webRtcDesktop.webrtc.on("dataChannel",function(rtcchannel){webRtcDesktop.rtcchannel=rtcchannel;webRtcDesktop.kvm=mesh.getRemoteDesktopStream();webRtcDesktop.kvm.pipe(webRtcDesktop.rtcchannel,{dataTypeSkip:1,end:false});webRtcDesktop.rtcchannel.on("end",function(){obj.webRtcCleanUp()});webRtcDesktop.rtcchannel.on("data",function(x){obj.kvmCtrlData(this,x)});webRtcDesktop.rtcchannel.pipe(webRtcDesktop.kvm,{dataTypeSkip:1,end:false})});obj.kvmSetData(JSON.stringify({action:"answer",ver:1,sdp:webRtcDesktop.webrtc.setOffer(data.sdp)}))}}};var path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};obj.kvmCtrlData=function(channel,cmd){if(cmd.length>0&&cmd.charCodeAt(0)!=123){if(this.fileupload!=null){cmd=Buffer.from(cmd,"base64");var header=cmd.readUInt32BE(0);if((header==16777216)||(header==16777217)){fs.writeSync(this.fileupload.fp,cmd.slice(4));channel.write({action:"upload",sub:"ack",reqid:this.fileupload.reqid});if(header==16777217){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}return}try{cmd=JSON.parse(cmd)}catch(ex){console.error("Invalid JSON: "+cmd);return}if((cmd.path!=null)&&(process.platform!="win32")&&(cmd.path[0]!="/")){cmd.path="/"+cmd.path}switch(cmd.action){case"ping":channel.write({action:"pong"});break;case"lock":if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}break;case"ls":var response=getDirectoryInfo(cmd.path);if(cmd.reqid!=undefined){response.reqid=cmd.reqid}channel.write(response);break;case"mkdir":fs.mkdirSync(cmd.path);break;case"rm":for(var i in cmd.delfiles){var fullpath=path.join(cmd.path,cmd.delfiles[i]);try{fs.unlinkSync(fullpath)}catch(e){console.log(e)}}break;case"rename":try{fs.renameSync(path.join(cmd.path,cmd.oldname),path.join(cmd.path,cmd.newname))}catch(e){console.log(e)}break;case"download":var sendNextBlock=0;if(cmd.sub=="start"){if(this.filedownload!=null){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}this.filedownload={id:cmd.id,path:cmd.path,ptr:0};try{this.filedownload.f=fs.openSync(this.filedownload.path,"rbN")}catch(e){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}if(this.filedownload){channel.write({action:"download",sub:"start",id:cmd.id})}}else{if((this.filedownload!=null)&&(cmd.id==this.filedownload.id)){if(cmd.sub=="startack"){sendNextBlock=8}else{if(cmd.sub=="stop"){delete this.filedownload}else{if(cmd.sub=="ack"){sendNextBlock=1}}}}}while(sendNextBlock>0){sendNextBlock--;var buf=Buffer.alloc(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}channel.write(buf.slice(0,len+4).toString("base64"))}break;case"upload":if(cmd.sub=="start"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp)}if(!cmd.path||!cmd.name){break}this.fileupload={reqid:cmd.reqid};var filepath=path.join(cmd.path,cmd.name);try{this.fileupload.fp=fs.openSync(filepath,"wbN")}catch(e){}if(this.fileupload.fp){channel.write({action:"upload",sub:"start",reqid:this.fileupload.reqid})}else{this.fileupload=null;channel.write({action:"upload",sub:"error",reqid:this.fileupload.reqid})}}else{if(cmd.sub=="cancel"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}break;case"copy":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:console.log("Invalid KVM command",cmd);sendConsoleText("Invalid KVM command: "+cmd);break}};obj.webRtcCleanUp=function(){sendConsoleText("webRtcCleanUp");if(webRtcDesktop==null){return}if(webRtcDesktop.rtcchannel){try{webRtcDesktop.rtcchannel.close()}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("data")}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("end")}catch(e){}delete webRtcDesktop.rtcchannel}if(webRtcDesktop.webrtc){try{webRtcDesktop.webrtc.close()}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("connected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("disconnected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("dataChannel")}catch(e){}delete webRtcDesktop.webrtc}if(webRtcDesktop.kvm){try{webRtcDesktop.kvm.end()}catch(e){}delete webRtcDesktop.kvm}webRtcDesktop=null};obj.kvmSetData=function(x){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString("base64"),function(){})};function deleteFolderRecursive(path,rec){if(fs.existsSync(path)){if(rec==true){fs.readdirSync(obj.path.join(path,"*")).forEach(function(file,index){var curPath=obj.path.join(path,file);if(fs.statSync(curPath).isDirectory()){deleteFolderRecursive(curPath,true)}else{fs.unlinkSync(curPath)}})}fs.unlinkSync(path)}}function deactivateCCM(){amtMei.unprovision(1,function(status){if(status==0){sendConsoleText("Success deactivating Intel AMT CCM.")}else{sendConsoleText("Intel AMT CCM deactivation error: "+status)}})}function activeToCCM(adminpass){sendConsoleText("Trying to get local account info...");amtMei.getLocalSystemAccount(function(x){if(x.user&&x.pass){sendConsoleText("Intel AMT local account info: User="+x.user+", Pass="+x.pass+".");var transport=require("amt-wsman-duk");var wsman=require("amt-wsman");var amt=require("amt");oswsstack=new wsman(transport,"127.0.0.1",16992,x.user,x.pass,false);osamtstack=new amt(oswsstack);sendConsoleText("Trying to get Intel AMT activation information...");osamtstack.BatchEnum(null,["*AMT_GeneralSettings","*IPS_HostBasedSetupService"],activeToCCMEx2,adminpass)}else{sendConsoleText("Unable to get $$OsAdmin password.")}})}function activeToCCMEx2(stack,name,responses,status,adminpass){if(status!=200){sendConsoleText("Failed to fetch activation information, status "+status)}else{if(responses.IPS_HostBasedSetupService.response.AllowedControlModes.length!=2){sendConsoleText("Client control mode activation not allowed")}else{stack.IPS_HostBasedSetupService_Setup(2,md5hex("admin:"+responses.AMT_GeneralSettings.response.DigestRealm+":"+adminpass).substring(0,32),null,null,null,null,activeToCCMEx3)}}}function activeToCCMEx3(stack,name,responses,status){if(status!=200){sendConsoleText("Failed to activate, status "+status)}else{if(responses.Body.ReturnValue!=0){sendConsoleText("Client control mode activation failed: "+responses.Body.ReturnValueStr)}else{sendConsoleText("Intel AMT CCM activation success")}}}function md5hex(str){return require("MD5Stream").create().syncHash(str).toString("hex")}return obj}try{var xexports=null,mainMeshCore=null;try{xexports=module.exports}catch(e){}if(xexports!=null){module.exports.createMeshCore=createMeshCore}else{mainMeshCore=createMeshCore();mainMeshCore.start(null)}}catch(ex){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException2: "+ex})}; \ No newline at end of file +process.on("uncaughtException",function(a){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException1: "+a})});var MESHRIGHT_EDITMESH=1;var MESHRIGHT_MANAGEUSERS=2;var MESHRIGHT_MANAGECOMPUTERS=4;var MESHRIGHT_REMOTECONTROL=8;var MESHRIGHT_AGENTCONSOLE=16;var MESHRIGHT_SERVERFILES=32;var MESHRIGHT_WAKEDEVICE=64;var MESHRIGHT_SETNOTES=128;var MESHRIGHT_REMOTEVIEW=256;function createMeshCore(agent){var obj={};var meshCoreObj={action:"coreinfo",value:"MeshCore v6",caps:14};try{require("os").name().then(function(v){meshCoreObj.osdesc=v})}catch(ex){}var meshServerConnectionState=0;var tunnels={};var lastMeInfo=null;var lastNetworkInfo=null;var lastPublicLocationInfo=null;var selfInfoUpdateTimer=null;var http=require("http");var net=require("net");var fs=require("fs");var rtc=require("ILibWebRTC");var processManager=require("process-manager");var amtMei=null,amtLms=null,amtLmsState=0;var amtMeiConnected=0,amtMeiTmpState=null;var wifiScannerLib=null;var wifiScanner=null;var networkMonitor=null;var amtscanner=null;var nextTunnelIndex=1;var oswsstack=null;var osamtstack=null;var amtPolicy=null;if(agent==null){db=require("SimpleDataStore").Shared();sha=require("SHA256Stream");mesh=require("MeshAgent");childProcess=require("child_process");if(mesh.hasKVM==1){try{if((process.platform=="win32")||(process.platform=="darwin")||(require("monitor-info").kvm_x11_support)){meshCoreObj.caps|=1}}catch(ex){}}}else{meshCoreObj.value+="-NodeJS";meshCoreObj.caps=8;mesh=agent.getMeshApi()}try{var AMTScannerModule=require("amt-scanner");amtscanner=new AMTScannerModule()}catch(ex){amtscanner=null}var SMBiosTables=null;var SMBiosTablesRaw=null;try{var SMBiosModule=null;try{SMBiosModule=require("smbios")}catch(ex){}if(SMBiosModule!=null){SMBiosModule.get(function(data){if(data!=null){SMBiosTablesRaw=data;SMBiosTables=require("smbios").parse(data);if(mesh.isControlChannelConnected){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}if(SMBiosTables.amtInfo&&(SMBiosTables.amtInfo.AMT==true)){resetMei()}}})}}catch(ex){sendConsoleText(ex)}try{var wifiScannerLib=require("wifi-scanner");wifiScanner=new wifiScannerLib();wifiScanner.on("accessPoint",function(data){sendConsoleText(data)})}catch(ex){wifiScannerLib=null;wifiScanner=null}try{amtPolicy=JSON.parse(db.Get("amtPolicy"))}catch(ex){amtPolicy=null}function resetMei(){try{var amtMeiLib=require("amt-mei");amtMei=new amtMeiLib();amtMei.on("error",function(e){amtMeiLib=null;amtMei=null;amtMeiConnected=-1;sendConsoleText("MEI Error.")});amtMeiConnected=2;sendPeriodicServerUpdate(1)}catch(ex){amtMeiLib=null;amtMei=null;amtMeiConnected=-1}}var getIpLocationDataExInProgress=false;var getIpLocationDataExCounts=[0,0];function getIpLocationDataEx(func){if(getIpLocationDataExInProgress==true){return false}try{getIpLocationDataExInProgress=true;getIpLocationDataExCounts[0]++;var options=http.parseUri("http://ipinfo.io/json");options.method="GET";http.request(options,function(resp){if(resp.statusCode==200){var geoData="";resp.data=function(geoipdata){geoData+=geoipdata};resp.end=function(){var location=null;try{if(typeof geoData=="string"){var result=JSON.parse(geoData);if(result.ip&&result.loc){location=result}}}catch(e){}if(func){getIpLocationDataExCounts[1]++;func(location)}}}else{func(null)}getIpLocationDataExInProgress=false}).end();return true}catch(e){return false}}function clearGatewayMac(str){if(str==null){return null}var x=JSON.parse(str);for(var i in x.netif){if(x.netif[i].gatewaymac){delete x.netif[i].gatewaymac}}return JSON.stringify(x)}function getIpLocationData(func){var publicLocationInfo=db.Get("publicLocationInfo");if(publicLocationInfo!=null){publicLocationInfo=JSON.parse(publicLocationInfo)}if(publicLocationInfo==null){getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(null)}}})}else{if(clearGatewayMac(publicLocationInfo.netInfoStr)==clearGatewayMac(lastNetworkInfo)){if(func){func(publicLocationInfo.locationData)}}else{getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(publicLocationInfo.locationData)}}})}}}if(!String.prototype.endsWith){String.prototype.endsWith=function(searchString,position){var subjectString=this.toString();if(typeof position!=="number"||!isFinite(position)||Math.floor(position)!==position||position>subjectString.length){position=subjectString.length}position-=searchString.length;var lastIndex=subjectString.lastIndexOf(searchString,position);return lastIndex!==-1&&lastIndex===position}}obj.path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};function toNumberIfNumber(x){if((typeof x=="string")&&(+parseInt(x)===x)){x=parseInt(x)}return x}function char2hex(i){return(i+256).toString(16).substr(-2).toUpperCase()}function rstr2hex(input){var r="",i;for(i=0;i8){return"[...]"}if(x==undefined){return"[undefined]"}if(typeof x=="string"){if(p==0){return x}return'"'+x+'"'}if(typeof x=="buffer"){return"[buffer]"}if(typeof x!="object"){return x}var r="{"+(ret?"\r\n":" ");for(var i in x){if(i!="_ObjectID"){r+=(addPad(p+2,pad)+i+": "+objToString(x[i],p+2,pad,ret)+(ret?"\r\n":" "))}}return r+addPad(p,pad)+"}"}function addPad(p,ret){var r="";for(var i=0;i2&&x[0]=="-"&&x[1]=="-"){if(current!=null){results[current]=true}current=x.substring(2)}else{if(current!=null){results[current]=toNumberIfNumber(x);current=null}else{results._.push(toNumberIfNumber(x))}}}if(current!=null){results[current]=true}return results}function getServerTargetUrl(path){var x=mesh.ServerUrl;if(x==null){return null}if(path==null){path=""}x=http.parseUri(x);if(x==null){return null}return x.protocol+"//"+x.host+":"+x.port+"/"+path}function getServerTargetUrlEx(url){if(url.substring(0,2)=="*/"){return getServerTargetUrl(url.substring(2))}return url}function sendWakeOnLan(hexMac){var count=0;try{var interfaces=require("os").networkInterfaces();var magic="FFFFFFFFFFFF";for(var x=1;x<=16;++x){magic+=hexMac}var magicbin=Buffer.from(magic,"hex");for(var adapter in interfaces){if(interfaces.hasOwnProperty(adapter)){for(var i=0;i0){sendNextBlock--;var buf=new Buffer(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}this.write(buf.slice(0,len+4))}break;case"upload":if(this.httprequest.uploadFile!=undefined){fs.closeSync(this.httprequest.uploadFile);this.httprequest.uploadFile=undefined}if(cmd.path==undefined){break}var filepath=cmd.name?obj.path.join(cmd.path,cmd.name):cmd.path;try{this.httprequest.uploadFile=fs.openSync(filepath,"wbN")}catch(e){this.write(new Buffer(JSON.stringify({action:"uploaderror",reqid:cmd.reqid})));break}this.httprequest.uploadFileid=cmd.reqid;if(this.httprequest.uploadFile){this.write(new Buffer(JSON.stringify({action:"uploadstart",reqid:this.httprequest.uploadFileid})))}break;case"copy":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:break}}}}}}}function onTunnelWebRTCControlData(data){if(typeof data!="string"){return}var obj;try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON on WebRTC: "+data);return}if(obj.type=="close"){try{this.close()}catch(e){}try{this.xrtc.close()}catch(e){}}}function onTunnelControlData(data,ws){var obj;if(ws==null){ws=this}if(typeof data=="string"){try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON: "+data);return}}else{if(typeof data=="object"){obj=data}else{return}}if(obj.action){switch(obj.action){case"lock":try{if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}}catch(e){}break;default:break}return}if(obj.type=="close"){try{ws.close()}catch(e){}}else{if(obj.type=="webrtc0"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.unpipe(ws)}else{ws.httprequest.process.stdout.unpipe(ws);ws.httprequest.process.stderr.unpipe(ws)}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.unpipe(ws)}else{ws.rtcchannel.httprequest=ws.httprequest;ws.rtcchannel.removeAllListeners("data");ws.rtcchannel.on("data",onTunnelData)}}ws.write('{"ctrlChannel":"102938","type":"webrtc1"}')}else{if(obj.type=="webrtc1"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.unpipe(ws.httprequest._term);ws.rtcchannel.pipe(ws.httprequest._term,{dataTypeSkip:1})}else{ws.unpipe(ws.httprequest.process.stdin);ws.rtcchannel.pipe(ws.httprequest.process.stdin,{dataTypeSkip:1})}ws.resume()}else{if(ws.httprequest.protocol==2){ws.unpipe(ws.httprequest.desktop.kvm);try{ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm,{dataTypeSkip:1,end:false})}catch(e){sendConsoleText("EX2")}ws.resume()}}ws.write('{"ctrlChannel":"102938","type":"webrtc2"}')}else{if(obj.type=="webrtc2"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}else{ws.httprequest.process.stdout.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false});ws.httprequest.process.stderr.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1})}}}else{if(obj.type=="offer"){if(ws.httprequest.protocol==1){return}ws.webrtc=rtc.createConnection();ws.webrtc.websocket=ws;ws.webrtc.on("connected",function(){});ws.webrtc.on("disconnected",function(){});ws.webrtc.on("dataChannel",function(rtcchannel){rtcchannel.xrtc=this;rtcchannel.websocket=this.websocket;this.rtcchannel=rtcchannel;this.websocket.rtcchannel=rtcchannel;this.websocket.rtcchannel.on("data",onTunnelWebRTCControlData);this.websocket.rtcchannel.on("end",function(){if(this.websocket.desktop&&this.websocket.desktop.kvm){this.unpipe(this.websocket.desktop.kvm);this.websocket.httprequest.desktop.kvm.unpipe(this)}});this.websocket.write('{"ctrlChannel":"102938","type":"webrtc0"}')});var sdp=null;try{sdp=ws.webrtc.setOffer(obj.sdp)}catch(ex){}if(sdp!=null){ws.write({type:"answer",ctrlChannel:"102938",sdp:sdp})}}}}}}}var consoleWebSockets={};var consoleHttpRequest=null;function consoleHttpResponse(response){response.data=function(data){sendConsoleText(rstr2hex(buf2rstr(data)),this.sessionid);consoleHttpRequest=null};response.close=function(){sendConsoleText("httprequest.response.close",this.sessionid);consoleHttpRequest=null}}function openUserDesktopUrl(url){var child=null;try{switch(process.platform){case"win32":child=require("child_process").execFile(process.env.windir+"\\system32\\cmd.exe",["/c","start",url],{type:childProcess.SpawnTypes.USER});break;case"linux":child=require("child_process").execFile("/usr/bin/xdg-open",["xdg-open",url],{uid:require("user-sessions").consoleUid()});break;case"darwin":child=require("child_process").execFile("/usr/bin/open",["open",url],{uid:require("user-sessions").consoleUid()});break;default:break}}catch(ex){}return child}function processConsoleCommand(cmd,args,rights,sessionid){try{var response=null;switch(cmd){case"help":response="Available commands: help, info, osinfo,args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, sendcaps, openurl, amtreset, amtccm, amtdeactivate,\r\namtpolicy, getscript, getclip, setclip.";break;case"getclip":require("clipboard").read().then(function(str){sendConsoleText(str,sessionid)});break;case"setclip":if(args._.length!=1){response="Proper usage: setclip (text)"}else{require("clipboard")(args._[0]);response="Setting clipboard to: "+args._[0]}break;case"amtreset":resetMei();resetMicroLms();response="Done.";break;case"amtccm":if(amtMei==null){response="Intel AMT not supported."}else{if(args._.length!=1){response="Proper usage: amtccm (adminPassword)"}else{activeToCCM(args._[0])}}break;case"amtdeactivate":if(amtMei==null){response="Intel AMT not supported."}else{deactivateCCM()}break;case"amtpolicy":if(amtPolicy==null){response="No Intel(R) AMT policy."}else{response=JSON.stringify(amtPolicy)}break;case"openurl":if(args._.length!=1){response="Proper usage: openurl (url)"}else{if(openUserDesktopUrl(args._[0])==null){response="Failed."}else{response="Success."}}break;case"users":if(meshCoreObj.users==null){response="Active users are unknown."}else{response="Active Users: "+meshCoreObj.users.join(", ")+"."}require("user-sessions").enumerateUsers().then(function(u){for(var i in u){sendConsoleText(u[i])}});break;case"toast":if(process.platform=="win32"){if(args._.length<1){response='Proper usage: toast "message"'}else{require("toaster").Toast("MeshCentral",args._[0]);response="ok"}}else{response="Only supported on Windows."}break;case"setdebug":if(args._.length<1){response="Proper usage: setdebug (target), 0 = Disabled, 1 = StdOut, 2 = This Console, * = All Consoles, 4 = WebLog, 8 = Logfile"}else{if(args._[0]=="*"){console.setDestination(2)}else{console.setDestination(parseInt(args._[0]),sessionid)}}break;case"ps":processManager.getProcesses(function(plist){var x="";for(var i in plist){x+=i+", "+plist[i].cmd+((plist[i].user)?(", "+plist[i].user):"")+"\r\n"}sendConsoleText(x,sessionid)});break;case"kill":if((args._.length<1)){response="Proper usage: kill [pid]"}else{process.kill(parseInt(args._[0]));response="Killed process "+args._[0]+"."}break;case"smbios":if(SMBiosTables==null){response="SMBios tables not available."}else{response=objToString(SMBiosTables,0," ",true)}break;case"rawsmbios":if(SMBiosTablesRaw==null){response="SMBios tables not available."}else{response="";for(var i in SMBiosTablesRaw){var header=false;for(var j in SMBiosTablesRaw[i]){if(SMBiosTablesRaw[i][j].length>0){if(header==false){response+=("Table type #"+i+((require("smbios").smTableTypes[i]==null)?"":(", "+require("smbios").smTableTypes[i])))+"\r\n";header=true}response+=(" "+SMBiosTablesRaw[i][j].toString("hex"))+"\r\n"}}}}break;case"eval":if(args._.length<1){response='Proper usage: eval "JavaScript code"'}else{response=JSON.stringify(mesh.eval(args._[0]))}break;case"notify":if(args._.length!=1){response='Proper usage: notify "message" [--session]'}else{var notification={action:"msg",type:"notify",value:args._[0],tag:"console"};if(args.session){notification.sessionid=sessionid}mesh.SendCommand(notification);response="ok"}break;case"info":response="Current Core: "+meshCoreObj.value+".\r\nAgent Time: "+Date()+".\r\nUser Rights: 0x"+rights.toString(16)+".\r\nPlatform: "+process.platform+".\r\nCapabilities: "+meshCoreObj.caps+".\r\nServer URL: "+mesh.ServerUrl+".";if(amtLmsState>=0){response+="\r\nBuilt-in LMS: "+["Disabled","Connecting..","Connected"][amtLmsState]+"."}if(meshCoreObj.osdesc){response+="\r\nOS: "+meshCoreObj.osdesc+"."}response+="\r\nModules: "+addedModules.join(", ")+".";response+="\r\nServer Connection: "+mesh.isControlChannelConnected+", State: "+meshServerConnectionState+".";response+="\rlastMeInfo: "+lastMeInfo+".";var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){response+="\r\nOldNodeID: "+oldNodeId+"."}if(process.platform!="win32"){response+="\r\nX11 support: "+require("monitor-info").kvm_x11_support+"."}break;case"osinfo":var i=1;if(args._.length>0){i=parseInt(args._[0]);if(i>8){i=8}response="Calling "+i+" times."}for(var j=0;j0){meshCoreObj.osdesc=args._[0];mesh.SendCommand(meshCoreObj);response=JSON.stringify(meshCoreObj)}else{response="Proper usage: sendosdesc [os description]"}break;case"args":response="args "+objToString(args,0," ",true);break;case"print":var r=[];for(var i in args._){r.push(args._[i])}console.log(r.join(" "));response="Message printed on agent console.";break;case"type":if(args._.length==0){response="Proper usage: type (filepath) [maxlength]"}else{var max=4096;if((args._.length>1)&&(typeof args._[1]=="number")){max=args._[1]}if(max>4096){max=4096}var buf=Buffer.alloc(max),fd=fs.openSync(args._[0],"r"),r=fs.readSync(fd,buf,0,max);response=buf.toString();var i=response.indexOf("\n");if((i>0)&&(response[i-1]!="\r")){response=response.split("\n").join("\r\n")}if(r==max){response+="..."}fs.closeSync(fd)}break;case"dbkeys":response=JSON.stringify(db.Keys);break;case"dbget":if(db==null){response="Database not accessible.";break}if(args._.length!=1){response="Proper usage: dbget (key)"}else{response=db.Get(args._[0])}break;case"dbset":if(db==null){response="Database not accessible.";break}if(args._.length!=2){response="Proper usage: dbset (key) (value)"}else{var r=db.Put(args._[0],args._[1]);response="Key set: "+r}break;case"dbcompact":if(db==null){response="Database not accessible.";break}var r=db.Compact();response="Database compacted: "+r;break;case"httpget":if(consoleHttpRequest!=null){response="HTTP operation already in progress."}else{if(args._.length!=1){response="Proper usage: httpget (url)"}else{var options=http.parseUri(args._[0]);options.method="GET";if(options==null){response="Invalid url."}else{try{consoleHttpRequest=http.request(options,consoleHttpResponse)}catch(e){response="Invalid HTTP GET request"}consoleHttpRequest.sessionid=sessionid;if(consoleHttpRequest!=null){consoleHttpRequest.end();response="HTTPGET "+options.protocol+"//"+options.host+":"+options.port+options.path}}}}break;case"wslist":response="";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}if(response==""){response="no websocket sessions."}break;case"wsconnect":if(args._.length==0){response="Proper usage: wsconnect (url)\r\nFor example: wsconnect wss://localhost:443/meshrelay.ashx?id=abc"}else{var httprequest=null;try{var options=http.parseUri(args._[0]);options.rejectUnauthorized=0;httprequest=http.request(options)}catch(e){response="Invalid HTTP websocket request"}if(httprequest!=null){httprequest.upgrade=onWebSocketUpgrade;httprequest.onerror=function(e){sendConsoleText("ERROR: "+JSON.stringify(e))};var index=1;while(consoleWebSockets[index]){index++}httprequest.sessionid=sessionid;httprequest.index=index;httprequest.url=args._[0];consoleWebSockets[index]=httprequest;response="New websocket session #"+index}}break;case"wssend":if(args._.length==0){response="Proper usage: wssend (socketnumber)\r\n";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){httprequest.s.write(args._[1]);response="ok"}else{response="Invalid web socket number"}}break;case"wsclose":if(args._.length==0){response="Proper usage: wsclose (socketnumber)"}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){if(httprequest.s!=null){httprequest.s.end()}else{httprequest.end()}response="ok"}else{response="Invalid web socket number"}}break;case"tunnels":response="";for(var i in tunnels){response+="Tunnel #"+i+", "+tunnels[i].url+"\r\n"}if(response==""){response="No websocket sessions."}break;case"ls":response="";var xpath="*";if(args._.length>0){xpath=obj.path.join(args._[0],"*")}response="List of "+xpath+"\r\n";var results=fs.readdirSync(xpath);for(var i=0;i0){var r="",pstates=["NotActivated","InActivation","Activated"];for(var i in data){var x=data[i];if(r!=""){r+="\r\n"}r+=x.address+" - Intel AMT v"+x.majorVersion+"."+x.minorVersion;if(x.provisioningState<3){r+=(", "+pstates[x.provisioningState])}if(x.provisioningState==2){r+=(", "+x.openPorts.join(", "))}r+="."}}else{r="No Intel AMT found."}sendConsoleText(r)})}}else{response="Intel AMT scanner module not present."}break;case"modules":response=JSON.stringify(addedModules);break;case"getscript":if(args._.length!=1){response="Proper usage: getscript [scriptNumber]."}else{mesh.SendCommand({action:"getScript",type:args._[0]})}break;default:response='Unknown command "'+cmd+'", type "help" for list of avaialble commands.';break}}catch(e){response="Command returned an exception error: "+e;console.log(e)}if(response!=null){sendConsoleText(response,sessionid)}}function sendConsoleText(text,sessionid){if(typeof text=="object"){text=JSON.stringify(text)}mesh.SendCommand({action:"msg",type:"console",value:text,sessionid:sessionid})}function handleServerConnection(state){meshServerConnectionState=state;if(meshServerConnectionState==0){if(selfInfoUpdateTimer!=null){clearInterval(selfInfoUpdateTimer);selfInfoUpdateTimer=null}lastSelfInfo=null}else{var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){mesh.SendCommand({action:"mc1migration",oldnodeid:oldNodeId})}mesh.SendCommand(meshCoreObj);if(SMBiosTablesRaw!=null){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}meInfoStr=null;sendPeriodicServerUpdate()}}var sendNetworkUpdateNagleTimer=null;function sendNetworkUpdateNagle(){if(sendNetworkUpdateNagleTimer!=null){clearTimeout(sendNetworkUpdateNagleTimer);sendNetworkUpdateNagleTimer=null}sendNetworkUpdateNagleTimer=setTimeout(sendNetworkUpdate,5000)}function sendNetworkUpdate(force){sendNetworkUpdateNagleTimer=null;var netInfo=mesh.NetInfo;netInfo.action="netinfo";var netInfoStr=JSON.stringify(netInfo);if((force==true)||(clearGatewayMac(netInfoStr)!=clearGatewayMac(lastNetworkInfo))){mesh.SendCommand(netInfo);lastNetworkInfo=netInfoStr}}function sendPeriodicServerUpdate(flags){if(meshServerConnectionState==0){return}if(!flags){flags=4294967295}if(flags&1){getAmtInfo(function(meinfo){try{if(meinfo==null){return}var intelamt={},p=false;if(meinfo.Versions&&meinfo.Versions.AMT){intelamt.ver=meinfo.Versions.AMT;p=true}if(meinfo.ProvisioningState){intelamt.state=meinfo.ProvisioningState;p=true}if(meinfo.Flags){intelamt.flags=meinfo.Flags;p=true}if(meinfo.OsHostname){intelamt.host=meinfo.OsHostname;p=true}if(meinfo.UUID){intelamt.uuid=meinfo.UUID;p=true}if(p==true){var meInfoStr=JSON.stringify(intelamt);if(meInfoStr!=lastMeInfo){meshCoreObj.intelamt=intelamt;mesh.SendCommand(meshCoreObj);lastMeInfo=meInfoStr}}}catch(ex){}})}if(flags&2){sendNetworkUpdateNagle(false)}}function getAmtInfo(func){if(amtMei==null||amtMeiConnected!=2){if(func!=null){func(null)}return}try{amtMeiTmpState={Flags:0};amtMei.getProtocolVersion(function(result){if(result!=null){amtMeiTmpState.MeiVersion=result}});amtMei.getVersion(function(result){if(result){amtMeiTmpState.Versions={};for(var version in result.Versions){amtMeiTmpState.Versions[result.Versions[version].Description]=result.Versions[version].Version}}});amtMei.getProvisioningMode(function(result){if(result){amtMeiTmpState.ProvisioningMode=result.mode}});amtMei.getProvisioningState(function(result){if(result){amtMeiTmpState.ProvisioningState=result.state}});amtMei.getEHBCState(function(result){if((result!=null)&&(result.EHBC==true)){amtMeiTmpState.Flags+=1}});amtMei.getControlMode(function(result){if(result!=null){if(result.controlMode==1){amtMeiTmpState.Flags+=2}if(result.controlMode==2){amtMeiTmpState.Flags+=4}}});amtMei.getLanInterfaceSettings(0,function(result){if(result){amtMeiTmpState.net0=result}});amtMei.getLanInterfaceSettings(1,function(result){if(result){amtMeiTmpState.net1=result}});amtMei.getUuid(function(result){if((result!=null)&&(result.uuid!=null)){amtMeiTmpState.UUID=result.uuid}});amtMei.getDnsSuffix(function(result){if(result!=null){amtMeiTmpState.dns=result}if(func!=null){func(amtMeiTmpState)}})}catch(e){if(func!=null){func(null)}return}}function handleAmtNotification(notifyMsg){if((notifyMsg==null)||(notifyMsg.Body==null)||(notifyMsg.Body.MessageID==null)||(notifyMsg.Body.MessageArguments==null)){return null}var amtMessage=notifyMsg.Body.MessageID,amtMessageArg=notifyMsg.Body.MessageArguments[0],notify=null;switch(amtMessage){case"iAMT0050":if(amtMessageArg=="48"){notify="Intel® AMT Serial-over-LAN connected"}else{if(amtMessageArg=="49"){notify="Intel® AMT Serial-over-LAN disconnected"}}break;case"iAMT0052":if(amtMessageArg=="1"){notify="Intel® AMT KVM connected"}else{if(amtMessageArg=="2"){notify="Intel® AMT KVM disconnected"}}break;default:break}if(notify!=null){mesh.SendCommand({action:"msg",type:"notify",value:notify,tag:"general"})}}function resetMicroLms(){try{var lme_heci=require("amt-lme");amtLmsState=1;amtLms=new lme_heci();amtLms.on("error",function(e){amtLmsState=0;amtLms=null;sendConsoleText("LMS Error.");obj.setupMeiOsAdmin(null,1)});amtLms.on("connect",function(){amtLmsState=2;obj.setupMeiOsAdmin(null,2)});amtLms.on("notify",function(data,options,str,code){if(code=="iAMT0052-3"){obj.kvmGetData()}else{handleAmtNotification(data)}})}catch(e){amtLmsState=-1;amtLms=null}}obj.start=function(){mesh.AddCommandHandler(handleServerCommand);mesh.AddConnectHandler(handleServerConnection);resetMicroLms();try{var userSession=require("user-sessions");userSession.on("changed",function onUserSessionChanged(){userSession.enumerateUsers().then(function(users){var u=[],a=users.Active;for(var i=0;i=12)){obj.kvmGetData("skip");obj.kvmTempTimer=setInterval(function(){obj.kvmGetData()},2000);obj.kvmSetData(JSON.stringify({action:"restart",ver:1}))}})})};obj.kvmGetData=function(tag){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(obj.kvmDataGetResponse,tag)};obj.kvmDataGetResponse=function(stack,name,response,status,tag){if((tag!="skip")&&(status==200)&&(response.Body.ReturnValue==0)){var val=null;try{val=Buffer.from(response.Body.DataMessage,"base64").toString()}catch(e){return}if(val!=null){obj.kvmProcessData(response.Body.RealmsBitmap,response.Body.MessageId,val)}}};var webRtcDesktop=null;obj.kvmProcessData=function(realms,messageId,val){var data=null;try{data=JSON.parse(val)}catch(e){}if((data!=null)&&(data.action)){if(data.action=="present"){obj.kvmSetData(JSON.stringify({action:"present",ver:1,platform:process.platform}))}if(data.action=="offer"){webRtcDesktop={};var rtc=require("ILibWebRTC");webRtcDesktop.webrtc=rtc.createConnection();webRtcDesktop.webrtc.on("connected",function(){});webRtcDesktop.webrtc.on("disconnected",function(){obj.webRtcCleanUp()});webRtcDesktop.webrtc.on("dataChannel",function(rtcchannel){webRtcDesktop.rtcchannel=rtcchannel;webRtcDesktop.kvm=mesh.getRemoteDesktopStream();webRtcDesktop.kvm.pipe(webRtcDesktop.rtcchannel,{dataTypeSkip:1,end:false});webRtcDesktop.rtcchannel.on("end",function(){obj.webRtcCleanUp()});webRtcDesktop.rtcchannel.on("data",function(x){obj.kvmCtrlData(this,x)});webRtcDesktop.rtcchannel.pipe(webRtcDesktop.kvm,{dataTypeSkip:1,end:false})});obj.kvmSetData(JSON.stringify({action:"answer",ver:1,sdp:webRtcDesktop.webrtc.setOffer(data.sdp)}))}}};var path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};obj.kvmCtrlData=function(channel,cmd){if(cmd.length>0&&cmd.charCodeAt(0)!=123){if(this.fileupload!=null){cmd=Buffer.from(cmd,"base64");var header=cmd.readUInt32BE(0);if((header==16777216)||(header==16777217)){fs.writeSync(this.fileupload.fp,cmd.slice(4));channel.write({action:"upload",sub:"ack",reqid:this.fileupload.reqid});if(header==16777217){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}return}try{cmd=JSON.parse(cmd)}catch(ex){console.error("Invalid JSON: "+cmd);return}if((cmd.path!=null)&&(process.platform!="win32")&&(cmd.path[0]!="/")){cmd.path="/"+cmd.path}switch(cmd.action){case"ping":channel.write({action:"pong"});break;case"lock":if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}break;case"ls":var response=getDirectoryInfo(cmd.path);if(cmd.reqid!=undefined){response.reqid=cmd.reqid}channel.write(response);break;case"mkdir":fs.mkdirSync(cmd.path);break;case"rm":for(var i in cmd.delfiles){var fullpath=path.join(cmd.path,cmd.delfiles[i]);try{fs.unlinkSync(fullpath)}catch(e){console.log(e)}}break;case"rename":try{fs.renameSync(path.join(cmd.path,cmd.oldname),path.join(cmd.path,cmd.newname))}catch(e){console.log(e)}break;case"download":var sendNextBlock=0;if(cmd.sub=="start"){if(this.filedownload!=null){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}this.filedownload={id:cmd.id,path:cmd.path,ptr:0};try{this.filedownload.f=fs.openSync(this.filedownload.path,"rbN")}catch(e){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}if(this.filedownload){channel.write({action:"download",sub:"start",id:cmd.id})}}else{if((this.filedownload!=null)&&(cmd.id==this.filedownload.id)){if(cmd.sub=="startack"){sendNextBlock=8}else{if(cmd.sub=="stop"){delete this.filedownload}else{if(cmd.sub=="ack"){sendNextBlock=1}}}}}while(sendNextBlock>0){sendNextBlock--;var buf=Buffer.alloc(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}channel.write(buf.slice(0,len+4).toString("base64"))}break;case"upload":if(cmd.sub=="start"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp)}if(!cmd.path||!cmd.name){break}this.fileupload={reqid:cmd.reqid};var filepath=path.join(cmd.path,cmd.name);try{this.fileupload.fp=fs.openSync(filepath,"wbN")}catch(e){}if(this.fileupload.fp){channel.write({action:"upload",sub:"start",reqid:this.fileupload.reqid})}else{this.fileupload=null;channel.write({action:"upload",sub:"error",reqid:this.fileupload.reqid})}}else{if(cmd.sub=="cancel"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}break;case"copy":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:console.log("Invalid KVM command",cmd);sendConsoleText("Invalid KVM command: "+cmd);break}};obj.webRtcCleanUp=function(){sendConsoleText("webRtcCleanUp");if(webRtcDesktop==null){return}if(webRtcDesktop.rtcchannel){try{webRtcDesktop.rtcchannel.close()}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("data")}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("end")}catch(e){}delete webRtcDesktop.rtcchannel}if(webRtcDesktop.webrtc){try{webRtcDesktop.webrtc.close()}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("connected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("disconnected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("dataChannel")}catch(e){}delete webRtcDesktop.webrtc}if(webRtcDesktop.kvm){try{webRtcDesktop.kvm.end()}catch(e){}delete webRtcDesktop.kvm}webRtcDesktop=null};obj.kvmSetData=function(x){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString("base64"),function(){})};function deleteFolderRecursive(path,rec){if(fs.existsSync(path)){if(rec==true){fs.readdirSync(obj.path.join(path,"*")).forEach(function(file,index){var curPath=obj.path.join(path,file);if(fs.statSync(curPath).isDirectory()){deleteFolderRecursive(curPath,true)}else{fs.unlinkSync(curPath)}})}fs.unlinkSync(path)}}function deactivateCCM(){amtMei.unprovision(1,function(status){if(status==0){sendConsoleText("Success deactivating Intel AMT CCM.")}else{sendConsoleText("Intel AMT CCM deactivation error: "+status)}})}function activeToCCM(adminpass){sendConsoleText("Trying to get local account info...");amtMei.getLocalSystemAccount(function(x){if(x.user&&x.pass){sendConsoleText("Intel AMT local account info: User="+x.user+", Pass="+x.pass+".");var transport=require("amt-wsman-duk");var wsman=require("amt-wsman");var amt=require("amt");oswsstack=new wsman(transport,"127.0.0.1",16992,x.user,x.pass,false);osamtstack=new amt(oswsstack);sendConsoleText("Trying to get Intel AMT activation information...");osamtstack.BatchEnum(null,["*AMT_GeneralSettings","*IPS_HostBasedSetupService"],activeToCCMEx2,adminpass)}else{sendConsoleText("Unable to get $$OsAdmin password.")}})}function activeToCCMEx2(stack,name,responses,status,adminpass){if(status!=200){sendConsoleText("Failed to fetch activation information, status "+status)}else{if(responses.IPS_HostBasedSetupService.response.AllowedControlModes.length!=2){sendConsoleText("Client control mode activation not allowed")}else{stack.IPS_HostBasedSetupService_Setup(2,md5hex("admin:"+responses.AMT_GeneralSettings.response.DigestRealm+":"+adminpass).substring(0,32),null,null,null,null,activeToCCMEx3)}}}function activeToCCMEx3(stack,name,responses,status){if(status!=200){sendConsoleText("Failed to activate, status "+status)}else{if(responses.Body.ReturnValue!=0){sendConsoleText("Client control mode activation failed: "+responses.Body.ReturnValueStr)}else{sendConsoleText("Intel AMT CCM activation success")}}}function md5hex(str){return require("MD5Stream").create().syncHash(str).toString("hex")}return obj}try{var xexports=null,mainMeshCore=null;try{xexports=module.exports}catch(e){}if(xexports!=null){module.exports.createMeshCore=createMeshCore}else{mainMeshCore=createMeshCore();mainMeshCore.start(null)}}catch(ex){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException2: "+ex})}; \ No newline at end of file diff --git a/agents/modules_meshcore/clipboard.js b/agents/modules_meshcore/clipboard.js new file mode 100644 index 00000000..341d0da5 --- /dev/null +++ b/agents/modules_meshcore/clipboard.js @@ -0,0 +1,178 @@ +/* +Copyright 2019 Intel Corporation + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +var promise = require('promise'); + +function nativeAddModule(name) +{ + var value = getJSModule(name); + var ret = "duk_peval_string_noresult(ctx, \"addModule('" + name + "', Buffer.from('" + Buffer.from(value).toString('base64') + "', 'base64').toString());\");"; + module.exports(ret); +} + +function lin_readtext() +{ + var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; }); + try + { + require('monitor-info') + } + catch(exc) + { + ret._rej(exc); + return (ret); + } + + var X11 = require('monitor-info')._X11; + if (!X11) + { + ret._rej('X11 required for Clipboard Manipulation'); + } + else + { + var SelectionNotify = 31; + var AnyPropertyType = 0; + var GM = require('monitor-info')._gm; + + ret._getInfoPromise = require('monitor-info').getInfo(); + ret._getInfoPromise._masterPromise = ret; + ret._getInfoPromise.then(function (mon) + { + if (mon.length > 0) + { + var white = X11.XWhitePixel(mon[0].display, mon[0].screenId).Val; + + this._masterPromise.CLIPID = X11.XInternAtom(mon[0].display, GM.CreateVariable('CLIPBOARD'), 0); + this._masterPromise.FMTID = X11.XInternAtom(mon[0].display, GM.CreateVariable('UTF8_STRING'), 0); + this._masterPromise.PROPID = X11.XInternAtom(mon[0].display, GM.CreateVariable('XSEL_DATA'), 0); + this._masterPromise.INCRID = X11.XInternAtom(mon[0].display, GM.CreateVariable('INCR'), 0); + this._masterPromise.ROOTWIN = X11.XRootWindow(mon[0].display, mon[0].screenId); + this._masterPromise.FAKEWIN = X11.XCreateSimpleWindow(mon[0].display, this._masterPromise.ROOTWIN, 0, 0, mon[0].right, 5, 0, white, white); + + X11.XSync(mon[0].display, 0); + X11.XConvertSelection(mon[0].display, this._masterPromise.CLIPID, this._masterPromise.FMTID, this._masterPromise.PROPID, this._masterPromise.FAKEWIN, 0); + X11.XSync(mon[0].display, 0); + + this._masterPromise.DescriptorEvent = require('DescriptorEvents').addDescriptor(X11.XConnectionNumber(mon[0].display).Val, { readset: true }); + this._masterPromise.DescriptorEvent._masterPromise = this._masterPromise; + this._masterPromise.DescriptorEvent._display = mon[0].display; + this._masterPromise.DescriptorEvent.on('readset', function (fd) + { + var XE = GM.CreateVariable(1024); + while (X11.XPending(this._display).Val) + { + X11.XNextEventSync(this._display, XE); + if(XE.Deref(0, 4).toBuffer().readUInt32LE() == SelectionNotify) + { + var id = GM.CreatePointer(); + var bits = GM.CreatePointer(); + var sz = GM.CreatePointer(); + var tail = GM.CreatePointer(); + var result = GM.CreatePointer(); + + X11.XGetWindowProperty(this._display, this._masterPromise.FAKEWIN, this._masterPromise.PROPID, 0, 65535, 0, AnyPropertyType, id, bits, sz, tail, result); + this._masterPromise._res(result.Deref().String); + X11.XFree(result.Deref()); + X11.XDestroyWindow(this._display, this._masterPromise.FAKEWIN); + + this.removeDescriptor(fd); + break; + } + } + }); + } + }); + } + return (ret); +} +function lin_copytext() +{ +} + +function win_readtext() +{ + var ret = ''; + var CF_TEXT = 1; + var GM = require('_GenericMarshal'); + var user32 = GM.CreateNativeProxy('user32.dll'); + var kernel32 = GM.CreateNativeProxy('kernel32.dll'); + kernel32.CreateMethod('GlobalAlloc'); + kernel32.CreateMethod('GlobalLock'); + kernel32.CreateMethod('GlobalUnlock'); + user32.CreateMethod('OpenClipboard'); + user32.CreateMethod('CloseClipboard'); + user32.CreateMethod('GetClipboardData'); + + user32.OpenClipboard(0); + var h = user32.GetClipboardData(CF_TEXT); + if(h.Val!=0) + { + var hbuffer = kernel32.GlobalLock(h); + ret = hbuffer.String; + kernel32.GlobalUnlock(h); + } + user32.CloseClipboard(); + + var p = new promise(function (res, rej) { this._res = res; this._rej = rej; }); + p._res(ret); + return (p); +} + +function win_copytext(txt) +{ + var GMEM_MOVEABLE = 0x0002; + var CF_TEXT = 1; + + var GM = require('_GenericMarshal'); + var user32 = GM.CreateNativeProxy('user32.dll'); + var kernel32 = GM.CreateNativeProxy('kernel32.dll'); + kernel32.CreateMethod('GlobalAlloc'); + kernel32.CreateMethod('GlobalLock'); + kernel32.CreateMethod('GlobalUnlock'); + user32.CreateMethod('OpenClipboard'); + user32.CreateMethod('EmptyClipboard'); + user32.CreateMethod('CloseClipboard'); + user32.CreateMethod('SetClipboardData'); + + var h = kernel32.GlobalAlloc(GMEM_MOVEABLE, txt.length + 2); + h.autoFree(false); + var hbuffer = kernel32.GlobalLock(h); + hbuffer.autoFree(false); + var tmp = Buffer.alloc(txt.length + 1); + Buffer.from(txt).copy(tmp); + tmp.copy(hbuffer.Deref(0, txt.length + 1).toBuffer()); + kernel32.GlobalUnlock(h); + + user32.OpenClipboard(0); + user32.EmptyClipboard(); + user32.SetClipboardData(CF_TEXT, h); + user32.CloseClipboard(); +} + +switch(process.platform) +{ + case 'win32': + module.exports = win_copytext; + module.exports.read = win_readtext; + break; + case 'linux': + module.exports = lin_copytext; + module.exports.read = lin_readtext; + break; + case 'darwin': + break; +} +module.exports.nativeAddModule = nativeAddModule; \ No newline at end of file diff --git a/agents/modules_meshcore_min/clipboard.min.js b/agents/modules_meshcore_min/clipboard.min.js new file mode 100644 index 00000000..44011229 --- /dev/null +++ b/agents/modules_meshcore_min/clipboard.min.js @@ -0,0 +1 @@ +var promise=require("promise");function nativeAddModule(a){var c=getJSModule(a);var b="duk_peval_string_noresult(ctx, \"addModule('"+a+"', Buffer.from('"+Buffer.from(c).toString("base64")+"', 'base64').toString());\");";module.exports(b)}function lin_readtext(){var d=new promise(function(h,g){this._res=h;this._rej=g});try{require("monitor-info")}catch(b){d._rej(b);return(d)}var f=require("monitor-info")._X11;if(!f){d._rej("X11 required for Clipboard Manipulation")}else{var e=31;var a=0;var c=require("monitor-info")._gm;d._getInfoPromise=require("monitor-info").getInfo();d._getInfoPromise._masterPromise=d;d._getInfoPromise.then(function(g){if(g.length>0){var h=f.XWhitePixel(g[0].display,g[0].screenId).Val;this._masterPromise.CLIPID=f.XInternAtom(g[0].display,c.CreateVariable("CLIPBOARD"),0);this._masterPromise.FMTID=f.XInternAtom(g[0].display,c.CreateVariable("UTF8_STRING"),0);this._masterPromise.PROPID=f.XInternAtom(g[0].display,c.CreateVariable("XSEL_DATA"),0);this._masterPromise.INCRID=f.XInternAtom(g[0].display,c.CreateVariable("INCR"),0);this._masterPromise.ROOTWIN=f.XRootWindow(g[0].display,g[0].screenId);this._masterPromise.FAKEWIN=f.XCreateSimpleWindow(g[0].display,this._masterPromise.ROOTWIN,0,0,g[0].right,5,0,h,h);f.XSync(g[0].display,0);f.XConvertSelection(g[0].display,this._masterPromise.CLIPID,this._masterPromise.FMTID,this._masterPromise.PROPID,this._masterPromise.FAKEWIN,0);f.XSync(g[0].display,0);this._masterPromise.DescriptorEvent=require("DescriptorEvents").addDescriptor(f.XConnectionNumber(g[0].display).Val,{readset:true});this._masterPromise.DescriptorEvent._masterPromise=this._masterPromise;this._masterPromise.DescriptorEvent._display=g[0].display;this._masterPromise.DescriptorEvent.on("readset",function(j){var o=c.CreateVariable(1024);while(f.XPending(this._display).Val){f.XNextEventSync(this._display,o);if(o.Deref(0,4).toBuffer().readUInt32LE()==e){var k=c.CreatePointer();var i=c.CreatePointer();var m=c.CreatePointer();var n=c.CreatePointer();var l=c.CreatePointer();f.XGetWindowProperty(this._display,this._masterPromise.FAKEWIN,this._masterPromise.PROPID,0,65535,0,a,k,i,m,n,l);this._masterPromise._res(l.Deref().String);f.XFree(l.Deref());f.XDestroyWindow(this._display,this._masterPromise.FAKEWIN);this.removeDescriptor(j);break}}})}})}return(d)}function lin_copytext(){}function win_readtext(){var g="";var a=1;var b=require("_GenericMarshal");var i=b.CreateNativeProxy("user32.dll");var e=b.CreateNativeProxy("kernel32.dll");e.CreateMethod("GlobalAlloc");e.CreateMethod("GlobalLock");e.CreateMethod("GlobalUnlock");i.CreateMethod("OpenClipboard");i.CreateMethod("CloseClipboard");i.CreateMethod("GetClipboardData");i.OpenClipboard(0);var c=i.GetClipboardData(a);if(c.Val!=0){var d=e.GlobalLock(c);g=d.String;e.GlobalUnlock(c)}i.CloseClipboard();var f=new promise(function(j,h){this._res=j;this._rej=h});f._res(g);return(f)}function win_copytext(i){var c=2;var a=1;var b=require("_GenericMarshal");var j=b.CreateNativeProxy("user32.dll");var f=b.CreateNativeProxy("kernel32.dll");f.CreateMethod("GlobalAlloc");f.CreateMethod("GlobalLock");f.CreateMethod("GlobalUnlock");j.CreateMethod("OpenClipboard");j.CreateMethod("EmptyClipboard");j.CreateMethod("CloseClipboard");j.CreateMethod("SetClipboardData");var d=f.GlobalAlloc(c,i.length+2);d.autoFree(false);var e=f.GlobalLock(d);e.autoFree(false);var g=Buffer.alloc(i.length+1);Buffer.from(i).copy(g);g.copy(e.Deref(0,i.length+1).toBuffer());f.GlobalUnlock(d);j.OpenClipboard(0);j.EmptyClipboard();j.SetClipboardData(a,d);j.CloseClipboard()}switch(process.platform){case"win32":module.exports=win_copytext;module.exports.read=win_readtext;break;case"linux":module.exports=lin_copytext;module.exports.read=lin_readtext;break;case"darwin":break}module.exports.nativeAddModule=nativeAddModule; \ No newline at end of file diff --git a/db.js b/db.js index 725d2da0..b60d3852 100644 --- a/db.js +++ b/db.js @@ -46,7 +46,7 @@ module.exports.CreateDB = function (parent) { obj.file.createIndex({ type: 1, domain: 1, meshid: 1 }, { sparse: 1 }); // Speeds up GetAllTypeNoTypeField() and GetAllTypeNoTypeFieldMeshFiltered() obj.file.createIndex({ email: 1 }, { sparse: 1 }); // Speeds up GetUserWithEmail() and GetUserWithVerifiedEmail() obj.file.createIndex({ ids: 1, time: -1 }, { sparse: 1 }); // Speeds up GetEvents() and GetEventsWithLimit() - obj.file.createIndex({ type: 1, node: 1, time: -1 }, { sparse: 1 }); // Speeds up getPowerTimeline() + obj.file.createIndex({ type: 1, nodeid: 1, time: 1 }, { sparse: 1 }); // Speeds up getPowerTimeline() obj.file.createIndex({ mesh: 1 }, { sparse: 1 }); // Speeds up RemoveMesh() } else { // Use NeDB (The default) @@ -186,7 +186,7 @@ module.exports.CreateDB = function (parent) { obj.SetUser = function (user) { var u = Clone(user); if (u.subscriptions) { delete u.subscriptions; } obj.Set(u); }; obj.dispose = function () { for (var x in obj) { if (obj[x].close) { obj[x].close(); } delete obj[x]; } }; obj.clearOldEntries = function (type, days, domain) { var cutoff = Date.now() - (1000 * 60 * 60 * 24 * days); obj.file.remove({ type: type, time: { $lt: cutoff } }, { multi: true }); }; - obj.getPowerTimeline = function (nodeid, func) { if (obj.databaseType == 1) { obj.file.find({ type: 'power', node: { $in: ['*', nodeid] } }).sort({ time: 1 }).exec(func); } else { obj.file.find({ type: 'power', node: { $in: ['*', nodeid] } }).sort({ time: 1 }, func); } }; + obj.getPowerTimeline = function (nodeid, func) { if (obj.databaseType == 1) { obj.file.find({ type: 'power', nodeid: { $in: ['*', nodeid] } }).sort({ time: 1 }).exec(func); } else { obj.file.find({ type: 'power', node: { $in: ['*', nodeid] } }).sort({ time: 1 }, func); } }; obj.getLocalAmtNodes = function (func) { obj.file.find({ type: 'node', host: { $exists: true, $ne: null }, intelamt: { $exists: true } }, func); }; obj.getAmtUuidNode = function (meshid, uuid, func) { obj.file.find({ type: 'node', meshid: meshid, 'intelamt.uuid': uuid }, func); }; obj.isMaxType = function (max, type, domainid, func) { if (max == null) { func(false); } else { obj.file.count({ type: type, domain: domainid }, function (err, count) { func((err != null) || (count > max)); }); } } diff --git a/meshcentral.js b/meshcentral.js index 7ff44573..b3582a5c 100644 --- a/meshcentral.js +++ b/meshcentral.js @@ -363,6 +363,21 @@ function CreateMeshCentralServer(config, args) { obj.db.RemoveAll(function () { obj.db.InsertMany(json, function (err) { if (err != null) { console.log(err); } else { console.log('Imported ' + json.length + ' objects(s) from ' + obj.args.dbimport + '.'); } process.exit(); }); }); return; } + /* + if (obj.args.dbimport) { + // Import the entire database from a very large JSON file + obj.db.RemoveAll(function () { + if (obj.args.dbimport == true) { obj.args.dbimport = obj.getConfigFilePath('meshcentral.db.json'); } + var json = null, json2 = "", badCharCount = 0; + const StreamArray = require('stream-json/streamers/StreamArray'); + const jsonStream = StreamArray.withParser(); + jsonStream.on('data', function (data) { obj.db.Set(data.value); }); + jsonStream.on('end', () => { console.log('Done.'); process.exit(); }); + obj.fs.createReadStream(obj.args.dbimport).pipe(jsonStream.input); + }); + return; + } + */ if (obj.args.dbmerge) { // Import the entire database from a JSON file if (obj.args.dbmerge == true) { obj.args.dbmerge = obj.getConfigFilePath('meshcentral.db.json'); } @@ -521,6 +536,7 @@ function CreateMeshCentralServer(config, args) { if (obj.args.minifycore === 0) obj.args.minifycore = false; // Clear old event entries and power entires + // TODO: Replace this is delete indexes on NeDB and MongoDB. obj.db.clearOldEntries('event', 30); // Clear all event entires that are older than 30 days. obj.db.clearOldEntries('power', 10); // Clear all event entires that are older than 10 days. If a node is connected longer than 10 days, current power state will be used for everything. @@ -565,9 +581,9 @@ function CreateMeshCentralServer(config, args) { // Set all nodes to power state of unknown (0) if (obj.multiServer == null) { - obj.db.file.insert({ type: 'power', time: Date.now(), node: '*', power: 0, s: 1 }); + obj.db.file.insert({ type: 'power', time: Date.now(), nodeid: '*', power: 0, s: 1 }); } else { - obj.db.file.insert({ type: 'power', time: Date.now(), node: '*', power: 0, s: 1, server: obj.multiServer.serverid }); + obj.db.file.insert({ type: 'power', time: Date.now(), nodeid: '*', power: 0, s: 1, server: obj.multiServer.serverid }); } // Read or setup database configuration values @@ -802,7 +818,7 @@ function CreateMeshCentralServer(config, args) { obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'stopped', msg: 'Server stopped' }); // Set all nodes to power state of unknown (0) - var record = { type: 'power', time: Date.now(), node: '*', power: 0, s: 2 }; + var record = { type: 'power', time: Date.now(), nodeid: '*', power: 0, s: 2 }; if (obj.multiServer != null) { record.server = obj.multiServer.serverid; } obj.db.file.insert(record, function () { if (restoreFile) { @@ -977,7 +993,7 @@ function CreateMeshCentralServer(config, args) { eventConnectChange = 1; // Set new power state in database - var record = { type: 'power', time: connectTime, node: nodeid, power: powerState }; + var record = { type: 'power', time: connectTime, nodeid: nodeid, power: powerState }; if (oldPowerState != null) record.oldPower = oldPowerState; obj.db.file.insert(record); } @@ -1008,7 +1024,7 @@ function CreateMeshCentralServer(config, args) { state.powerState = powerState; // Set new power state in database - var record = { type: 'power', time: connectTime, node: nodeid, power: powerState, server: obj.multiServer.serverid }; + var record = { type: 'power', time: connectTime, nodeid: nodeid, power: powerState, server: obj.multiServer.serverid }; if (oldPowerState != null) record.oldPower = oldPowerState; obj.db.file.insert(record); } @@ -1052,7 +1068,7 @@ function CreateMeshCentralServer(config, args) { eventConnectChange = 1; // Set new power state in database - obj.db.file.insert({ type: 'power', time: Date.now(), node: nodeid, power: powerState, oldPower: oldPowerState }); + obj.db.file.insert({ type: 'power', time: Date.now(), nodeid: nodeid, power: powerState, oldPower: oldPowerState }); } // Event the node connection change diff --git a/meshuser.js b/meshuser.js index 0e7391a3..2daba107 100644 --- a/meshuser.js +++ b/meshuser.js @@ -181,7 +181,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use var os = require('os'); var stats = { action: 'serverstats', totalmem: os.totalmem(), freemem: os.freemem() }; if (obj.parent.parent.platform != 'win32') { stats.cpuavg = os.loadavg(); } // else { stats.cpuavg = [ 0.2435345, 0.523234234, 0.6435345345 ]; } - var serverStats = { "User Accounts": Object.keys(obj.parent.users).length, "Device Groups": Object.keys(obj.parent.meshes).length, "Connected Agents": Object.keys(obj.parent.wsagents).length, "Connected Users": Object.keys(obj.parent.wssessions2).length }; + var serverStats = { "User Accounts": Object.keys(obj.parent.users).length, "Device Groups": Object.keys(obj.parent.meshes).length, "Agent Sessions": Object.keys(obj.parent.wsagents).length, "Users Sessions": Object.keys(obj.parent.wssessions2).length }; if (obj.parent.parent.mpsserver != null) { serverStats['Connected Intel® AMT'] = Object.keys(obj.parent.parent.mpsserver.ciraConnections).length; } stats.values = { "Server State": serverStats } try { ws.send(JSON.stringify(stats)); } catch (ex) { } @@ -1802,6 +1802,49 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use }); break; } + case 'getClip': { + if (obj.common.validateString(command.nodeid, 1, 1024) == false) break; // Check nodeid + + // Get the device + obj.db.Get(command.nodeid, function (err, nodes) { + if (nodes.length != 1) return; + var node = nodes[0]; + + // Get the mesh for this device + mesh = obj.parent.meshes[node.meshid]; + if (mesh) { + // Check if this user has "remote" rights to do this + if ((mesh.links[user._id] == null) || ((mesh.links[user._id].rights & 16) == 0)) return; + + // Ask for clipboard data from agent + var agent = obj.parent.wsagents[node._id]; + if (agent != null) { try { agent.send(JSON.stringify({ action: 'getClip' })); } catch (ex) { } } + } + }); + break; + } + case 'setClip': { + if (obj.common.validateString(command.nodeid, 1, 1024) == false) break; // Check nodeid + if (obj.common.validateString(command.data, 1, 65535) == false) break; // Check + + // Get the device + obj.db.Get(command.nodeid, function (err, nodes) { + if (nodes.length != 1) return; + var node = nodes[0]; + + // Get the mesh for this device + mesh = obj.parent.meshes[node.meshid]; + if (mesh) { + // Check if this user has "remote" rights to do this + if ((mesh.links[user._id] == null) || ((mesh.links[user._id].rights & 16) == 0)) return; + + // Send clipboard data to the agent + var agent = obj.parent.wsagents[node._id]; + if (agent != null) { try { agent.send(JSON.stringify({ action: 'setClip', data: command.data })); } catch (ex) { } } + } + }); + break; + } case 'getNotes': { // Argument validation diff --git a/package.json b/package.json index dfd38774..fea01801 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "meshcentral", - "version": "0.2.8-o", + "version": "0.2.8-q", "keywords": [ "Remote Management", "Intel AMT", diff --git a/views/default-min.handlebars b/views/default-min.handlebars index a3e900f1..44e41270 100644 --- a/views/default-min.handlebars +++ b/views/default-min.handlebars @@ -1 +1 @@ - MeshCentral
{{{title}}}
{{{title2}}}

{{{logoutControl}}}

 

\ No newline at end of file + MeshCentral
{{{title}}}
{{{title2}}}

{{{logoutControl}}}

 

\ No newline at end of file diff --git a/views/default.handlebars b/views/default.handlebars index 1e9199d1..d468fb33 100644 --- a/views/default.handlebars +++ b/views/default.handlebars @@ -488,7 +488,8 @@ - + + Input  @@ -920,6 +921,7 @@ QV('p13AutoConnect', debugmode); // Files QV('autoconnectbutton2', debugmode); // Terminal QV('autoconnectbutton1', debugmode); // Desktop + QV('DeskClip', debugmode); // Clipboard feature, not completed so show in in debug mode only. toggleFullScreen(); @@ -1291,6 +1293,12 @@ addNotification(n); } else if (message.type == 'ps') { showDeskToolsProcesses(message); + } else if ((message.type == 'getclip') && (xxdialogTag == 'clipboard') && (currentNode != null) && (currentNode._id == message.nodeid)) { + Q('d2clipText').value = message.data; + } else if ((message.type == 'setclip') && (xxdialogTag == 'clipboard') && (currentNode != null) && (currentNode._id == message.nodeid)) { + // Display success/fail on the clipboard dialog box. + QH('dlgClipStatus', message.success ? 'Success' : 'Failed') + setTimeout(function () { try { QH('dlgClipStatus', ''); } catch (ex) { } }, 2000); } } } else { @@ -4012,6 +4020,7 @@ QV('deskFocusBtn', (desktop != null) && (desktop.contype == 2) && (deskState != 0) && (desktopsettings.showfocus)); QV('DeskCAD', meshrights & 8); QE('DeskCAD', deskState == 3); + QE('DeskClip', deskState == 3); QV('DeskWD', (currentNode.agent) && (currentNode.agent.id < 5) && (meshrights & 8)); QE('DeskWD', deskState == 3); QV('deskkeys', (currentNode.agent) && (currentNode.agent.id < 5) && (meshrights & 8)); @@ -4410,6 +4419,29 @@ } } + // Show clipboard dialog + function showDeskClip() { + if (xxdialogMode || desktop == null || desktop.State != 3) return; + Q('DeskClip').blur(); + var x = ''; + x += ''; + x += '
'; + x += ''; + x += '
 
'; + setDialogMode(2, "Remote Clipboard", 8, null, x, 'clipboard'); + Q('d2clipText').focus(); + } + + function showDeskClipGet() { + if (desktop == null || desktop.State != 3) return; + meshserver.send({ action: 'msg', type: 'getclip', nodeid: currentNode._id }); + } + + function showDeskClipSet() { + if (desktop == null || desktop.State != 3) return; + meshserver.send({ action: 'msg', type: 'setclip', nodeid: currentNode._id, data: Q('d2clipText').value }); + } + // Send CTRL-ALT-DEL function sendCAD() { if (xxdialogMode || desktop == null || desktop.State != 3) return;