1 line
15 KiB
JavaScript
1 line
15 KiB
JavaScript
var NOTIFY_FOR_THIS_SESSION=0;var NOTIFY_FOR_ALL_SESSIONS=1;var WM_WTSSESSION_CHANGE=689;var WM_POWERBROADCAST=536;var PBT_POWERSETTINGCHANGE=32787;var PBT_APMSUSPEND=4;var PBT_APMRESUMESUSPEND=7;var PBT_APMRESUMEAUTOMATIC=18;var PBT_APMPOWERSTATUSCHANGE=10;var WTS_CONSOLE_CONNECT=(1);var WTS_CONSOLE_DISCONNECT=(2);var WTS_REMOTE_CONNECT=(3);var WTS_REMOTE_DISCONNECT=(4);var WTS_SESSION_LOGON=(5);var WTS_SESSION_LOGOFF=(6);var WTS_SESSION_LOCK=(7);var WTS_SESSION_UNLOCK=(8);var WTS_SESSION_REMOTE_CONTROL=(9);var WTS_SESSION_CREATE=(10);var WTS_SESSION_TERMINATE=(11);var GUID_ACDC_POWER_SOURCE;var GUID_BATTERY_PERCENTAGE_REMAINING;var GUID_CONSOLE_DISPLAY_STATE;function UserSessions(){this._ObjectID="user-sessions";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("locked").createEvent("unlocked");this.enumerateUsers=function h(){var s=require("promise");var r=new s(function(t,p){this.__resolver=t;this.__rejector=p});r.__handler=function o(p){r.__resolver(p)};try{this.Current(r.__handler)}catch(q){r.__rejector(q)}r.parent=this;return(r)};if(process.platform=="win32"){this._serviceHooked=false;this._marshal=require("_GenericMarshal");this._kernel32=this._marshal.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("GetLastError");try{this._wts=this._marshal.CreateNativeProxy("Wtsapi32.dll");this._wts.CreateMethod("WTSEnumerateSessionsA");this._wts.CreateMethod("WTSQuerySessionInformationA");this._wts.CreateMethod("WTSRegisterSessionNotification");this._wts.CreateMethod("WTSUnRegisterSessionNotification");this._wts.CreateMethod("WTSFreeMemory")}catch(i){}this._advapi=this._marshal.CreateNativeProxy("Advapi32.dll");this._advapi.CreateMethod("AllocateAndInitializeSid");this._advapi.CreateMethod("CheckTokenMembership");this._advapi.CreateMethod("FreeSid");this._user32=this._marshal.CreateNativeProxy("user32.dll");this._user32.CreateMethod({method:"RegisterPowerSettingNotification",threadDispatch:1});this._user32.CreateMethod("UnregisterPowerSettingNotification");this._rpcrt=this._marshal.CreateNativeProxy("Rpcrt4.dll");this._rpcrt.CreateMethod("UuidFromStringA");this._rpcrt.StringToUUID=function n(o){var p=n.us._marshal.CreateVariable(16);if(n.us._rpcrt.UuidFromStringA(n.us._marshal.CreateVariable(o),p).Val==0){return(p)}else{throw ("Could not convert string to UUID")}};this._rpcrt.StringToUUID.us=this;GUID_ACDC_POWER_SOURCE=this._rpcrt.StringToUUID("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548");GUID_BATTERY_PERCENTAGE_REMAINING=this._rpcrt.StringToUUID("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");GUID_CONSOLE_DISPLAY_STATE=this._rpcrt.StringToUUID("6fe69556-704a-47a0-8f24-c28d936fda47");this.SessionStates=["Active","Connected","ConnectQuery","Shadow","Disconnected","Idle","Listening","Reset","Down","Init"];this.InfoClass={WTSInitialProgram:0,WTSApplicationName:1,WTSWorkingDirectory:2,WTSOEMId:3,WTSSessionId:4,WTSUserName:5,WTSWinStationName:6,WTSDomainName:7,WTSConnectState:8,WTSClientBuildNumber:9,WTSClientName:10,WTSClientDirectory:11,WTSClientProductId:12,WTSClientHardwareId:13,WTSClientAddress:14,WTSClientDisplay:15,WTSClientProtocolType:16,WTSIdleTime:17,WTSLogonTime:18,WTSIncomingBytes:19,WTSOutgoingBytes:20,WTSIncomingFrames:21,WTSOutgoingFrames:22,WTSClientInfo:23,WTSSessionInfo:24,WTSSessionInfoEx:25,WTSConfigInfo:26,WTSValidationInfo:27,WTSSessionAddressV4:28,WTSIsRemoteSession:29};this.isRoot=function k(){var r=this._marshal.CreateVariable(6);r.toBuffer().writeInt8(5,5);var p=this._marshal.CreatePointer();var o=false;if(this._advapi.AllocateAndInitializeSid(r,2,32,544,0,0,0,0,0,0,p).Val!=0){var q=this._marshal.CreateInteger();if(this._advapi.CheckTokenMembership(0,p.Deref(),q).Val!=0){if(q.toBuffer().readUInt32LE()!=0){o=true}}this._advapi.FreeSid(p.Deref())}return o};this.getSessionAttribute=function j(s,o){var p=this._marshal.CreatePointer();var q=this._marshal.CreateVariable(4);if(this._wts.WTSQuerySessionInformationA(0,s,o,p,q).Val==0){throw ("Error calling WTSQuerySessionInformation: "+this._kernel32.GetLastError.Val)}var r=p.Deref().String;this._wts.WTSFreeMemory(p.Deref());return(r)};this.Current=function f(o){var u={};var t=this._marshal.CreatePointer();var p=this._marshal.CreateVariable(4);if(this._wts.WTSEnumerateSessionsA(0,0,1,t,p).Val==0){throw ("Error calling WTSEnumerateSessionsA: "+this._kernel32.GetLastError().Val)}for(var q=0;q<p.toBuffer().readUInt32LE();++q){var r=t.Deref().Deref(q*(this._marshal.PointerSize==4?12:24),this._marshal.PointerSize==4?12:24);var s={SessionId:r.toBuffer().readUInt32LE()};s.StationName=r.Deref(this._marshal.PointerSize==4?4:8,this._marshal.PointerSize).Deref().String;s.State=this.SessionStates[r.Deref(this._marshal.PointerSize==4?8:16,4).toBuffer().readUInt32LE()];if(s.State=="Active"){s.Username=this.getSessionAttribute(s.SessionId,this.InfoClass.WTSUserName);s.Domain=this.getSessionAttribute(s.SessionId,this.InfoClass.WTSDomainName)}u[s.SessionId]=s}this._wts.WTSFreeMemory(t.Deref());Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o(u)}return(u)};var l=require("win-message-pump");this._messagepump=new l({filter:WM_WTSSESSION_CHANGE});this._messagepump.parent=this;this._messagepump.on("exit",function(o){this.parent._wts.WTSUnRegisterSessionNotification(this.parent.hwnd)});this._messagepump.on("hwnd",function(o){this.parent.hwnd=o;this.immediate=setImmediate(function(p){if(p.parent._wts){p.parent._wts.WTSRegisterSessionNotification(p.parent.hwnd,NOTIFY_FOR_ALL_SESSIONS)}p.parent._user32.ACDC_H=p.parent._user32.RegisterPowerSettingNotification(p.parent.hwnd,GUID_ACDC_POWER_SOURCE,0);p.parent._user32.BATT_H=p.parent._user32.RegisterPowerSettingNotification(p.parent.hwnd,GUID_BATTERY_PERCENTAGE_REMAINING,0);p.parent._user32.DISP_H=p.parent._user32.RegisterPowerSettingNotification(p.parent.hwnd,GUID_CONSOLE_DISPLAY_STATE,0)},this)});this._messagepump.on("message",function(q){switch(q.message){case WM_WTSSESSION_CHANGE:switch(q.wparam){case WTS_SESSION_LOCK:this.parent.enumerateUsers().then(function(r){if(r[q.lparam]){this.parent.emit("locked",r[q.lparam])}});break;case WTS_SESSION_UNLOCK:this.parent.enumerateUsers().then(function(r){if(r[q.lparam]){this.parent.emit("unlocked",r[q.lparam])}});break;case WTS_SESSION_LOGON:case WTS_SESSION_LOGOFF:this.parent.emit("changed");break}break;case WM_POWERBROADCAST:switch(q.wparam){default:console.log("WM_POWERBROADCAST [UNKNOWN wparam]: "+q.wparam);break;case PBT_APMSUSPEND:require("power-monitor").emit("sx","SLEEP");break;case PBT_APMRESUMEAUTOMATIC:require("power-monitor").emit("sx","RESUME_NON_INTERACTIVE");break;case PBT_APMRESUMESUSPEND:require("power-monitor").emit("sx","RESUME_INTERACTIVE");break;case PBT_APMPOWERSTATUSCHANGE:require("power-monitor").emit("changed");break;case PBT_POWERSETTINGCHANGE:var p=this.parent._marshal.CreatePointer(Buffer.from(q.lparam_hex,"hex"));var o=p.Deref(20,p.Deref(16,4).toBuffer().readUInt32LE(0)).toBuffer();switch(p.Deref(0,16).toBuffer().toString("hex")){case GUID_ACDC_POWER_SOURCE.Deref(0,16).toBuffer().toString("hex"):switch(o.readUInt32LE(0)){case 0:require("power-monitor").emit("acdc","AC");break;case 1:require("power-monitor").emit("acdc","BATTERY");break;case 2:require("power-monitor").emit("acdc","HOT");break}break;case GUID_BATTERY_PERCENTAGE_REMAINING.Deref(0,16).toBuffer().toString("hex"):require("power-monitor").emit("batteryLevel",o.readUInt32LE(0));break;case GUID_CONSOLE_DISPLAY_STATE.Deref(0,16).toBuffer().toString("hex"):switch(o.readUInt32LE(0)){case 0:require("power-monitor").emit("display","OFF");break;case 1:require("power-monitor").emit("display","ON");break;case 2:require("power-monitor").emit("display","DIMMED");break}break}break}break;default:break}})}else{if(process.platform=="linux"){var g=require("linux-dbus");this._linuxWatcher=require("fs").watch("/var/run/utmp");this._linuxWatcher.user_session=this;this._linuxWatcher.on("change",function(o,p){this.user_session.emit("changed")});this._users=function d(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[0]]=s[1]}}return(r)};this._uids=function c(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[1]]=s[0]}}return(r)};this.Self=function m(){var q=require("promise");var o=new q(function(r,p){this.__resolver=r;this.__rejector=p;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u"]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(s){this._txt+=s.toString()});this.__child.on("exit",function(s){try{parseInt(this.stdout._txt)}catch(t){this.promise.__rejector("invalid uid");return}var u=parseInt(this.stdout._txt);this.promise.__resolver(u)})});return(o)};this.Current=function f(o){var p={};p._ObjectID="UserSession";Object.defineProperty(p,"_callback",{value:o});Object.defineProperty(p,"_child",{value:require("child_process").execFile("/usr/bin/last",["last","-f","/var/run/utmp"])});p._child.Parent=p;p._child._txt="";p._child.on("exit",function(q){var u=this._txt.split("\n");var A=[];var D={};for(var t in u){if(u[t]){var B=getTokens(u[t]);var z={Username:B[0],SessionId:B[1]};if(B[3].includes("still logged in")){z.State="Active"}else{z.LastActive=B[3]}A.push(z)}}A.pop();var C={};var y=[];for(var t in A){if(A[t].Username!="reboot"){D[A[t].SessionId]=A[t];if(C[A[t].Username]==null){C[A[t].Username]=-1}}}try{require("promise")}catch(r){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(this.Parent._callback){this.Parent._callback.call(this.Parent,D)}return}var x=require("promise");for(var v in C){var w=new x(function(E,s){this.__username=v;this.__resolver=E;this.__rejector=s;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u",v]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(F){this._txt+=F.toString()});this.__child.on("exit",function(F){try{parseInt(this.stdout._txt)}catch(G){this.promise.__rejector("invalid uid");return}var H=parseInt(this.stdout._txt);this.promise.__resolver(H)})});y.push(w)}x.all(y).then(function(E){var F={};for(var s in E){F[E[s].__username]=E[s]._internal.completedArgs[0]}for(var s in D){D[s].uid=F[D[s].Username]}Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}},function(s){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}})});p._child.stdout.Parent=p._child;p._child.stdout.on("data",function(q){this.Parent._txt+=q.toString()});return(p)};this._recheckLoggedInUsers=function a(){this.enumerateUsers().then(function(o){if(o.Active.length>0){if(this.parent._linux_lock_watcher!=null&&this.parent._linux_lock_watcher.uid!=o.Active[0].uid){delete this.parent._linux_lock_watcher}this.parent._linux_lock_watcher=new g(process.env.XDG_CURRENT_DESKTOP=="Unity"?"com.ubuntu.Upstart0_6":"org.gnome.ScreenSaver",o.Active[0].uid);this.parent._linux_lock_watcher.user_session=this.parent;this.parent._linux_lock_watcher.on("signal",function(r){var q=this.user_session.enumerateUsers();q.signalData=r.data[0];q.then(function(p){switch(this.signalData){case true:case"desktop-lock":this.parent.emit("locked",p.Active[0]);break;case false:case"desktop-unlock":this.parent.emit("unlocked",p.Active[0]);break}})})}else{if(this.parent._linux_lock_watcher!=null){delete this.parent._linux_lock_watcher}}})};this.on("changed",this._recheckLoggedInUsers);this._recheckLoggedInUsers()}else{if(process.platform=="darwin"){this._users=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p<q.length;++p){r=q[p].split(" ");if(r[0]){s[r[0]]=r[r.length-1]}}return(s)};this._uids=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p<q.length;++p){r=q[p].split(" ");if(r[0]){s[r[r.length-1]]=r[0]}}return(s)};this._idTable=function(){var v={};var o=require("child_process").execFile("/usr/bin/id",["id"]);o.stdout.str="";o.stdout.on("data",function(y){this.str+=y.toString()});o.waitExit();var t=o.stdout.str.split("\n")[0].split(" ");for(var p=0;p<t.length;++p){var x=t[p].split("=");var w=x[1].split(",");v[x[0]]={};for(var s in w){var r=w[s].split("(");var q=r[0];var u=r[1].substring(0,r[1].length-1).trim();v[x[0]][u]=q;v[x[0]][q]=u}}return(v)};this.Current=function(o){var u={};var t=this._idTable();var p=require("child_process").execFile("/usr/bin/last",["last"]);p.stdout.str="";p.stdout.on("data",function(v){this.str+=v.toString()});p.waitExit();var s=p.stdout.str.split("\n");for(var r=0;r<s.length&&s[r].length>0;++r){if(!u[s[r].split(" ")[0]]){try{u[s[r].split(" ")[0]]={Username:s[r].split(" ")[0],State:s[r].split("still logged in").length>1?"Active":"Inactive",uid:t.uid[s[r].split(" ")[0]]}}catch(q){}}else{if(u[s[r].split(" ")[0]].State!="Active"&&s[r].split("still logged in").length>1){u[s[r].split(" ")[0]].State="Active"}}}Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o.call(this,u)}}}}}if(process.platform=="linux"||process.platform=="darwin"){this._self=function b(){var o=require("child_process").execFile("/usr/bin/id",["id","-u"]);o.stdout.str="";o.stdout.on("data",function(p){this.str+=p.toString()});o.waitExit();return(parseInt(o.stdout.str))};this.isRoot=function k(){return(this._self()==0)};this.consoleUid=function e(){var o=process.platform=="darwin"?"console":((process.env.DISPLAY)?process.env.DISPLAY:":0");var p=require("child_process").execFile("/bin/sh",["sh"]);p.stdout.str="";p.stdout.on("data",function(u){this.str+=u.toString()});p.stdin.write("who\nexit\n");p.waitExit();var s=p.stdout.str.split("\n");var t,q,r;for(q in s){t=s[q].split(" ");for(r=1;r<t.length;++r){if(t[r].length>0&&(t[r]==o||t[r]==("("+o+")"))){return(parseInt(this._users()[t[0]]))}}}throw ("nobody logged into console")}}}function showActiveOnly(c){var b=[];var e={};var f=[];var d;for(var a in c){if(c[a].State=="Active"){b.push(c[a]);d=(c[a].Domain?(c[a].Domain+"\\"):"")+c[a].Username;if(!e[d]){e[d]=d}}}for(var a in e){f.push(a)}Object.defineProperty(b,"usernames",{value:f});return(b)}function getTokens(d){var a=[];var b;a.push(d.substring(0,(b=d.indexOf(" "))));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}var c=d.substring(b).trim();a.push(c);return(a)}module.exports=new UserSessions(); |