Clean up.

Ylian Saint-Hilaire committed Mar 15, 2019 at 13:56 UTC dfafc6372f25d7b8827aafd97370fa61cbbe24bc
8 files changed -2406
agents/modules_meshcmd/x/process-manager.js deleted
-163
@@ -1,163 +0,0 @@
1 -/*
2 -Copyright 2018-2019 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -
18 -var GM = require('_GenericMarshal');
19 -
20 -// Used on Windows and Linux to get information about running processes
21 -function processManager() {
22 - this._ObjectID = 'process-manager'; // Used for debugging, allows you to get the object type at runtime.
23 -
24 - // Setup the platform specific calls.
25 - switch (process.platform)
26 - {
27 - case 'win32':
28 - this._kernel32 = GM.CreateNativeProxy('kernel32.dll');
29 - this._kernel32.CreateMethod('GetLastError');
30 - this._kernel32.CreateMethod('CreateToolhelp32Snapshot');
31 - this._kernel32.CreateMethod('Process32First');
32 - this._kernel32.CreateMethod('Process32Next');
33 - break;
34 - case 'linux':
35 - case 'darwin':
36 - this._childProcess = require('child_process');
37 - break;
38 - default:
39 - throw (process.platform + ' not supported');
40 - break;
41 - }
42 - this.enumerateProcesses = function enumerateProcesses()
43 - {
44 - var promise = require('promise');
45 - var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
46 - this.getProcesses(function (ps, prom) { prom._res(ps); }, ret);
47 - return (ret);
48 - }
49 - // Return a object of: pid -> process information.
50 - this.getProcesses = function getProcesses(callback)
51 - {
52 - switch(process.platform)
53 - {
54 - default:
55 - throw ('Enumerating processes on ' + process.platform + ' not supported');
56 - break;
57 - case 'win32': // Windows processes
58 - var retVal = {};
59 - var h = this._kernel32.CreateToolhelp32Snapshot(2, 0);
60 - var info = GM.CreateVariable(304);
61 - info.toBuffer().writeUInt32LE(304, 0);
62 - var nextProcess = this._kernel32.Process32First(h, info);
63 - while (nextProcess.Val)
64 - {
65 - retVal[info.Deref(8, 4).toBuffer().readUInt32LE(0)] = { pid: info.Deref(8, 4).toBuffer().readUInt32LE(0), cmd: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String };
66 - nextProcess = this._kernel32.Process32Next(h, info);
67 - }
68 - if (callback) { callback.apply(this, [retVal]); }
69 - break;
70 - case 'linux': // Linux processes
71 - if (!this._psp) { this._psp = {}; }
72 - var p = this._childProcess.execFile("/bin/ps", ["ps", "-uxa"], { type: this._childProcess.SpawnTypes.TERM });
73 - this._psp[p.pid] = p;
74 - p.Parent = this;
75 - p.ps = '';
76 - p.callback = callback;
77 - p.args = [];
78 - for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
79 - p.on('exit', function onGetProcesses()
80 - {
81 - delete this.Parent._psp[this.pid];
82 - var retVal = {}, lines = this.ps.split('\x0D\x0A'), key = {}, keyi = 0;
83 - for (var i in lines)
84 - {
85 - var tokens = lines[i].split(' ');
86 - var tokenList = [];
87 - for(var x in tokens)
88 - {
89 - if (i == 0 && tokens[x]) { key[tokens[x]] = keyi++; }
90 - if (i > 0 && tokens[x]) { tokenList.push(tokens[x]);}
91 - }
92 - if (i > 0) {
93 - if (tokenList[key.PID]) { retVal[tokenList[key.PID]] = { pid: key.PID, user: tokenList[key.USER], cmd: tokenList[key.COMMAND] }; }
94 - }
95 - }
96 - if (this.callback)
97 - {
98 - this.args.unshift(retVal);
99 - this.callback.apply(this.parent, this.args);
100 - }
101 - });
102 - p.stdout.on('data', function (chunk) { this.parent.ps += chunk.toString(); });
103 - break;
104 - case 'darwin':
105 - var promise = require('promise');
106 - var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
107 - p.pm = this;
108 - p.callback = callback;
109 - p.args = [];
110 - for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
111 - p.child = this._childProcess.execFile("/bin/ps", ["ps", "-xa"]);
112 - p.child.promise = p;
113 - p.child.stdout.ps = '';
114 - p.child.stdout.on('data', function (chunk) { this.ps += chunk.toString(); });
115 - p.child.on('exit', function ()
116 - {
117 - var lines = this.stdout.ps.split('\n');
118 - var pidX = lines[0].split('PID')[0].length + 3;
119 - var cmdX = lines[0].split('CMD')[0].length;
120 - var ret = {};
121 - for (var i = 1; i < lines.length; ++i)
122 - {
123 - if (lines[i].length > 0)
124 - {
125 - ret[lines[i].substring(0, pidX).trim()] = { pid: lines[i].substring(0, pidX).trim(), cmd: lines[i].substring(cmdX) };
126 - }
127 - }
128 - this.promise._res(ret);
129 - });
130 - p.then(function (ps)
131 - {
132 - this.args.unshift(ps);
133 - this.callback.apply(this.pm, this.args);
134 - });
135 - break;
136 - }
137 - };
138 -
139 - // Get information about a specific process on Linux
140 - this.getProcessInfo = function getProcessInfo(pid)
141 - {
142 - switch(process.platform)
143 - {
144 - default:
145 - throw ('getProcessInfo() not supported for ' + process.platform);
146 - break;
147 - case 'linux':
148 - var status = require('fs').readFileSync('/proc/' + pid + '/status');
149 - var info = {};
150 - var lines = status.toString().split('\n');
151 - for(var i in lines)
152 - {
153 - var tokens = lines[i].split(':');
154 - if (tokens.length > 1) { tokens[1] = tokens[1].trim(); }
155 - info[tokens[0]] = tokens[1];
156 - }
157 - return (info);
158 - break;
159 - }
160 - };
161 -}
162 -
163 -module.exports = new processManager();
\ No newline at end of file
agents/modules_meshcore/x/clipboard.js deleted
-178
@@ -1,178 +0,0 @@
1 -/*
2 -Copyright 2019 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -var promise = require('promise');
18 -
19 -function nativeAddModule(name)
20 -{
21 - var value = getJSModule(name);
22 - var ret = "duk_peval_string_noresult(ctx, \"addModule('" + name + "', Buffer.from('" + Buffer.from(value).toString('base64') + "', 'base64').toString());\");";
23 - module.exports(ret);
24 -}
25 -
26 -function lin_readtext()
27 -{
28 - var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
29 - try
30 - {
31 - require('monitor-info')
32 - }
33 - catch(exc)
34 - {
35 - ret._rej(exc);
36 - return (ret);
37 - }
38 -
39 - var X11 = require('monitor-info')._X11;
40 - if (!X11)
41 - {
42 - ret._rej('X11 required for Clipboard Manipulation');
43 - }
44 - else
45 - {
46 - var SelectionNotify = 31;
47 - var AnyPropertyType = 0;
48 - var GM = require('monitor-info')._gm;
49 -
50 - ret._getInfoPromise = require('monitor-info').getInfo();
51 - ret._getInfoPromise._masterPromise = ret;
52 - ret._getInfoPromise.then(function (mon)
53 - {
54 - if (mon.length > 0)
55 - {
56 - var white = X11.XWhitePixel(mon[0].display, mon[0].screenId).Val;
57 -
58 - this._masterPromise.CLIPID = X11.XInternAtom(mon[0].display, GM.CreateVariable('CLIPBOARD'), 0);
59 - this._masterPromise.FMTID = X11.XInternAtom(mon[0].display, GM.CreateVariable('UTF8_STRING'), 0);
60 - this._masterPromise.PROPID = X11.XInternAtom(mon[0].display, GM.CreateVariable('XSEL_DATA'), 0);
61 - this._masterPromise.INCRID = X11.XInternAtom(mon[0].display, GM.CreateVariable('INCR'), 0);
62 - this._masterPromise.ROOTWIN = X11.XRootWindow(mon[0].display, mon[0].screenId);
63 - this._masterPromise.FAKEWIN = X11.XCreateSimpleWindow(mon[0].display, this._masterPromise.ROOTWIN, 0, 0, mon[0].right, 5, 0, white, white);
64 -
65 - X11.XSync(mon[0].display, 0);
66 - X11.XConvertSelection(mon[0].display, this._masterPromise.CLIPID, this._masterPromise.FMTID, this._masterPromise.PROPID, this._masterPromise.FAKEWIN, 0);
67 - X11.XSync(mon[0].display, 0);
68 -
69 - this._masterPromise.DescriptorEvent = require('DescriptorEvents').addDescriptor(X11.XConnectionNumber(mon[0].display).Val, { readset: true });
70 - this._masterPromise.DescriptorEvent._masterPromise = this._masterPromise;
71 - this._masterPromise.DescriptorEvent._display = mon[0].display;
72 - this._masterPromise.DescriptorEvent.on('readset', function (fd)
73 - {
74 - var XE = GM.CreateVariable(1024);
75 - while (X11.XPending(this._display).Val)
76 - {
77 - X11.XNextEventSync(this._display, XE);
78 - if(XE.Deref(0, 4).toBuffer().readUInt32LE() == SelectionNotify)
79 - {
80 - var id = GM.CreatePointer();
81 - var bits = GM.CreatePointer();
82 - var sz = GM.CreatePointer();
83 - var tail = GM.CreatePointer();
84 - var result = GM.CreatePointer();
85 -
86 - X11.XGetWindowProperty(this._display, this._masterPromise.FAKEWIN, this._masterPromise.PROPID, 0, 65535, 0, AnyPropertyType, id, bits, sz, tail, result);
87 - this._masterPromise._res(result.Deref().String);
88 - X11.XFree(result.Deref());
89 - X11.XDestroyWindow(this._display, this._masterPromise.FAKEWIN);
90 -
91 - this.removeDescriptor(fd);
92 - break;
93 - }
94 - }
95 - });
96 - }
97 - });
98 - }
99 - return (ret);
100 -}
101 -function lin_copytext()
102 -{
103 -}
104 -
105 -function win_readtext()
106 -{
107 - var ret = '';
108 - var CF_TEXT = 1;
109 - var GM = require('_GenericMarshal');
110 - var user32 = GM.CreateNativeProxy('user32.dll');
111 - var kernel32 = GM.CreateNativeProxy('kernel32.dll');
112 - kernel32.CreateMethod('GlobalAlloc');
113 - kernel32.CreateMethod('GlobalLock');
114 - kernel32.CreateMethod('GlobalUnlock');
115 - user32.CreateMethod('OpenClipboard');
116 - user32.CreateMethod('CloseClipboard');
117 - user32.CreateMethod('GetClipboardData');
118 -
119 - user32.OpenClipboard(0);
120 - var h = user32.GetClipboardData(CF_TEXT);
121 - if(h.Val!=0)
122 - {
123 - var hbuffer = kernel32.GlobalLock(h);
124 - ret = hbuffer.String;
125 - kernel32.GlobalUnlock(h);
126 - }
127 - user32.CloseClipboard();
128 -
129 - var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
130 - p._res(ret);
131 - return (p);
132 -}
133 -
134 -function win_copytext(txt)
135 -{
136 - var GMEM_MOVEABLE = 0x0002;
137 - var CF_TEXT = 1;
138 -
139 - var GM = require('_GenericMarshal');
140 - var user32 = GM.CreateNativeProxy('user32.dll');
141 - var kernel32 = GM.CreateNativeProxy('kernel32.dll');
142 - kernel32.CreateMethod('GlobalAlloc');
143 - kernel32.CreateMethod('GlobalLock');
144 - kernel32.CreateMethod('GlobalUnlock');
145 - user32.CreateMethod('OpenClipboard');
146 - user32.CreateMethod('EmptyClipboard');
147 - user32.CreateMethod('CloseClipboard');
148 - user32.CreateMethod('SetClipboardData');
149 -
150 - var h = kernel32.GlobalAlloc(GMEM_MOVEABLE, txt.length + 2);
151 - h.autoFree(false);
152 - var hbuffer = kernel32.GlobalLock(h);
153 - hbuffer.autoFree(false);
154 - var tmp = Buffer.alloc(txt.length + 1);
155 - Buffer.from(txt).copy(tmp);
156 - tmp.copy(hbuffer.Deref(0, txt.length + 1).toBuffer());
157 - kernel32.GlobalUnlock(h);
158 -
159 - user32.OpenClipboard(0);
160 - user32.EmptyClipboard();
161 - user32.SetClipboardData(CF_TEXT, h);
162 - user32.CloseClipboard();
163 -}
164 -
165 -switch(process.platform)
166 -{
167 - case 'win32':
168 - module.exports = win_copytext;
169 - module.exports.read = win_readtext;
170 - break;
171 - case 'linux':
172 - module.exports = lin_copytext;
173 - module.exports.read = lin_readtext;
174 - break;
175 - case 'darwin':
176 - break;
177 -}
178 -module.exports.nativeAddModule = nativeAddModule;
\ No newline at end of file
agents/modules_meshcore/x/monitor-info.js deleted
-313
@@ -1,313 +0,0 @@
1 -/*
2 -Copyright 2018 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -var promise = require('promise');
18 -var PPosition = 4;
19 -var PSize = 8;
20 -var _NET_WM_STATE_REMOVE = 0; // remove/unset property
21 -var _NET_WM_STATE_ADD = 1; // add/set property
22 -var _NET_WM_STATE_TOGGLE = 2; // toggle property
23 -var SubstructureRedirectMask = (1 << 20);
24 -var SubstructureNotifyMask = (1 << 19);
25 -
26 -function getLibInfo(libname)
27 -{
28 - if (process.platform != 'linux') { throw ('Only supported on linux'); }
29 -
30 - var child = require('child_process').execFile('/bin/sh', ['sh']);
31 - child.stdout.str = '';
32 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
33 - child.stdin.write("ldconfig -p | grep '" + libname + ".so.'\nexit\n");
34 - child.waitExit();
35 -
36 - var v = [];
37 - var lines = child.stdout.str.split('\n');
38 - for (var i in lines) {
39 - if (lines[i]) {
40 - var info = lines[i].split('=>');
41 - var pth = info[1].trim();
42 - var libinfo = info[0].trim().split(' ');
43 - var lib = libinfo[0];
44 - var plat = libinfo[1].substring(1, libinfo[1].length - 1).split(',');
45 -
46 - if (lib.startsWith(libname + '.so.')) {
47 - v.push({ lib: lib, path: pth, info: plat });
48 - }
49 - }
50 - }
51 - return (v);
52 -}
53 -
54 -function monitorinfo()
55 -{
56 - this._ObjectID = 'monitor-info';
57 - this._gm = require('_GenericMarshal');
58 -
59 - if (process.platform == 'win32')
60 - {
61 - this._user32 = this._gm.CreateNativeProxy('user32.dll');
62 - this._user32.CreateMethod('EnumDisplayMonitors');
63 - this._kernel32 = this._gm.CreateNativeProxy('kernel32.dll');
64 - this._kernel32.CreateMethod('GetLastError');
65 -
66 - this.getInfo = function getInfo()
67 - {
68 - var info = this;
69 - return (new promise(function (resolver, rejector) {
70 - this._monitorinfo = { resolver: resolver, rejector: rejector, self: info, callback: info._gm.GetGenericGlobalCallback(4) };
71 - this._monitorinfo.callback.info = this._monitorinfo;
72 - this._monitorinfo.dwData = info._gm.ObjectToPtr(this._monitorinfo);
73 -
74 - this._monitorinfo.callback.results = [];
75 - this._monitorinfo.callback.on('GlobalCallback', function OnMonitorInfo(hmon, hdc, r, user) {
76 - if (this.ObjectToPtr_Verify(this.info, user)) {
77 - var rb = r.Deref(0, 16).toBuffer();
78 - this.results.push({ left: rb.readInt32LE(0), top: rb.readInt32LE(4), right: rb.readInt32LE(8), bottom: rb.readInt32LE(12) });
79 -
80 - var r = this.info.self._gm.CreateInteger();
81 - r.Val = 1;
82 - return (r);
83 - }
84 - });
85 -
86 - if (info._user32.EnumDisplayMonitors(0, 0, this._monitorinfo.callback, this._monitorinfo.dwData).Val == 0) {
87 - rejector('LastError=' + info._kernel32.GetLastError().Val);
88 - return;
89 - }
90 - else {
91 - resolver(this._monitorinfo.callback.results);
92 - }
93 -
94 - }));
95 - }
96 - }
97 - else if(process.platform == 'linux')
98 - {
99 - // First thing we need to do, is determine where the X11 libraries are
100 - var askOS = false;
101 - try
102 - {
103 - if (require('user-sessions').isRoot()) { askOS = true; }
104 - }
105 - catch (e)
106 - { }
107 -
108 - if (askOS)
109 - {
110 - // Sufficient access rights to use ldconfig
111 - var x11info = getLibInfo('libX11');
112 - var xtstinfo = getLibInfo('libXtst');
113 - var xextinfo = getLibInfo('libXext');
114 - var ix;
115 -
116 - for(ix in x11info)
117 - {
118 - try
119 - {
120 - this._gm.CreateNativeProxy(x11info[ix].path);
121 - Object.defineProperty(this, 'Location_X11LIB', { value: x11info[ix].path });
122 - break;
123 - }
124 - catch(ex)
125 - {
126 - }
127 - }
128 - for (ix in xtstinfo)
129 - {
130 - try
131 - {
132 - this._gm.CreateNativeProxy(xtstinfo[ix].path);
133 - Object.defineProperty(this, 'Location_X11TST', { value: xtstinfo[ix].path });
134 - break;
135 - }
136 - catch (ex)
137 - {
138 - }
139 - }
140 - for (ix in xextinfo)
141 - {
142 - try
143 - {
144 - this._gm.CreateNativeProxy(xextinfo[ix].path);
145 - Object.defineProperty(this, 'Location_X11EXT', { value: xextinfo[ix].path });
146 - break;
147 - }
148 - catch (ex)
149 - {
150 - }
151 - }
152 - }
153 - else
154 - {
155 - // Not enough access rights to use ldconfig, so manually search
156 - var fs = require('fs');
157 - var files = fs.readdirSync('/usr/lib');
158 - var files2;
159 -
160 - for (var i in files) {
161 - try {
162 - if (files[i].split('libX11.so.').length > 1 && files[i].split('.').length == 3) {
163 - Object.defineProperty(this, 'Location_X11LIB', { value: '/usr/lib/' + files[i] });
164 - }
165 - if (files[i].split('libXtst.so.').length > 1 && files[i].split('.').length == 3) {
166 - Object.defineProperty(this, 'Location_X11TST', { value: '/usr/lib/' + files[i] });
167 - }
168 - if (files[i].split('libXext.so.').length > 1 && files[i].split('.').length == 3) {
169 - Object.defineProperty(this, 'Location_X11EXT', { value: '/usr/lib/' + files[i] });
170 - }
171 -
172 - if (files[i].split('-linux-').length > 1) {
173 - files2 = fs.readdirSync('/usr/lib/' + files[i]);
174 - for (j in files2) {
175 - if (files2[j].split('libX11.so.').length > 1 && files2[j].split('.').length == 3) {
176 - Object.defineProperty(this, 'Location_X11LIB', { value: '/usr/lib/' + files[i] + '/' + files2[j] });
177 - }
178 - if (files2[j].split('libXtst.so.').length > 1 && files2[j].split('.').length == 3) {
179 - Object.defineProperty(this, 'Location_X11TST', { value: '/usr/lib/' + files[i] + '/' + files2[j] });
180 - }
181 - if (files2[j].split('libXext.so.').length > 1 && files2[j].split('.').length == 3) {
182 - Object.defineProperty(this, 'Location_X11EXT', { value: '/usr/lib/' + files[i] + '/' + files2[j] });
183 - }
184 - }
185 - }
186 - } catch (ex) { }
187 - }
188 - }
189 - Object.defineProperty(this, 'kvm_x11_support', { value: (this.Location_X11LIB && this.Location_X11TST && this.Location_X11EXT)?true:false });
190 -
191 - if (this.Location_X11LIB)
192 - {
193 - this._X11 = this._gm.CreateNativeProxy(this.Location_X11LIB);
194 - this._X11.CreateMethod('XChangeProperty');
195 - this._X11.CreateMethod('XCloseDisplay');
196 - this._X11.CreateMethod('XConnectionNumber');
197 - this._X11.CreateMethod('XConvertSelection');
198 - this._X11.CreateMethod('XCreateGC');
199 - this._X11.CreateMethod('XCreateWindow');
200 - this._X11.CreateMethod('XCreateSimpleWindow');
201 - this._X11.CreateMethod('XDefaultColormap');
202 - this._X11.CreateMethod('XDefaultScreen');
203 - this._X11.CreateMethod('XDestroyWindow');
204 - this._X11.CreateMethod('XDrawLine');
205 - this._X11.CreateMethod('XDisplayHeight');
206 - this._X11.CreateMethod('XDisplayWidth');
207 - this._X11.CreateMethod('XFetchName');
208 - this._X11.CreateMethod('XFlush');
209 - this._X11.CreateMethod('XFree');
210 - this._X11.CreateMethod('XCreateGC');
211 - this._X11.CreateMethod('XGetWindowProperty');
212 - this._X11.CreateMethod('XInternAtom');
213 - this._X11.CreateMethod('XMapWindow');
214 - this._X11.CreateMethod({ method: 'XNextEvent', threadDispatch: true });
215 - this._X11.CreateMethod({ method: 'XNextEvent', newName: 'XNextEventSync' });
216 - this._X11.CreateMethod('XOpenDisplay');
217 - this._X11.CreateMethod('XPending');
218 - this._X11.CreateMethod('XRootWindow');
219 - this._X11.CreateMethod('XSelectInput');
220 - this._X11.CreateMethod('XScreenCount');
221 - this._X11.CreateMethod('XScreenOfDisplay');
222 - this._X11.CreateMethod('XSelectInput');
223 - this._X11.CreateMethod('XSendEvent');
224 - this._X11.CreateMethod('XSetForeground');
225 - this._X11.CreateMethod('XSetFunction');
226 - this._X11.CreateMethod('XSetLineAttributes');
227 - this._X11.CreateMethod('XSetNormalHints');
228 - this._X11.CreateMethod('XSetSubwindowMode');
229 - this._X11.CreateMethod('XSync');
230 - this._X11.CreateMethod('XBlackPixel');
231 - this._X11.CreateMethod('XWhitePixel');
232 - }
233 -
234 - this.isUnity = function isUnity()
235 - {
236 - return (process.env['XDG_CURRENT_DESKTOP'] == 'Unity');
237 - }
238 -
239 - this.unDecorateWindow = function unDecorateWindow(display, window)
240 - {
241 - var MwmHints = this._gm.CreateVariable(40);
242 - var mwmHintsProperty = this._X11.XInternAtom(display, this._gm.CreateVariable('_MOTIF_WM_HINTS'), 0);
243 - MwmHints.Deref(0, 4).toBuffer().writeUInt32LE(1 << 1);
244 - this._X11.XChangeProperty(display, window, mwmHintsProperty, mwmHintsProperty, 32, 0, MwmHints, 5);
245 - }
246 - this.setWindowSizeHints = function setWindowSizeHints(display, window, x, y, width, height)
247 - {
248 - var sizeHints = this._gm.CreateVariable(80);
249 - sizeHints.Deref(0, 4).toBuffer().writeUInt32LE(PPosition | PSize);
250 - sizeHints.Deref(8, 4).toBuffer().writeUInt32LE(x);
251 - sizeHints.Deref(12, 4).toBuffer().writeUInt32LE(y);
252 - sizeHints.Deref(16, 4).toBuffer().writeUInt32LE(width);
253 - sizeHints.Deref(20, 4).toBuffer().writeUInt32LE(height);
254 - this._X11.XSetNormalHints(display, window, sizeHints);
255 - }
256 - this.setAlwaysOnTop = function setAlwaysOnTop(display, rootWindow, window)
257 - {
258 - var wmNetWmState = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE'), 1);
259 - var wmStateAbove = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE_ABOVE'), 1);
260 -
261 - var xclient = this._gm.CreateVariable(96);
262 - xclient.Deref(0, 4).toBuffer().writeUInt32LE(33); // ClientMessage type
263 - xclient.Deref(48, 4).toBuffer().writeUInt32LE(32); // Format 32
264 - wmNetWmState.pointerBuffer().copy(xclient.Deref(40, 8).toBuffer()); // message_type
265 - xclient.Deref(56, 8).toBuffer().writeUInt32LE(_NET_WM_STATE_ADD); // data.l[0]
266 - wmStateAbove.pointerBuffer().copy(xclient.Deref(64, 8).toBuffer()); // data.l[1]
267 -
268 - window.pointerBuffer().copy(xclient.Deref(32, 8).toBuffer()); // window
269 - this._X11.XSendEvent(display, rootWindow, 0, SubstructureRedirectMask | SubstructureNotifyMask, xclient);
270 - }
271 - this.hideWindowIcon = function hideWindowIcon(display, rootWindow, window)
272 - {
273 - var wmNetWmState = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE'), 1);
274 - var wmStateSkip = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE_SKIP_TASKBAR'), 1);
275 -
276 - var xclient = this._gm.CreateVariable(96);
277 - xclient.Deref(0, 4).toBuffer().writeUInt32LE(33); // ClientMessage type
278 - xclient.Deref(48, 4).toBuffer().writeUInt32LE(32); // Format 32
279 - wmNetWmState.pointerBuffer().copy(xclient.Deref(40, 8).toBuffer()); // message_type
280 - xclient.Deref(56, 8).toBuffer().writeUInt32LE(_NET_WM_STATE_ADD); // data.l[0]
281 - wmStateSkip.pointerBuffer().copy(xclient.Deref(64, 8).toBuffer()); // data.l[1]
282 -
283 - window.pointerBuffer().copy(xclient.Deref(32, 8).toBuffer()); // window
284 - this._X11.XSendEvent(display, rootWindow, 0, SubstructureRedirectMask | SubstructureNotifyMask, xclient);
285 - }
286 -
287 - this.getInfo = function getInfo()
288 - {
289 - var info = this;
290 - return (new promise(function (resolver, rejector)
291 - {
292 - var display = info._X11.XOpenDisplay(info._gm.CreateVariable(':0'));
293 - var screenCount = info._X11.XScreenCount(display).Val;
294 - var ret = [];
295 - for(var i=0;i<screenCount;++i)
296 - {
297 - var screen = info._X11.XScreenOfDisplay(display, i);
298 - ret.push({ left: 0, top: 0, right: info._X11.XDisplayWidth(display, i).Val, bottom: info._X11.XDisplayHeight(display, i).Val, screen: screen, screenId: i, display: display });
299 - }
300 - resolver(ret);
301 - }));
302 - }
303 - }
304 - else
305 - {
306 - throw (process.platform + ' not supported');
307 - }
308 -}
309 -
310 -module.exports = new monitorinfo();
311 -
312 -
313 -
agents/modules_meshcore/x/process-manager.js deleted
-163
@@ -1,163 +0,0 @@
1 -/*
2 -Copyright 2018-2019 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -
18 -var GM = require('_GenericMarshal');
19 -
20 -// Used on Windows and Linux to get information about running processes
21 -function processManager() {
22 - this._ObjectID = 'process-manager'; // Used for debugging, allows you to get the object type at runtime.
23 -
24 - // Setup the platform specific calls.
25 - switch (process.platform)
26 - {
27 - case 'win32':
28 - this._kernel32 = GM.CreateNativeProxy('kernel32.dll');
29 - this._kernel32.CreateMethod('GetLastError');
30 - this._kernel32.CreateMethod('CreateToolhelp32Snapshot');
31 - this._kernel32.CreateMethod('Process32First');
32 - this._kernel32.CreateMethod('Process32Next');
33 - break;
34 - case 'linux':
35 - case 'darwin':
36 - this._childProcess = require('child_process');
37 - break;
38 - default:
39 - throw (process.platform + ' not supported');
40 - break;
41 - }
42 - this.enumerateProcesses = function enumerateProcesses()
43 - {
44 - var promise = require('promise');
45 - var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
46 - this.getProcesses(function (ps, prom) { prom._res(ps); }, ret);
47 - return (ret);
48 - }
49 - // Return a object of: pid -> process information.
50 - this.getProcesses = function getProcesses(callback)
51 - {
52 - switch(process.platform)
53 - {
54 - default:
55 - throw ('Enumerating processes on ' + process.platform + ' not supported');
56 - break;
57 - case 'win32': // Windows processes
58 - var retVal = {};
59 - var h = this._kernel32.CreateToolhelp32Snapshot(2, 0);
60 - var info = GM.CreateVariable(304);
61 - info.toBuffer().writeUInt32LE(304, 0);
62 - var nextProcess = this._kernel32.Process32First(h, info);
63 - while (nextProcess.Val)
64 - {
65 - retVal[info.Deref(8, 4).toBuffer().readUInt32LE(0)] = { pid: info.Deref(8, 4).toBuffer().readUInt32LE(0), cmd: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String };
66 - nextProcess = this._kernel32.Process32Next(h, info);
67 - }
68 - if (callback) { callback.apply(this, [retVal]); }
69 - break;
70 - case 'linux': // Linux processes
71 - if (!this._psp) { this._psp = {}; }
72 - var p = this._childProcess.execFile("/bin/ps", ["ps", "-uxa"], { type: this._childProcess.SpawnTypes.TERM });
73 - this._psp[p.pid] = p;
74 - p.Parent = this;
75 - p.ps = '';
76 - p.callback = callback;
77 - p.args = [];
78 - for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
79 - p.on('exit', function onGetProcesses()
80 - {
81 - delete this.Parent._psp[this.pid];
82 - var retVal = {}, lines = this.ps.split('\x0D\x0A'), key = {}, keyi = 0;
83 - for (var i in lines)
84 - {
85 - var tokens = lines[i].split(' ');
86 - var tokenList = [];
87 - for(var x in tokens)
88 - {
89 - if (i == 0 && tokens[x]) { key[tokens[x]] = keyi++; }
90 - if (i > 0 && tokens[x]) { tokenList.push(tokens[x]);}
91 - }
92 - if (i > 0) {
93 - if (tokenList[key.PID]) { retVal[tokenList[key.PID]] = { pid: key.PID, user: tokenList[key.USER], cmd: tokenList[key.COMMAND] }; }
94 - }
95 - }
96 - if (this.callback)
97 - {
98 - this.args.unshift(retVal);
99 - this.callback.apply(this.parent, this.args);
100 - }
101 - });
102 - p.stdout.on('data', function (chunk) { this.parent.ps += chunk.toString(); });
103 - break;
104 - case 'darwin':
105 - var promise = require('promise');
106 - var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
107 - p.pm = this;
108 - p.callback = callback;
109 - p.args = [];
110 - for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
111 - p.child = this._childProcess.execFile("/bin/ps", ["ps", "-xa"]);
112 - p.child.promise = p;
113 - p.child.stdout.ps = '';
114 - p.child.stdout.on('data', function (chunk) { this.ps += chunk.toString(); });
115 - p.child.on('exit', function ()
116 - {
117 - var lines = this.stdout.ps.split('\n');
118 - var pidX = lines[0].split('PID')[0].length + 3;
119 - var cmdX = lines[0].split('CMD')[0].length;
120 - var ret = {};
121 - for (var i = 1; i < lines.length; ++i)
122 - {
123 - if (lines[i].length > 0)
124 - {
125 - ret[lines[i].substring(0, pidX).trim()] = { pid: lines[i].substring(0, pidX).trim(), cmd: lines[i].substring(cmdX) };
126 - }
127 - }
128 - this.promise._res(ret);
129 - });
130 - p.then(function (ps)
131 - {
132 - this.args.unshift(ps);
133 - this.callback.apply(this.pm, this.args);
134 - });
135 - break;
136 - }
137 - };
138 -
139 - // Get information about a specific process on Linux
140 - this.getProcessInfo = function getProcessInfo(pid)
141 - {
142 - switch(process.platform)
143 - {
144 - default:
145 - throw ('getProcessInfo() not supported for ' + process.platform);
146 - break;
147 - case 'linux':
148 - var status = require('fs').readFileSync('/proc/' + pid + '/status');
149 - var info = {};
150 - var lines = status.toString().split('\n');
151 - for(var i in lines)
152 - {
153 - var tokens = lines[i].split(':');
154 - if (tokens.length > 1) { tokens[1] = tokens[1].trim(); }
155 - info[tokens[0]] = tokens[1];
156 - }
157 - return (info);
158 - break;
159 - }
160 - };
161 -}
162 -
163 -module.exports = new processManager();
\ No newline at end of file
agents/modules_meshcore/x/service-manager.js deleted
-497
@@ -1,497 +0,0 @@
1 -/*
2 -Copyright 2018 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -function parseServiceStatus(token)
18 -{
19 - var j = {};
20 - var serviceType = token.Deref(0, 4).IntVal;
21 - j.isFileSystemDriver = ((serviceType & 0x00000002) == 0x00000002);
22 - j.isKernelDriver = ((serviceType & 0x00000001) == 0x00000001);
23 - j.isSharedProcess = ((serviceType & 0x00000020) == 0x00000020);
24 - j.isOwnProcess = ((serviceType & 0x00000010) == 0x00000010);
25 - j.isInteractive = ((serviceType & 0x00000100) == 0x00000100);
26 - switch (token.Deref((1 * 4), 4).toBuffer().readUInt32LE())
27 - {
28 - case 0x00000005:
29 - j.state = 'CONTINUE_PENDING';
30 - break;
31 - case 0x00000006:
32 - j.state = 'PAUSE_PENDING';
33 - break;
34 - case 0x00000007:
35 - j.state = 'PAUSED';
36 - break;
37 - case 0x00000004:
38 - j.state = 'RUNNING';
39 - break;
40 - case 0x00000002:
41 - j.state = 'START_PENDING';
42 - break;
43 - case 0x00000003:
44 - j.state = 'STOP_PENDING';
45 - break;
46 - case 0x00000001:
47 - j.state = 'STOPPED';
48 - break;
49 - }
50 - var controlsAccepted = token.Deref((2 * 4), 4).toBuffer().readUInt32LE();
51 - j.controlsAccepted = [];
52 - if ((controlsAccepted & 0x00000010) == 0x00000010)
53 - {
54 - j.controlsAccepted.push('SERVICE_CONTROL_NETBINDADD');
55 - j.controlsAccepted.push('SERVICE_CONTROL_NETBINDREMOVE');
56 - j.controlsAccepted.push('SERVICE_CONTROL_NETBINDENABLE');
57 - j.controlsAccepted.push('SERVICE_CONTROL_NETBINDDISABLE');
58 - }
59 - if ((controlsAccepted & 0x00000008) == 0x00000008) { j.controlsAccepted.push('SERVICE_CONTROL_PARAMCHANGE'); }
60 - if ((controlsAccepted & 0x00000002) == 0x00000002) { j.controlsAccepted.push('SERVICE_CONTROL_PAUSE'); j.controlsAccepted.push('SERVICE_CONTROL_CONTINUE'); }
61 - if ((controlsAccepted & 0x00000100) == 0x00000100) { j.controlsAccepted.push('SERVICE_CONTROL_PRESHUTDOWN'); }
62 - if ((controlsAccepted & 0x00000004) == 0x00000004) { j.controlsAccepted.push('SERVICE_CONTROL_SHUTDOWN'); }
63 - if ((controlsAccepted & 0x00000001) == 0x00000001) { j.controlsAccepted.push('SERVICE_CONTROL_STOP'); }
64 - if ((controlsAccepted & 0x00000020) == 0x00000020) { j.controlsAccepted.push('SERVICE_CONTROL_HARDWAREPROFILECHANGE'); }
65 - if ((controlsAccepted & 0x00000040) == 0x00000040) { j.controlsAccepted.push('SERVICE_CONTROL_POWEREVENT'); }
66 - if ((controlsAccepted & 0x00000080) == 0x00000080) { j.controlsAccepted.push('SERVICE_CONTROL_SESSIONCHANGE'); }
67 - j.pid = token.Deref((7 * 4), 4).toBuffer().readUInt32LE();
68 - return (j);
69 -}
70 -
71 -function serviceManager()
72 -{
73 - this._ObjectID = 'service-manager';
74 - if (process.platform == 'win32')
75 - {
76 - this.GM = require('_GenericMarshal');
77 - this.proxy = this.GM.CreateNativeProxy('Advapi32.dll');
78 - this.proxy.CreateMethod('OpenSCManagerA');
79 - this.proxy.CreateMethod('EnumServicesStatusExA');
80 - this.proxy.CreateMethod('OpenServiceA');
81 - this.proxy.CreateMethod('QueryServiceStatusEx');
82 - this.proxy.CreateMethod('ControlService');
83 - this.proxy.CreateMethod('StartServiceA');
84 - this.proxy.CreateMethod('CloseServiceHandle');
85 - this.proxy.CreateMethod('CreateServiceA');
86 - this.proxy.CreateMethod('ChangeServiceConfig2A');
87 - this.proxy.CreateMethod('DeleteService');
88 - this.proxy.CreateMethod('AllocateAndInitializeSid');
89 - this.proxy.CreateMethod('CheckTokenMembership');
90 - this.proxy.CreateMethod('FreeSid');
91 -
92 - this.proxy2 = this.GM.CreateNativeProxy('Kernel32.dll');
93 - this.proxy2.CreateMethod('GetLastError');
94 -
95 - this.isAdmin = function isAdmin() {
96 - var NTAuthority = this.GM.CreateVariable(6);
97 - NTAuthority.toBuffer().writeInt8(5, 5);
98 - var AdministratorsGroup = this.GM.CreatePointer();
99 - var admin = false;
100 -
101 - if (this.proxy.AllocateAndInitializeSid(NTAuthority, 2, 32, 544, 0, 0, 0, 0, 0, 0, AdministratorsGroup).Val != 0)
102 - {
103 - var member = this.GM.CreateInteger();
104 - if (this.proxy.CheckTokenMembership(0, AdministratorsGroup.Deref(), member).Val != 0)
105 - {
106 - if (member.toBuffer().readUInt32LE() != 0) { admin = true; }
107 - }
108 - this.proxy.FreeSid(AdministratorsGroup.Deref());
109 - }
110 - return admin;
111 - };
112 - this.getProgramFolder = function getProgramFolder()
113 - {
114 - if (require('os').arch() == 'x64')
115 - {
116 - // 64 bit Windows
117 - if (this.GM.PointerSize == 4)
118 - {
119 - return process.env['ProgramFiles(x86)']; // 32 Bit App
120 - }
121 - return process.env['ProgramFiles']; // 64 bit App
122 - }
123 -
124 - // 32 bit Windows
125 - return process.env['ProgramFiles'];
126 - };
127 - this.getServiceFolder = function getServiceFolder() { return this.getProgramFolder() + '\\mesh'; };
128 -
129 - this.enumerateService = function () {
130 - var machineName = this.GM.CreatePointer();
131 - var dbName = this.GM.CreatePointer();
132 - var handle = this.proxy.OpenSCManagerA(0x00, 0x00, 0x0001 | 0x0004);
133 -
134 - var bytesNeeded = this.GM.CreatePointer();
135 - var servicesReturned = this.GM.CreatePointer();
136 - var resumeHandle = this.GM.CreatePointer();
137 - //var services = this.proxy.CreateVariable(262144);
138 - var success = this.proxy.EnumServicesStatusExA(handle, 0, 0x00000030, 0x00000003, 0x00, 0x00, bytesNeeded, servicesReturned, resumeHandle, 0x00);
139 - if (bytesNeeded.IntVal <= 0) {
140 - throw ('error enumerating services');
141 - }
142 - var sz = bytesNeeded.IntVal;
143 - var services = this.GM.CreateVariable(sz);
144 - this.proxy.EnumServicesStatusExA(handle, 0, 0x00000030, 0x00000003, services, sz, bytesNeeded, servicesReturned, resumeHandle, 0x00);
145 - console.log("servicesReturned", servicesReturned.IntVal);
146 -
147 - var ptrSize = dbName._size;
148 - var blockSize = 36 + (2 * ptrSize);
149 - blockSize += ((ptrSize - (blockSize % ptrSize)) % ptrSize);
150 - var retVal = [];
151 - for (var i = 0; i < servicesReturned.IntVal; ++i) {
152 - var token = services.Deref(i * blockSize, blockSize);
153 - var j = {};
154 - j.name = token.Deref(0, ptrSize).Deref().String;
155 - j.displayName = token.Deref(ptrSize, ptrSize).Deref().String;
156 - j.status = parseServiceStatus(token.Deref(2 * ptrSize, 36));
157 - retVal.push(j);
158 - }
159 - this.proxy.CloseServiceHandle(handle);
160 - return (retVal);
161 - }
162 - this.getService = function (name) {
163 - var serviceName = this.GM.CreateVariable(name);
164 - var ptr = this.GM.CreatePointer();
165 - var bytesNeeded = this.GM.CreateVariable(ptr._size);
166 - var handle = this.proxy.OpenSCManagerA(0x00, 0x00, 0x0001 | 0x0004 | 0x0020 | 0x0010);
167 - if (handle.Val == 0) { throw ('could not open ServiceManager'); }
168 - var h = this.proxy.OpenServiceA(handle, serviceName, 0x0004 | 0x0020 | 0x0010 | 0x00010000);
169 - if (h.Val != 0) {
170 - var success = this.proxy.QueryServiceStatusEx(h, 0, 0, 0, bytesNeeded);
171 - var status = this.GM.CreateVariable(bytesNeeded.toBuffer().readUInt32LE());
172 - success = this.proxy.QueryServiceStatusEx(h, 0, status, status._size, bytesNeeded);
173 - if (success != 0) {
174 - retVal = {};
175 - retVal.status = parseServiceStatus(status);
176 - retVal._scm = handle;
177 - retVal._service = h;
178 - retVal._GM = this.GM;
179 - retVal._proxy = this.proxy;
180 - require('events').inherits(retVal);
181 - retVal.on('~', function () { this._proxy.CloseServiceHandle(this); this._proxy.CloseServiceHandle(this._scm); });
182 - retVal.name = name;
183 - retVal.stop = function () {
184 - if (this.status.state == 'RUNNING') {
185 - var newstate = this._GM.CreateVariable(36);
186 - var success = this._proxy.ControlService(this._service, 0x00000001, newstate);
187 - if (success == 0) {
188 - throw (this.name + '.stop() failed');
189 - }
190 - }
191 - else {
192 - throw ('cannot call ' + this.name + '.stop(), when current state is: ' + this.status.state);
193 - }
194 - }
195 - retVal.start = function () {
196 - if (this.status.state == 'STOPPED') {
197 - var success = this._proxy.StartServiceA(this._service, 0, 0);
198 - if (success == 0) {
199 - throw (this.name + '.start() failed');
200 - }
201 - }
202 - else {
203 - throw ('cannot call ' + this.name + '.start(), when current state is: ' + this.status.state);
204 - }
205 - }
206 - return (retVal);
207 - }
208 - else {
209 -
210 - }
211 - }
212 -
213 - this.proxy.CloseServiceHandle(handle);
214 - throw ('could not find service: ' + name);
215 - }
216 - }
217 - else
218 - {
219 - this.isAdmin = function isAdmin()
220 - {
221 - return (require('user-sessions').isRoot());
222 - }
223 - }
224 - this.installService = function installService(options)
225 - {
226 - if (process.platform == 'win32')
227 - {
228 - if (!this.isAdmin()) { throw ('Installing as Service, requires admin'); }
229 -
230 - // Before we start, we need to copy the binary to the right place
231 - var folder = this.getServiceFolder();
232 - if (!require('fs').existsSync(folder)) { require('fs').mkdirSync(folder); }
233 - require('fs').copyFileSync(options.servicePath, folder + '\\' + options.name + '.exe');
234 - options.servicePath = folder + '\\' + options.name + '.exe';
235 -
236 - var servicePath = this.GM.CreateVariable('"' + options.servicePath + '"');
237 - var handle = this.proxy.OpenSCManagerA(0x00, 0x00, 0x0002);
238 - if (handle.Val == 0) { throw ('error opening SCManager'); }
239 - var serviceName = this.GM.CreateVariable(options.name);
240 - var displayName = this.GM.CreateVariable(options.name);
241 - var allAccess = 0x000F01FF;
242 - var serviceType;
243 -
244 -
245 - switch (options.startType) {
246 - case 'BOOT_START':
247 - serviceType = 0x00;
248 - break;
249 - case 'SYSTEM_START':
250 - serviceType = 0x01;
251 - break;
252 - case 'AUTO_START':
253 - serviceType = 0x02;
254 - break;
255 - case 'DEMAND_START':
256 - serviceType = 0x03;
257 - break;
258 - default:
259 - serviceType = 0x04; // Disabled
260 - break;
261 - }
262 -
263 - var h = this.proxy.CreateServiceA(handle, serviceName, displayName, allAccess, 0x10 | 0x100, serviceType, 0, servicePath, 0, 0, 0, 0, 0);
264 - if (h.Val == 0) { this.proxy.CloseServiceHandle(handle); throw ('Error Creating Service: ' + this.proxy2.GetLastError().Val); }
265 - if (options.description) {
266 - console.log(options.description);
267 -
268 - var dscPtr = this.GM.CreatePointer();
269 - dscPtr.Val = this.GM.CreateVariable(options.description);
270 -
271 - if (this.proxy.ChangeServiceConfig2A(h, 1, dscPtr) == 0) {
272 - this.proxy.CloseServiceHandle(h);
273 - this.proxy.CloseServiceHandle(handle);
274 - throw ('Unable to set description');
275 - }
276 - }
277 - this.proxy.CloseServiceHandle(h);
278 - this.proxy.CloseServiceHandle(handle);
279 - return (this.getService(options.name));
280 - }
281 - if(process.platform == 'linux')
282 - {
283 - if (!this.isAdmin()) { throw ('Installing as Service, requires root'); }
284 -
285 - switch (this.getServiceType())
286 - {
287 - case 'init':
288 - require('fs').copyFileSync(options.servicePath, '/etc/init.d/' + options.name);
289 - console.log('copying ' + options.servicePath);
290 - var m = require('fs').statSync('/etc/init.d/' + options.name).mode;
291 - m |= (require('fs').CHMOD_MODES.S_IXUSR | require('fs').CHMOD_MODES.S_IXGRP);
292 - require('fs').chmodSync('/etc/init.d/' + options.name, m);
293 - this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM });
294 - this._update._moduleName = options.name;
295 - this._update.stdout.on('data', function (chunk) { });
296 - this._update.stdin.write('update-rc.d ' + options.name + ' defaults\n');
297 - this._update.stdin.write('exit\n');
298 - //update-rc.d meshagent defaults # creates symlinks for rc.d
299 - //service meshagent start
300 -
301 - this._update.waitExit();
302 -
303 - break;
304 - case 'systemd':
305 - var serviceDescription = options.description ? options.description : 'MeshCentral Agent';
306 - if (!require('fs').existsSync('/usr/local/mesh')) { require('fs').mkdirSync('/usr/local/mesh'); }
307 - require('fs').copyFileSync(options.servicePath, '/usr/local/mesh/' + options.name);
308 - var m = require('fs').statSync('/usr/local/mesh/' + options.name).mode;
309 - m |= (require('fs').CHMOD_MODES.S_IXUSR | require('fs').CHMOD_MODES.S_IXGRP);
310 - require('fs').chmodSync('/usr/local/mesh/' + options.name, m);
311 - require('fs').writeFileSync('/lib/systemd/system/' + options.name + '.service', '[Unit]\nDescription=' + serviceDescription + '\n[Service]\nExecStart=/usr/local/mesh/' + options.name + '\nStandardOutput=null\nRestart=always\nRestartSec=3\n[Install]\nWantedBy=multi-user.target\nAlias=' + options.name + '.service\n', { flags: 'w' });
312 - this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM });
313 - this._update._moduleName = options.name;
314 - this._update.stdout.on('data', function (chunk) { });
315 - this._update.stdin.write('systemctl enable ' + options.name + '.service\n');
316 - this._update.stdin.write('exit\n');
317 - this._update.waitExit();
318 - break;
319 - default: // unknown platform service type
320 - break;
321 - }
322 - }
323 - if(process.platform == 'darwin')
324 - {
325 - if (!this.isAdmin()) { throw ('Installing as Service, requires root'); }
326 -
327 - // Mac OS
328 - var stdoutpath = (options.stdout ? ('<key>StandardOutPath</key>\n<string>' + options.stdout + '</string>') : '');
329 - var autoStart = (options.startType == 'AUTO_START' ? '<true/>' : '<false/>');
330 - var params = ' <key>ProgramArguments</key>\n';
331 - params += ' <array>\n';
332 - params += (' <string>/usr/local/mesh_services/' + options.name + '/' + options.name + '</string>\n');
333 - if(options.parameters)
334 - {
335 - for(var itm in options.parameters)
336 - {
337 - params += (' <string>' + options.parameters[itm] + '</string>\n');
338 - }
339 - }
340 - params += ' </array>\n';
341 -
342 - var plist = '<?xml version="1.0" encoding="UTF-8"?>\n';
343 - plist += '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n';
344 - plist += '<plist version="1.0">\n';
345 - plist += ' <dict>\n';
346 - plist += ' <key>Label</key>\n';
347 - plist += (' <string>' + options.name + '</string>\n');
348 - plist += (params + '\n');
349 - plist += ' <key>WorkingDirectory</key>\n';
350 - plist += (' <string>/usr/local/mesh_services/' + options.name + '</string>\n');
351 - plist += (stdoutpath + '\n');
352 - plist += ' <key>RunAtLoad</key>\n';
353 - plist += (autoStart + '\n');
354 - plist += ' </dict>\n';
355 - plist += '</plist>';
356 -
357 - if (!require('fs').existsSync('/usr/local/mesh_services')) { require('fs').mkdirSync('/usr/local/mesh_services'); }
358 - if (!require('fs').existsSync('/Library/LaunchDaemons/' + options.name + '.plist'))
359 - {
360 - if (!require('fs').existsSync('/usr/local/mesh_services/' + options.name)) { require('fs').mkdirSync('/usr/local/mesh_services/' + options.name); }
361 - if (options.binary)
362 - {
363 - require('fs').writeFileSync('/usr/local/mesh_services/' + options.name + '/' + options.name, options.binary);
364 - }
365 - else
366 - {
367 - require('fs').copyFileSync(options.servicePath, '/usr/local/mesh_services/' + options.name + '/' + options.name);
368 - }
369 - require('fs').writeFileSync('/Library/LaunchDaemons/' + options.name + '.plist', plist);
370 - var m = require('fs').statSync('/usr/local/mesh_services/' + options.name + '/' + options.name).mode;
371 - m |= (require('fs').CHMOD_MODES.S_IXUSR | require('fs').CHMOD_MODES.S_IXGRP);
372 - require('fs').chmodSync('/usr/local/mesh_services/' + options.name + '/' + options.name, m);
373 - }
374 - else
375 - {
376 - throw ('Service: ' + options.name + ' already exists');
377 - }
378 - }
379 - }
380 - this.uninstallService = function uninstallService(name)
381 - {
382 - if (!this.isAdmin()) { throw ('Uninstalling a service, requires admin'); }
383 -
384 - if (typeof (name) == 'object') { name = name.name; }
385 - if (process.platform == 'win32')
386 - {
387 - var service = this.getService(name);
388 - if (service.status.state == undefined || service.status.state == 'STOPPED')
389 - {
390 - if (this.proxy.DeleteService(service._service) == 0)
391 - {
392 - throw ('Uninstall Service for: ' + name + ', failed with error: ' + this.proxy2.GetLastError());
393 - }
394 - else
395 - {
396 - try
397 - {
398 - require('fs').unlinkSync(this.getServiceFolder() + '\\' + name + '.exe');
399 - }
400 - catch(e)
401 - {
402 - }
403 - }
404 - }
405 - else
406 - {
407 - throw ('Cannot uninstall service: ' + name + ', because it is: ' + service.status.state);
408 - }
409 - }
410 - else if(process.platform == 'linux')
411 - {
412 - switch (this.getServiceType())
413 - {
414 - case 'init':
415 - this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM });
416 - this._update.stdout.on('data', function (chunk) { });
417 - this._update.stdin.write('service ' + name + ' stop\n');
418 - this._update.stdin.write('update-rc.d -f ' + name + ' remove\n');
419 - this._update.stdin.write('exit\n');
420 - this._update.waitExit();
421 - try
422 - {
423 - require('fs').unlinkSync('/etc/init.d/' + name);
424 - console.log(name + ' uninstalled');
425 -
426 - }
427 - catch (e)
428 - {
429 - console.log(name + ' could not be uninstalled', e)
430 - }
431 - break;
432 - case 'systemd':
433 - this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM });
434 - this._update.stdout.on('data', function (chunk) { });
435 - this._update.stdin.write('systemctl stop ' + name + '.service\n');
436 - this._update.stdin.write('systemctl disable ' + name + '.service\n');
437 - this._update.stdin.write('exit\n');
438 - this._update.waitExit();
439 - try
440 - {
441 - require('fs').unlinkSync('/usr/local/mesh/' + name);
442 - require('fs').unlinkSync('/lib/systemd/system/' + name + '.service');
443 - console.log(name + ' uninstalled');
444 - }
445 - catch (e)
446 - {
447 - console.log(name + ' could not be uninstalled', e)
448 - }
449 - break;
450 - default: // unknown platform service type
451 - break;
452 - }
453 - }
454 - else if(process.platform == 'darwin')
455 - {
456 - if (require('fs').existsSync('/Library/LaunchDaemons/' + name + '.plist'))
457 - {
458 - var child = require('child_process').execFile('/bin/sh', ['sh']);
459 - child.stdout.on('data', function (chunk) { });
460 - child.stdin.write('launchctl stop ' + name + '\n');
461 - child.stdin.write('launchctl unload /Library/LaunchDaemons/' + name + '.plist\n');
462 - child.stdin.write('exit\n');
463 - child.waitExit();
464 -
465 - try
466 - {
467 - require('fs').unlinkSync('/usr/local/mesh_services/' + name + '/' + name);
468 - require('fs').unlinkSync('/Library/LaunchDaemons/' + name + '.plist');
469 - }
470 - catch(e)
471 - {
472 - throw ('Error uninstalling service: ' + name + ' => ' + e);
473 - }
474 -
475 - try
476 - {
477 - require('fs').rmdirSync('/usr/local/mesh_services/' + name);
478 - }
479 - catch(e)
480 - {}
481 - }
482 - else
483 - {
484 - throw ('Service: ' + name + ' does not exist');
485 - }
486 - }
487 - }
488 - if(process.platform == 'linux')
489 - {
490 - this.getServiceType = function getServiceType()
491 - {
492 - return (require('process-manager').getProcessInfo(1).Name);
493 - };
494 - }
495 -}
496 -
497 -module.exports = serviceManager;
\ No newline at end of file
agents/modules_meshcore/x/user-sessions.js deleted
-750
@@ -1,750 +0,0 @@
1 -/*
2 -Copyright 2018 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -var NOTIFY_FOR_THIS_SESSION = 0;
18 -var NOTIFY_FOR_ALL_SESSIONS = 1;
19 -var WM_WTSSESSION_CHANGE = 0x02B1;
20 -var WM_POWERBROADCAST = 0x218;
21 -var PBT_POWERSETTINGCHANGE = 0x8013;
22 -var PBT_APMSUSPEND = 0x4;
23 -var PBT_APMRESUMESUSPEND = 0x7;
24 -var PBT_APMRESUMEAUTOMATIC = 0x12;
25 -var PBT_APMPOWERSTATUSCHANGE = 0xA;
26 -
27 -var WTS_CONSOLE_CONNECT = (0x1);
28 -var WTS_CONSOLE_DISCONNECT = (0x2);
29 -var WTS_REMOTE_CONNECT = (0x3);
30 -var WTS_REMOTE_DISCONNECT = (0x4);
31 -var WTS_SESSION_LOGON = (0x5);
32 -var WTS_SESSION_LOGOFF = (0x6);
33 -var WTS_SESSION_LOCK = (0x7);
34 -var WTS_SESSION_UNLOCK = (0x8);
35 -var WTS_SESSION_REMOTE_CONTROL = (0x9);
36 -var WTS_SESSION_CREATE = (0xA);
37 -var WTS_SESSION_TERMINATE = (0xB);
38 -
39 -var GUID_ACDC_POWER_SOURCE;
40 -var GUID_BATTERY_PERCENTAGE_REMAINING;
41 -var GUID_CONSOLE_DISPLAY_STATE;
42 -
43 -function UserSessions()
44 -{
45 - this._ObjectID = 'user-sessions';
46 - require('events').EventEmitter.call(this, true)
47 - .createEvent('changed')
48 - .createEvent('locked')
49 - .createEvent('unlocked');
50 -
51 - this.enumerateUsers = function enumerateUsers()
52 - {
53 - var promise = require('promise');
54 - var p = new promise(function (res, rej)
55 - {
56 - this.__resolver = res;
57 - this.__rejector = rej;
58 - });
59 - p.__handler = function __handler(users)
60 - {
61 - p.__resolver(users);
62 - };
63 - try
64 - {
65 - this.Current(p.__handler);
66 - }
67 - catch(e)
68 - {
69 - p.__rejector(e);
70 - }
71 - p.parent = this;
72 - return (p);
73 - }
74 -
75 - if (process.platform == 'win32')
76 - {
77 - this._serviceHooked = false;
78 - this._marshal = require('_GenericMarshal');
79 - this._kernel32 = this._marshal.CreateNativeProxy('Kernel32.dll');
80 - this._kernel32.CreateMethod('GetLastError');
81 -
82 - try
83 - {
84 - this._wts = this._marshal.CreateNativeProxy('Wtsapi32.dll');
85 - this._wts.CreateMethod('WTSEnumerateSessionsA');
86 - this._wts.CreateMethod('WTSQuerySessionInformationA');
87 - this._wts.CreateMethod('WTSRegisterSessionNotification');
88 - this._wts.CreateMethod('WTSUnRegisterSessionNotification');
89 - this._wts.CreateMethod('WTSFreeMemory');
90 - }
91 - catch(exc)
92 - {
93 - }
94 -
95 - this._advapi = this._marshal.CreateNativeProxy('Advapi32.dll');
96 - this._advapi.CreateMethod('AllocateAndInitializeSid');
97 - this._advapi.CreateMethod('CheckTokenMembership');
98 - this._advapi.CreateMethod('FreeSid');
99 -
100 - this._user32 = this._marshal.CreateNativeProxy('user32.dll');
101 - this._user32.CreateMethod({ method: 'RegisterPowerSettingNotification', threadDispatch: 1});
102 - this._user32.CreateMethod('UnregisterPowerSettingNotification');
103 - this._rpcrt = this._marshal.CreateNativeProxy('Rpcrt4.dll');
104 - this._rpcrt.CreateMethod('UuidFromStringA');
105 - this._rpcrt.StringToUUID = function StringToUUID(guid)
106 - {
107 - var retVal = StringToUUID.us._marshal.CreateVariable(16);
108 - if(StringToUUID.us._rpcrt.UuidFromStringA(StringToUUID.us._marshal.CreateVariable(guid), retVal).Val == 0)
109 - {
110 - return (retVal);
111 - }
112 - else
113 - {
114 - throw ('Could not convert string to UUID');
115 - }
116 - }
117 - this._rpcrt.StringToUUID.us = this;
118 -
119 - GUID_ACDC_POWER_SOURCE = this._rpcrt.StringToUUID('5d3e9a59-e9D5-4b00-a6bd-ff34ff516548');
120 - GUID_BATTERY_PERCENTAGE_REMAINING = this._rpcrt.StringToUUID('a7ad8041-b45a-4cae-87a3-eecbb468a9e1');
121 - GUID_CONSOLE_DISPLAY_STATE = this._rpcrt.StringToUUID('6fe69556-704a-47a0-8f24-c28d936fda47');
122 -
123 - this.SessionStates = ['Active', 'Connected', 'ConnectQuery', 'Shadow', 'Disconnected', 'Idle', 'Listening', 'Reset', 'Down', 'Init'];
124 - this.InfoClass =
125 - {
126 - 'WTSInitialProgram': 0,
127 - 'WTSApplicationName': 1,
128 - 'WTSWorkingDirectory': 2,
129 - 'WTSOEMId': 3,
130 - 'WTSSessionId': 4,
131 - 'WTSUserName': 5,
132 - 'WTSWinStationName': 6,
133 - 'WTSDomainName': 7,
134 - 'WTSConnectState': 8,
135 - 'WTSClientBuildNumber': 9,
136 - 'WTSClientName': 10,
137 - 'WTSClientDirectory': 11,
138 - 'WTSClientProductId': 12,
139 - 'WTSClientHardwareId': 13,
140 - 'WTSClientAddress': 14,
141 - 'WTSClientDisplay': 15,
142 - 'WTSClientProtocolType': 16,
143 - 'WTSIdleTime': 17,
144 - 'WTSLogonTime': 18,
145 - 'WTSIncomingBytes': 19,
146 - 'WTSOutgoingBytes': 20,
147 - 'WTSIncomingFrames': 21,
148 - 'WTSOutgoingFrames': 22,
149 - 'WTSClientInfo': 23,
150 - 'WTSSessionInfo': 24,
151 - 'WTSSessionInfoEx': 25,
152 - 'WTSConfigInfo': 26,
153 - 'WTSValidationInfo': 27,
154 - 'WTSSessionAddressV4': 28,
155 - 'WTSIsRemoteSession': 29
156 - };
157 -
158 - this.isRoot = function isRoot()
159 - {
160 - var NTAuthority = this._marshal.CreateVariable(6);
161 - NTAuthority.toBuffer().writeInt8(5, 5);
162 -
163 - var AdministratorsGroup = this._marshal.CreatePointer();
164 - var admin = false;
165 -
166 - if (this._advapi.AllocateAndInitializeSid(NTAuthority, 2, 32, 544, 0, 0, 0, 0, 0, 0, AdministratorsGroup).Val != 0)
167 - {
168 - var member = this._marshal.CreateInteger();
169 - if (this._advapi.CheckTokenMembership(0, AdministratorsGroup.Deref(), member).Val != 0)
170 - {
171 - if (member.toBuffer().readUInt32LE() != 0) { admin = true; }
172 - }
173 - this._advapi.FreeSid(AdministratorsGroup.Deref());
174 - }
175 - return admin;
176 - }
177 -
178 - this.getSessionAttribute = function getSessionAttribute(sessionId, attr)
179 - {
180 - var buffer = this._marshal.CreatePointer();
181 - var bytesReturned = this._marshal.CreateVariable(4);
182 -
183 - if (this._wts.WTSQuerySessionInformationA(0, sessionId, attr, buffer, bytesReturned).Val == 0)
184 - {
185 - throw ('Error calling WTSQuerySessionInformation: ' + this._kernel32.GetLastError.Val);
186 - }
187 -
188 - var retVal = buffer.Deref().String;
189 -
190 - this._wts.WTSFreeMemory(buffer.Deref());
191 - return (retVal);
192 - };
193 -
194 - this.Current = function Current(cb)
195 - {
196 - var retVal = {};
197 - var pinfo = this._marshal.CreatePointer();
198 - var count = this._marshal.CreateVariable(4);
199 - if (this._wts.WTSEnumerateSessionsA(0, 0, 1, pinfo, count).Val == 0)
200 - {
201 - throw ('Error calling WTSEnumerateSessionsA: ' + this._kernel32.GetLastError().Val);
202 - }
203 -
204 - for (var i = 0; i < count.toBuffer().readUInt32LE() ; ++i)
205 - {
206 - var info = pinfo.Deref().Deref(i * (this._marshal.PointerSize == 4 ? 12 : 24), this._marshal.PointerSize == 4 ? 12 : 24);
207 - var j = { SessionId: info.toBuffer().readUInt32LE() };
208 - j.StationName = info.Deref(this._marshal.PointerSize == 4 ? 4 : 8, this._marshal.PointerSize).Deref().String;
209 - j.State = this.SessionStates[info.Deref(this._marshal.PointerSize == 4 ? 8 : 16, 4).toBuffer().readUInt32LE()];
210 - if (j.State == 'Active') {
211 - j.Username = this.getSessionAttribute(j.SessionId, this.InfoClass.WTSUserName);
212 - j.Domain = this.getSessionAttribute(j.SessionId, this.InfoClass.WTSDomainName);
213 - }
214 - retVal[j.SessionId] = j;
215 - }
216 -
217 - this._wts.WTSFreeMemory(pinfo.Deref());
218 -
219 - Object.defineProperty(retVal, 'Active', { value: showActiveOnly(retVal) });
220 - if (cb) { cb(retVal); }
221 - return (retVal);
222 - };
223 -
224 -
225 - // We need to spin up a message pump, and fetch a window handle
226 - var message_pump = require('win-message-pump');
227 - this._messagepump = new message_pump({ filter: WM_WTSSESSION_CHANGE }); this._messagepump.parent = this;
228 - this._messagepump.on('exit', function (code) { this.parent._wts.WTSUnRegisterSessionNotification(this.parent.hwnd); });
229 - this._messagepump.on('hwnd', function (h)
230 - {
231 - this.parent.hwnd = h;
232 -
233 - // We need to yield, and do this in the next event loop pass, becuase we don't want to call 'RegisterPowerSettingNotification'
234 - // from the messagepump 'thread', because we are actually on the microstack thread, such that the message pump thread, is holding
235 - // on a semaphore for us to return. If we call now, we may deadlock on Windows 7, becuase it will try to notify immediately
236 - this.immediate = setImmediate(function (self)
237 - {
238 - // Now that we have a window handle, we can register it to receive Windows Messages
239 - if (self.parent._wts) { self.parent._wts.WTSRegisterSessionNotification(self.parent.hwnd, NOTIFY_FOR_ALL_SESSIONS); }
240 - self.parent._user32.ACDC_H = self.parent._user32.RegisterPowerSettingNotification(self.parent.hwnd, GUID_ACDC_POWER_SOURCE, 0);
241 - self.parent._user32.BATT_H = self.parent._user32.RegisterPowerSettingNotification(self.parent.hwnd, GUID_BATTERY_PERCENTAGE_REMAINING, 0);
242 - self.parent._user32.DISP_H = self.parent._user32.RegisterPowerSettingNotification(self.parent.hwnd, GUID_CONSOLE_DISPLAY_STATE, 0);
243 - //console.log(self.parent._user32.ACDC_H.Val, self.parent._user32.BATT_H.Val, self.parent._user32.DISP_H.Val);
244 - }, this);
245 - });
246 - this._messagepump.on('message', function (msg)
247 - {
248 - switch(msg.message)
249 - {
250 - case WM_WTSSESSION_CHANGE:
251 - switch(msg.wparam)
252 - {
253 - case WTS_SESSION_LOCK:
254 - this.parent.enumerateUsers().then(function (users)
255 - {
256 - if (users[msg.lparam]) { this.parent.emit('locked', users[msg.lparam]); }
257 - });
258 - break;
259 - case WTS_SESSION_UNLOCK:
260 - this.parent.enumerateUsers().then(function (users)
261 - {
262 - if (users[msg.lparam]) { this.parent.emit('unlocked', users[msg.lparam]); }
263 - });
264 - break;
265 - case WTS_SESSION_LOGON:
266 - case WTS_SESSION_LOGOFF:
267 - this.parent.emit('changed');
268 - break;
269 - }
270 - break;
271 - case WM_POWERBROADCAST:
272 - switch(msg.wparam)
273 - {
274 - default:
275 - console.log('WM_POWERBROADCAST [UNKNOWN wparam]: ' + msg.wparam);
276 - break;
277 - case PBT_APMSUSPEND:
278 - require('power-monitor').emit('sx', 'SLEEP');
279 - break;
280 - case PBT_APMRESUMEAUTOMATIC:
281 - require('power-monitor').emit('sx', 'RESUME_NON_INTERACTIVE');
282 - break;
283 - case PBT_APMRESUMESUSPEND:
284 - require('power-monitor').emit('sx', 'RESUME_INTERACTIVE');
285 - break;
286 - case PBT_APMPOWERSTATUSCHANGE:
287 - require('power-monitor').emit('changed');
288 - break;
289 - case PBT_POWERSETTINGCHANGE:
290 - var lparam = this.parent._marshal.CreatePointer(Buffer.from(msg.lparam_hex, 'hex'));
291 - var data = lparam.Deref(20, lparam.Deref(16, 4).toBuffer().readUInt32LE(0)).toBuffer();
292 - switch(lparam.Deref(0, 16).toBuffer().toString('hex'))
293 - {
294 - case GUID_ACDC_POWER_SOURCE.Deref(0, 16).toBuffer().toString('hex'):
295 - switch(data.readUInt32LE(0))
296 - {
297 - case 0:
298 - require('power-monitor').emit('acdc', 'AC');
299 - break;
300 - case 1:
301 - require('power-monitor').emit('acdc', 'BATTERY');
302 - break;
303 - case 2:
304 - require('power-monitor').emit('acdc', 'HOT');
305 - break;
306 - }
307 - break;
308 - case GUID_BATTERY_PERCENTAGE_REMAINING.Deref(0, 16).toBuffer().toString('hex'):
309 - require('power-monitor').emit('batteryLevel', data.readUInt32LE(0));
310 - break;
311 - case GUID_CONSOLE_DISPLAY_STATE.Deref(0, 16).toBuffer().toString('hex'):
312 - switch(data.readUInt32LE(0))
313 - {
314 - case 0:
315 - require('power-monitor').emit('display', 'OFF');
316 - break;
317 - case 1:
318 - require('power-monitor').emit('display', 'ON');
319 - break;
320 - case 2:
321 - require('power-monitor').emit('display', 'DIMMED');
322 - break;
323 - }
324 - break;
325 - }
326 - break;
327 - }
328 - break;
329 - default:
330 - break;
331 - }
332 - });
333 - }
334 - else if(process.platform == 'linux')
335 - {
336 - var dbus = require('linux-dbus');
337 - this._linuxWatcher = require('fs').watch('/var/run/utmp');
338 - this._linuxWatcher.user_session = this;
339 - this._linuxWatcher.on('change', function (a, b)
340 - {
341 - this.user_session.emit('changed');
342 - });
343 - this._users = function _users()
344 - {
345 - var child = require('child_process').execFile('/bin/sh', ['sh']);
346 - child.stdout.str = '';
347 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
348 - child.stdin.write('awk -F: \'($3 >= 0) {printf "%s:%s\\n", $1, $3}\' /etc/passwd\nexit\n');
349 - child.waitExit();
350 -
351 - var lines = child.stdout.str.split('\n');
352 - var ret = {}, tokens;
353 - for (var ln in lines)
354 - {
355 - tokens = lines[ln].split(':');
356 - if (tokens[0]) { ret[tokens[0]] = tokens[1]; }
357 - }
358 - return (ret);
359 - }
360 - this._uids = function _uids() {
361 - var child = require('child_process').execFile('/bin/sh', ['sh']);
362 - child.stdout.str = '';
363 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
364 - child.stdin.write('awk -F: \'($3 >= 0) {printf "%s:%s\\n", $1, $3}\' /etc/passwd\nexit\n');
365 - child.waitExit();
366 -
367 - var lines = child.stdout.str.split('\n');
368 - var ret = {}, tokens;
369 - for (var ln in lines) {
370 - tokens = lines[ln].split(':');
371 - if (tokens[0]) { ret[tokens[1]] = tokens[0]; }
372 - }
373 - return (ret);
374 - }
375 - this.Self = function Self()
376 - {
377 - var promise = require('promise');
378 - var p = new promise(function (res, rej)
379 - {
380 - this.__resolver = res; this.__rejector = rej;
381 - this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u']);
382 - this.__child.promise = this;
383 - this.__child.stdout._txt = '';
384 - this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
385 - this.__child.on('exit', function (code)
386 - {
387 - try
388 - {
389 - parseInt(this.stdout._txt);
390 - }
391 - catch (e)
392 - {
393 - this.promise.__rejector('invalid uid');
394 - return;
395 - }
396 -
397 - var id = parseInt(this.stdout._txt);
398 - this.promise.__resolver(id);
399 - });
400 - });
401 - return (p);
402 - };
403 - this.Current = function Current(cb)
404 - {
405 - var retVal = {};
406 - retVal._ObjectID = 'UserSession'
407 - Object.defineProperty(retVal, '_callback', { value: cb });
408 - Object.defineProperty(retVal, '_child', { value: require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']) });
409 -
410 - retVal._child.Parent = retVal;
411 - retVal._child._txt = '';
412 - retVal._child.on('exit', function (code)
413 - {
414 - var lines = this._txt.split('\n');
415 - var sessions = [];
416 - var users = {};
417 -
418 - for(var i in lines)
419 - {
420 - if (lines[i])
421 - {
422 - var tokens = getTokens(lines[i]);
423 - var s = { Username: tokens[0], SessionId: tokens[1] }
424 - if (tokens[3].includes('still logged in'))
425 - {
426 - s.State = 'Active';
427 - }
428 - else
429 - {
430 - s.LastActive = tokens[3];
431 - }
432 -
433 - sessions.push(s);
434 - }
435 - }
436 - sessions.pop();
437 -
438 -
439 - var usernames = {};
440 - var promises = [];
441 -
442 - for (var i in sessions)
443 - {
444 - if (sessions[i].Username != 'reboot')
445 - {
446 - users[sessions[i].SessionId] = sessions[i];
447 - if(usernames[sessions[i].Username] == null)
448 - {
449 - usernames[sessions[i].Username] = -1;
450 - }
451 - }
452 - }
453 -
454 - try
455 - {
456 - require('promise');
457 - }
458 - catch(e)
459 - {
460 - Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
461 - if (this.Parent._callback) { this.Parent._callback.call(this.Parent, users); }
462 - return;
463 - }
464 -
465 - var promise = require('promise');
466 - for (var n in usernames)
467 - {
468 - var p = new promise(function (res, rej)
469 - {
470 - this.__username = n;
471 - this.__resolver = res; this.__rejector = rej;
472 - this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u', n]);
473 - this.__child.promise = this;
474 - this.__child.stdout._txt = '';
475 - this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
476 - this.__child.on('exit', function (code)
477 - {
478 - try
479 - {
480 - parseInt(this.stdout._txt);
481 - }
482 - catch(e)
483 - {
484 - this.promise.__rejector('invalid uid');
485 - return;
486 - }
487 -
488 - var id = parseInt(this.stdout._txt);
489 - this.promise.__resolver(id);
490 - });
491 - });
492 - promises.push(p);
493 - }
494 - promise.all(promises).then(function (plist)
495 - {
496 - // Done
497 - var table = {};
498 - for(var i in plist)
499 - {
500 - table[plist[i].__username] = plist[i]._internal.completedArgs[0];
501 - }
502 - for(var i in users)
503 - {
504 - users[i].uid = table[users[i].Username];
505 - }
506 - Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
507 - if (retVal._callback) { retVal._callback.call(retVal, users); }
508 - }, function (reason)
509 - {
510 - // Failed
511 - Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
512 - if (retVal._callback) { retVal._callback.call(retVal, users); }
513 - });
514 - });
515 - retVal._child.stdout.Parent = retVal._child;
516 - retVal._child.stdout.on('data', function (chunk) { this.Parent._txt += chunk.toString(); });
517 -
518 - return (retVal);
519 - }
520 - this._recheckLoggedInUsers = function _recheckLoggedInUsers()
521 - {
522 - this.enumerateUsers().then(function (u)
523 - {
524 -
525 - if (u.Active.length > 0)
526 - {
527 - // There is already a user logged in, so we can monitor DBUS for lock/unlock
528 - if (this.parent._linux_lock_watcher != null && this.parent._linux_lock_watcher.uid != u.Active[0].uid)
529 - {
530 - delete this.parent._linux_lock_watcher;
531 - }
532 - this.parent._linux_lock_watcher = new dbus(process.env['XDG_CURRENT_DESKTOP'] == 'Unity' ? 'com.ubuntu.Upstart0_6' : 'org.gnome.ScreenSaver', u.Active[0].uid);
533 - this.parent._linux_lock_watcher.user_session = this.parent;
534 - this.parent._linux_lock_watcher.on('signal', function (s)
535 - {
536 - var p = this.user_session.enumerateUsers();
537 - p.signalData = s.data[0];
538 - p.then(function (u)
539 - {
540 - switch (this.signalData)
541 - {
542 - case true:
543 - case 'desktop-lock':
544 - this.parent.emit('locked', u.Active[0]);
545 - break;
546 - case false:
547 - case 'desktop-unlock':
548 - this.parent.emit('unlocked', u.Active[0]);
549 - break;
550 - }
551 - });
552 - });
553 - }
554 - else if (this.parent._linux_lock_watcher != null)
555 - {
556 - delete this.parent._linux_lock_watcher;
557 - }
558 - });
559 -
560 - };
561 - this.on('changed', this._recheckLoggedInUsers); // For linux Lock/Unlock monitoring, we need to watch for LogOn/LogOff, and keep track of the UID.
562 -
563 -
564 - // First step, is to see if there is a user logged in:
565 - this._recheckLoggedInUsers();
566 - }
567 - else if(process.platform == 'darwin')
568 - {
569 - this._users = function ()
570 - {
571 - var child = require('child_process').execFile('/usr/bin/dscl', ['dscl', '.', 'list', '/Users', 'UniqueID']);
572 - child.stdout.str = '';
573 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
574 - child.stdin.write('exit\n');
575 - child.waitExit();
576 -
577 - var lines = child.stdout.str.split('\n');
578 - var tokens, i;
579 - var users = {};
580 -
581 - for (i = 0; i < lines.length; ++i) {
582 - tokens = lines[i].split(' ');
583 - if (tokens[0]) { users[tokens[0]] = tokens[tokens.length - 1]; }
584 - }
585 -
586 - return (users);
587 - }
588 - this._uids = function () {
589 - var child = require('child_process').execFile('/usr/bin/dscl', ['dscl', '.', 'list', '/Users', 'UniqueID']);
590 - child.stdout.str = '';
591 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
592 - child.stdin.write('exit\n');
593 - child.waitExit();
594 -
595 - var lines = child.stdout.str.split('\n');
596 - var tokens, i;
597 - var users = {};
598 -
599 - for (i = 0; i < lines.length; ++i) {
600 - tokens = lines[i].split(' ');
601 - if (tokens[0]) { users[tokens[tokens.length - 1]] = tokens[0]; }
602 - }
603 -
604 - return (users);
605 - }
606 - this._idTable = function()
607 - {
608 - var table = {};
609 - var child = require('child_process').execFile('/usr/bin/id', ['id']);
610 - child.stdout.str = '';
611 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
612 - child.waitExit();
613 -
614 - var lines = child.stdout.str.split('\n')[0].split(' ');
615 - for (var i = 0; i < lines.length; ++i) {
616 - var types = lines[i].split('=');
617 - var tokens = types[1].split(',');
618 - table[types[0]] = {};
619 -
620 - for (var j in tokens) {
621 - var idarr = tokens[j].split('(');
622 - var id = idarr[0];
623 - var name = idarr[1].substring(0, idarr[1].length - 1).trim();
624 - table[types[0]][name] = id;
625 - table[types[0]][id] = name;
626 - }
627 - }
628 - return (table);
629 - }
630 - this.Current = function (cb)
631 - {
632 - var users = {};
633 - var table = this._idTable();
634 - var child = require('child_process').execFile('/usr/bin/last', ['last']);
635 - child.stdout.str = '';
636 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
637 - child.waitExit();
638 -
639 - var lines = child.stdout.str.split('\n');
640 - for (var i = 0; i < lines.length && lines[i].length > 0; ++i)
641 - {
642 - if (!users[lines[i].split(' ')[0]])
643 - {
644 - try
645 - {
646 - users[lines[i].split(' ')[0]] = { Username: lines[i].split(' ')[0], State: lines[i].split('still logged in').length > 1 ? 'Active' : 'Inactive', uid: table.uid[lines[i].split(' ')[0]] };
647 - }
648 - catch(e)
649 - {}
650 - }
651 - else
652 - {
653 - if(users[lines[i].split(' ')[0]].State != 'Active' && lines[i].split('still logged in').length > 1)
654 - {
655 - users[lines[i].split(' ')[0]].State = 'Active';
656 - }
657 - }
658 - }
659 -
660 - Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
661 - if (cb) { cb.call(this, users); }
662 - }
663 - }
664 -
665 - if(process.platform == 'linux' || process.platform == 'darwin')
666 - {
667 - this._self = function _self()
668 - {
669 - var child = require('child_process').execFile('/usr/bin/id', ['id', '-u']);
670 - child.stdout.str = '';
671 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
672 - child.waitExit();
673 - return (parseInt(child.stdout.str));
674 - }
675 - this.isRoot = function isRoot()
676 - {
677 - return (this._self() == 0);
678 - }
679 - this.consoleUid = function consoleUid()
680 - {
681 - var checkstr = process.platform == 'darwin' ? 'console' : ((process.env['DISPLAY'])?process.env['DISPLAY']:':0')
682 - var child = require('child_process').execFile('/bin/sh', ['sh']);
683 - child.stdout.str = '';
684 - child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
685 - child.stdin.write('who\nexit\n');
686 - child.waitExit();
687 -
688 - var lines = child.stdout.str.split('\n');
689 - var tokens, i, j;
690 - for (i in lines)
691 - {
692 - tokens = lines[i].split(' ');
693 - for (j = 1; j < tokens.length; ++j)
694 - {
695 - if (tokens[j].length > 0)
696 - {
697 - return (parseInt(this._users()[tokens[0]]));
698 - }
699 - }
700 - }
701 -
702 - throw ('nobody logged into console');
703 - }
704 - }
705 -
706 -
707 -}
708 -function showActiveOnly(source)
709 -{
710 - var retVal = [];
711 - var unique = {};
712 - var usernames = [];
713 - var tmp;
714 -
715 - for (var i in source)
716 - {
717 - if (source[i].State == 'Active')
718 - {
719 - retVal.push(source[i]);
720 - tmp = (source[i].Domain ? (source[i].Domain + '\\') : '') + source[i].Username;
721 - if (!unique[tmp]) { unique[tmp] = tmp;}
722 - }
723 - }
724 -
725 - for (var i in unique)
726 - {
727 - usernames.push(i);
728 - }
729 -
730 - Object.defineProperty(retVal, 'usernames', { value: usernames });
731 - return (retVal);
732 -}
733 -function getTokens(str)
734 -{
735 - var columns = [];
736 - var i;
737 -
738 - columns.push(str.substring(0, (i=str.indexOf(' '))));
739 - while (str[++i] == ' ');
740 - columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
741 - while (str[++i] == ' ');
742 - columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
743 - while (str[++i] == ' ');
744 - var status = str.substring(i).trim();
745 - columns.push(status);
746 -
747 - return (columns);
748 -}
749 -
750 -module.exports = new UserSessions();
\ No newline at end of file
agents/modules_meshcore/x/win-message-pump.js deleted
-124
@@ -1,124 +0,0 @@
1 -/*
2 -Copyright 2018-2019 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -var WH_CALLWNDPROC = 4;
18 -var WM_QUIT = 0x0012;
19 -
20 -var GM = require('_GenericMarshal');
21 -
22 -function WindowsMessagePump(options)
23 -{
24 - this._ObjectID = 'win-message-pump';
25 - this._options = options;
26 - var emitterUtils = require('events').inherits(this);
27 - emitterUtils.createEvent('hwnd');
28 - emitterUtils.createEvent('error');
29 - emitterUtils.createEvent('message');
30 - emitterUtils.createEvent('exit');
31 -
32 - this._msg = GM.CreateVariable(GM.PointerSize == 4 ? 28 : 48);
33 - this._kernel32 = GM.CreateNativeProxy('Kernel32.dll');
34 - this._kernel32.mp = this;
35 - this._kernel32.CreateMethod('GetLastError');
36 - this._kernel32.CreateMethod('GetModuleHandleA');
37 -
38 - this._user32 = GM.CreateNativeProxy('User32.dll');
39 - this._user32.mp = this;
40 - this._user32.CreateMethod('GetMessageA');
41 - this._user32.CreateMethod('CreateWindowExA');
42 - this._user32.CreateMethod('TranslateMessage');
43 - this._user32.CreateMethod('DispatchMessageA');
44 - this._user32.CreateMethod('RegisterClassExA');
45 - this._user32.CreateMethod('DefWindowProcA');
46 - this._user32.CreateMethod('PostMessageA');
47 -
48 -
49 - this.wndclass = GM.CreateVariable(GM.PointerSize == 4 ? 48 : 80);
50 - this.wndclass.mp = this;
51 - this.wndclass.hinstance = this._kernel32.GetModuleHandleA(0);
52 - this.wndclass.cname = GM.CreateVariable('MainWWWClass');
53 - this.wndclass.wndproc = GM.GetGenericGlobalCallback(4);
54 - this.wndclass.wndproc.mp = this;
55 - this.wndclass.toBuffer().writeUInt32LE(this.wndclass._size);
56 - this.wndclass.cname.pointerBuffer().copy(this.wndclass.Deref(GM.PointerSize == 4 ? 40 : 64, GM.PointerSize).toBuffer());
57 - this.wndclass.wndproc.pointerBuffer().copy(this.wndclass.Deref(8, GM.PointerSize).toBuffer());
58 - this.wndclass.hinstance.pointerBuffer().copy(this.wndclass.Deref(GM.PointerSize == 4 ? 20 : 24, GM.PointerSize).toBuffer());
59 - this.wndclass.wndproc.on('GlobalCallback', function onWndProc(xhwnd, xmsg, wparam, lparam)
60 - {
61 - if (this.mp._hwnd != null && this.mp._hwnd.Val == xhwnd.Val)
62 - {
63 - // This is for us
64 - this.mp.emit('message', { message: xmsg.Val, wparam: wparam.Val, lparam: lparam.Val, lparam_hex: lparam.pointerBuffer().toString('hex') });
65 - return (this.mp._user32.DefWindowProcA(xhwnd, xmsg, wparam, lparam));
66 - }
67 - else if(this.mp._hwnd == null && this.CallingThread() == this.mp._user32.RegisterClassExA.async.threadId())
68 - {
69 - // This message was generated from our CreateWindowExA method
70 - return (this.mp._user32.DefWindowProcA(xhwnd, xmsg, wparam, lparam));
71 - }
72 - });
73 -
74 - this._user32.RegisterClassExA.async(this.wndclass).then(function ()
75 - {
76 - this.nativeProxy.CreateWindowExA.async(this.nativeProxy.RegisterClassExA.async, 0x00000088, this.nativeProxy.mp.wndclass.cname, 0, 0x00800000, 0, 0, 100, 100, 0, 0, 0, 0)
77 - .then(function(h)
78 - {
79 - if (h.Val == 0)
80 - {
81 - // Error creating hidden window
82 - this.nativeProxy.mp.emit('error', 'Error creating hidden window');
83 - }
84 - else
85 - {
86 - this.nativeProxy.mp._hwnd = h;
87 - this.nativeProxy.mp.emit('hwnd', h);
88 - this.nativeProxy.mp._startPump();
89 - }
90 - });
91 - });
92 - this._startPump = function _startPump()
93 - {
94 - this._user32.GetMessageA.async(this._user32.RegisterClassExA.async, this._msg, this._hwnd, 0, 0).then(function (r)
95 - {
96 - if(r.Val > 0)
97 - {
98 - this.nativeProxy.TranslateMessage.async(this.nativeProxy.RegisterClassExA.async, this.nativeProxy.mp._msg).then(function ()
99 - {
100 - this.nativeProxy.DispatchMessageA.async(this.nativeProxy.RegisterClassExA.async, this.nativeProxy.mp._msg).then(function ()
101 - {
102 - this.nativeProxy.mp._startPump();
103 - });
104 - });
105 - }
106 - else
107 - {
108 - // We got a 'QUIT' message
109 - delete this.nativeProxy.mp._hwnd;
110 - this.nativeProxy.mp.emit('exit', 0);
111 - }
112 - }, function (err) { this.nativeProxy.mp.stop(); });
113 - }
114 -
115 - this.stop = function stop()
116 - {
117 - if (this._hwnd)
118 - {
119 - this._user32.PostMessageA(this._hwnd, WM_QUIT, 0, 0);
120 - }
121 - };
122 -}
123 -
124 -module.exports = WindowsMessagePump;
agents/modules_meshcore/x/win-registry.js deleted
-218
@@ -1,218 +0,0 @@
1 -/*
2 -Copyright 2018 Intel Corporation
3 -
4 -Licensed under the Apache License, Version 2.0 (the "License");
5 -you may not use this file except in compliance with the License.
6 -You may obtain a copy of the License at
7 -
8 - http://www.apache.org/licenses/LICENSE-2.0
9 -
10 -Unless required by applicable law or agreed to in writing, software
11 -distributed under the License is distributed on an "AS IS" BASIS,
12 -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 -See the License for the specific language governing permissions and
14 -limitations under the License.
15 -*/
16 -
17 -var KEY_QUERY_VALUE = 0x0001;
18 -var KEY_ENUMERATE_SUB_KEYS = 0x0008;
19 -var KEY_WRITE = 0x20006;
20 -
21 -var KEY_DATA_TYPES =
22 - {
23 - REG_NONE: 0,
24 - REG_SZ: 1,
25 - REG_EXPAND_SZ: 2,
26 - REG_BINARY: 3,
27 - REG_DWORD: 4,
28 - REG_DWORD_BIG_ENDIAN: 5,
29 - REG_LINK: 6,
30 - REG_MULTI_SZ: 7,
31 - REG_RESOURCE_LIST: 8,
32 - REG_FULL_RESOURCE_DESCRIPTOR: 9,
33 - REG_RESOURCE_REQUIREMENTS_LIST: 10,
34 - REG_QWORD: 11
35 - };
36 -
37 -function windows_registry()
38 -{
39 - this._ObjectId = 'win-registry';
40 - this._marshal = require('_GenericMarshal');
41 - this._AdvApi = this._marshal.CreateNativeProxy('Advapi32.dll');
42 - this._AdvApi.CreateMethod('RegCreateKeyExA');
43 - this._AdvApi.CreateMethod('RegEnumKeyExA');
44 - this._AdvApi.CreateMethod('RegEnumValueA');
45 - this._AdvApi.CreateMethod('RegOpenKeyExA');
46 - this._AdvApi.CreateMethod('RegQueryInfoKeyA');
47 - this._AdvApi.CreateMethod('RegQueryValueExA');
48 - this._AdvApi.CreateMethod('RegCloseKey');
49 - this._AdvApi.CreateMethod('RegDeleteKeyA');
50 - this._AdvApi.CreateMethod('RegDeleteValueA');
51 - this._AdvApi.CreateMethod('RegSetValueExA');
52 - this.HKEY = { Root: Buffer.from('80000000', 'hex').swap32(), CurrentUser: Buffer.from('80000001', 'hex').swap32(), LocalMachine: Buffer.from('80000002', 'hex').swap32(), Users: Buffer.from('80000003', 'hex').swap32() };
53 -
54 - this.QueryKey = function QueryKey(hkey, path, key)
55 - {
56 - var err;
57 - var h = this._marshal.CreatePointer();
58 - var len = this._marshal.CreateVariable(4);
59 - var valType = this._marshal.CreateVariable(4);
60 - var HK = this._marshal.CreatePointer(hkey);
61 - var retVal = null;
62 - if (key) { key = this._marshal.CreateVariable(key); }
63 - if (!path) { path = ''; }
64 -
65 -
66 - if ((err = this._AdvApi.RegOpenKeyExA(HK, this._marshal.CreateVariable(path), 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, h).Val) != 0)
67 - {
68 - throw ('Opening Registry Key: ' + path + ' => Returned Error: ' + err);
69 - }
70 -
71 - if ((path == '' && !key) || !key)
72 - {
73 - var result = { subkeys: [], values: [] };
74 -
75 - // Enumerate keys
76 - var achClass = this._marshal.CreateVariable(1024);
77 - var achKey = this._marshal.CreateVariable(1024);
78 - var achValue = this._marshal.CreateVariable(32768);
79 - var achValueSize = this._marshal.CreateVariable(4);
80 - var nameSize = this._marshal.CreateVariable(4);
81 - var achClassSize = this._marshal.CreateVariable(4); achClassSize.toBuffer().writeUInt32LE(1024);
82 - var numSubKeys = this._marshal.CreateVariable(4);
83 - var numValues = this._marshal.CreateVariable(4);
84 - var longestSubkeySize = this._marshal.CreateVariable(4);
85 - var longestClassString = this._marshal.CreateVariable(4);
86 - var longestValueName = this._marshal.CreateVariable(4);
87 - var longestValueData = this._marshal.CreateVariable(4);
88 - var securityDescriptor = this._marshal.CreateVariable(4);
89 - var lastWriteTime = this._marshal.CreateVariable(8);
90 -
91 - retVal = this._AdvApi.RegQueryInfoKeyA(h.Deref(), achClass, achClassSize, 0,
92 - numSubKeys, longestSubkeySize, longestClassString, numValues,
93 - longestValueName, longestValueData, securityDescriptor, lastWriteTime);
94 - if (retVal.Val != 0) { throw ('RegQueryInfoKeyA() returned error: ' + retVal.Val); }
95 - for(var i = 0; i < numSubKeys.toBuffer().readUInt32LE(); ++i)
96 - {
97 - nameSize.toBuffer().writeUInt32LE(1024);
98 - retVal = this._AdvApi.RegEnumKeyExA(h.Deref(), i, achKey, nameSize, 0, 0, 0, lastWriteTime);
99 - if(retVal.Val == 0)
100 - {
101 - result.subkeys.push(achKey.String);
102 - }
103 - }
104 - for (var i = 0; i < numValues.toBuffer().readUInt32LE() ; ++i)
105 - {
106 - achValueSize.toBuffer().writeUInt32LE(32768);
107 - if(this._AdvApi.RegEnumValueA(h.Deref(), i, achValue, achValueSize, 0, 0, 0, 0).Val == 0)
108 - {
109 - result.values.push(achValue.String);
110 - }
111 - }
112 - return (result);
113 - }
114 -
115 - if(this._AdvApi.RegQueryValueExA(h.Deref(), key, 0, 0, 0, len).Val == 0)
116 - {
117 - var data = this._marshal.CreateVariable(len.toBuffer().readUInt32LE());
118 - if (this._AdvApi.RegQueryValueExA(h.Deref(), key, 0, valType, data, len).Val == 0)
119 - {
120 - switch(valType.toBuffer().readUInt32LE())
121 - {
122 - case KEY_DATA_TYPES.REG_DWORD:
123 - retVal = data.toBuffer().readUInt32LE();
124 - break;
125 - case KEY_DATA_TYPES.REG_DWORD_BIG_ENDIAN:
126 - retVal = data.toBuffer().readUInt32BE();
127 - break;
128 - case KEY_DATA_TYPES.REG_SZ:
129 - retVal = data.String;
130 - break;
131 - case KEY_DATA_TYPES.REG_BINARY:
132 - default:
133 - retVal = data.toBuffer();
134 - retVal._data = data;
135 - break;
136 - }
137 - }
138 - }
139 - else
140 - {
141 - this._AdvApi.RegCloseKey(h.Deref());
142 - throw ('Not Found');
143 - }
144 - this._AdvApi.RegCloseKey(h.Deref());
145 - return (retVal);
146 - };
147 - this.WriteKey = function WriteKey(hkey, path, key, value)
148 - {
149 - var result;
150 - var h = this._marshal.CreatePointer();
151 -
152 - if (this._AdvApi.RegCreateKeyExA(this._marshal.CreatePointer(hkey), this._marshal.CreateVariable(path), 0, 0, 0, KEY_WRITE, 0, h, 0).Val != 0)
153 - {
154 - throw ('Error Opening Registry Key: ' + path);
155 - }
156 -
157 - var data;
158 - var dataType;
159 -
160 - switch(typeof(value))
161 - {
162 - case 'boolean':
163 - dataType = KEY_DATA_TYPES.REG_DWORD;
164 - data = this._marshal.CreateVariable(4);
165 - data.toBuffer().writeUInt32LE(value ? 1 : 0);
166 - break;
167 - case 'number':
168 - dataType = KEY_DATA_TYPES.REG_DWORD;
169 - data = this._marshal.CreateVariable(4);
170 - data.toBuffer().writeUInt32LE(value);
171 - break;
172 - case 'string':
173 - dataType = KEY_DATA_TYPES.REG_SZ;
174 - data = this._marshal.CreateVariable(value);
175 - break;
176 - default:
177 - dataType = KEY_DATA_TYPES.REG_BINARY;
178 - data = this._marshal.CreateVariable(value.length);
179 - value.copy(data.toBuffer());
180 - break;
181 - }
182 -
183 - if(this._AdvApi.RegSetValueExA(h.Deref(), this._marshal.CreateVariable(key), 0, dataType, data, data._size).Val != 0)
184 - {
185 - this._AdvApi.RegCloseKey(h.Deref());
186 - throw ('Error writing reg key: ' + key);
187 - }
188 - this._AdvApi.RegCloseKey(h.Deref());
189 - };
190 - this.DeleteKey = function DeleteKey(hkey, path, key)
191 - {
192 - if(!key)
193 - {
194 - if(this._AdvApi.RegDeleteKeyA(this._marshal.CreatePointer(hkey), this._marshal.CreateVariable(path)).Val != 0)
195 - {
196 - throw ('Error Deleting Key: ' + path);
197 - }
198 - }
199 - else
200 - {
201 - var h = this._marshal.CreatePointer();
202 - var result;
203 - if (this._AdvApi.RegOpenKeyExA(this._marshal.CreatePointer(hkey), this._marshal.CreateVariable(path), 0, KEY_QUERY_VALUE | KEY_WRITE, h).Val != 0)
204 - {
205 - throw ('Error Opening Registry Key: ' + path);
206 - }
207 - if ((result = this._AdvApi.RegDeleteValueA(h.Deref(), this._marshal.CreateVariable(key)).Val) != 0)
208 - {
209 - this._AdvApi.RegCloseKey(h.Deref());
210 - throw ('Error[' + result + '] Deleting Key: ' + path + '.' + key);
211 - }
212 - this._AdvApi.RegCloseKey(h.Deref());
213 - }
214 - };
215 -}
216 -
217 -module.exports = new windows_registry();
218 -