2* @description MeshCentral IP KVM Management Module
3* @author Ylian Saint-Hilaire
4* @copyright Intel Corporation 2021-2022
9function CreateIPKVMManager(parent) {
12 obj.managedGroups = {} // meshid --> Manager
13 obj.managedPorts = {} // nodeid --> PortInfo
16 const MESHRIGHT_EDITMESH = 0x00000001; // 1
17 const MESHRIGHT_MANAGEUSERS = 0x00000002; // 2
18 const MESHRIGHT_MANAGECOMPUTERS = 0x00000004; // 4
19 const MESHRIGHT_REMOTECONTROL = 0x00000008; // 8
20 const MESHRIGHT_AGENTCONSOLE = 0x00000010; // 16
21 const MESHRIGHT_SERVERFILES = 0x00000020; // 32
22 const MESHRIGHT_WAKEDEVICE = 0x00000040; // 64
23 const MESHRIGHT_SETNOTES = 0x00000080; // 128
24 const MESHRIGHT_REMOTEVIEWONLY = 0x00000100; // 256
25 const MESHRIGHT_NOTERMINAL = 0x00000200; // 512
26 const MESHRIGHT_NOFILES = 0x00000400; // 1024
27 const MESHRIGHT_NOAMT = 0x00000800; // 2048
28 const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000; // 4096
29 const MESHRIGHT_LIMITEVENTS = 0x00002000; // 8192
30 const MESHRIGHT_CHATNOTIFY = 0x00004000; // 16384
31 const MESHRIGHT_UNINSTALL = 0x00008000; // 32768
32 const MESHRIGHT_NODESKTOP = 0x00010000; // 65536
33 const MESHRIGHT_REMOTECOMMAND = 0x00020000; // 131072
34 const MESHRIGHT_RESETOFF = 0x00040000; // 262144
35 const MESHRIGHT_GUESTSHARING = 0x00080000; // 524288
36 const MESHRIGHT_DEVICEDETAILS = 0x00100000; // ?1048576?
37 const MESHRIGHT_ADMIN = 0xFFFFFFFF;
39 // Subscribe for mesh creation events
40 parent.AddEventDispatch(['server-createmesh', 'server-deletemesh', 'server-editmesh', 'devport-operation'], obj);
41 obj.HandleEvent = function (source, event, ids, id) {
42 if ((event == null) || (event.mtype != 4)) return;
43 if (event.action == 'createmesh') {
44 // Start managing this new device group
45 startManagement(parent.webserver.meshes[event.meshid]);
46 } else if (event.action == 'deletemesh') {
47 // Stop managing this device group
48 stopManagement(event.meshid);
49 } else if ((event.action == 'meshchange') && (event.relayid != null)) {
50 // See if the relayid changed
51 changeManagementRelayId(event.meshid, event.relayid);
52 } else if ((event.action == 'turnon') || (event.action == 'turnoff')) {
53 // Perform power operation
54 const manager = obj.managedGroups[event.meshid];
55 if ((manager) && (manager.powerOperation)) { manager.powerOperation(event); }
59 // Run thru the list of device groups that require
60 for (var i in parent.webserver.meshes) {
61 const mesh = parent.webserver.meshes[i];
62 if ((mesh.mtype == 4) && (mesh.deleted == null)) { startManagement(mesh); }
65 // Start managing a IP KVM device
66 function startManagement(mesh) {
67 if ((mesh == null) || (mesh.mtype != 4) || (mesh.kvm == null) || (mesh.deleted != null) || (obj.managedGroups[mesh._id] != null)) return;
68 var port = 443, hostSplit = mesh.kvm.host.split(':'), host = hostSplit[0];
69 if (hostSplit.length == 2) { port = parseInt(hostSplit[1]); }
70 if (mesh.kvm.model == 1) { // Raritan KX III
71 const manager = CreateRaritanKX3Manager(obj, host, port, mesh.kvm.user, mesh.kvm.pass);
72 manager.meshid = mesh._id;
73 manager.relayid = mesh.relayid;
74 manager.domainid = mesh._id.split('/')[1];
75 obj.managedGroups[mesh._id] = manager;
76 manager.onStateChanged = onStateChanged;
77 manager.onPortsChanged = onPortsChanged;
79 } else if (mesh.kvm.model == 2) { // WebPowerSwitch 7
80 const manager = CreateWebPowerSwitch(obj, host, port, mesh.kvm.user, mesh.kvm.pass);
81 manager.meshid = mesh._id;
82 manager.relayid = mesh.relayid;
83 manager.domainid = mesh._id.split('/')[1];
84 obj.managedGroups[mesh._id] = manager;
85 manager.onStateChanged = onStateChanged;
86 manager.onPortsChanged = onPortsChanged;
91 // Stop managing a IP KVM device
92 function stopManagement(meshid) {
93 const manager = obj.managedGroups[meshid];
94 if (manager != null) {
95 // Remove all managed ports
96 for (var i = 0; i < manager.ports.length; i++) {
97 const port = manager.ports[i];
98 const nodeid = generateIpKvmNodeId(manager.meshid, port.PortId, manager.domainid);
99 delete obj.managedPorts[nodeid]; // Remove the managed port
102 // Remove the manager
103 delete obj.managedGroups[meshid];
108 // Change the relayid of a managed device if needed
109 function changeManagementRelayId(meshid, relayid) {
110 const manager = obj.managedGroups[meshid];
111 if ((manager != null) && (manager.relayid != null) && (manager.relayid != relayid)) { manager.updateRelayId(relayid); }
114 // Called when a KVM device changes state
115 function onStateChanged(sender, state) {
117 console.log('State: ' + ['Disconnected', 'Connecting', 'Connected'][state]);
119 if (sender.deviceModel) { console.log('DeviceModel:', sender.deviceModel); }
120 if (sender.firmwareVersion) { console.log('FirmwareVersion:', sender.firmwareVersion); }
125 // Disconnect all nodes for this device group
126 for (var i in sender.ports) {
127 const port = sender.ports[i];
128 const nodeid = generateIpKvmNodeId(sender.meshid, port.PortId, sender.domainid);
129 if (obj.managedPorts[nodeid] != null) {
130 parent.ClearConnectivityState(sender.meshid, nodeid, 1, null, null);
131 delete obj.managedPorts[nodeid];
138 // Called when a KVM device changes state
139 function onPortsChanged(sender, updatedPorts) {
140 for (var i = 0; i < updatedPorts.length; i++) {
141 const port = sender.ports[updatedPorts[i]];
142 const nodeid = generateIpKvmNodeId(sender.meshid, port.PortId, sender.domainid);
143 if ((port.Status == 1) && (port.Class == 'PDU')) {
144 //console.log(port.PortNumber + ', ' + port.PortId + ', ' + port.Name + ', ' + port.State);
145 if ((obj.managedPorts[nodeid] == null) || (obj.managedPorts[nodeid].name != port.Name)) {
146 parent.db.Get(nodeid, function (err, nodes) {
147 if ((err != null) || (nodes == null)) return;
148 const mesh = parent.webserver.meshes[sender.meshid];
149 if (nodes.length == 0) {
150 // The device does not exist, create it
151 const device = { type: 'node', mtype: 4, _id: nodeid, icon: 4, meshid: sender.meshid, name: port.Name, rname: port.Name, domain: sender.domainid, portid: port.PortId, portnum: port.PortNumber, porttype: 'PDU' };
152 parent.db.Set(device);
154 // Event the new node
155 parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'addnode', nodeid: nodeid, node: device, msgid: 57, msgArgs: [port.Name, mesh.name], msg: ('Added device ' + port.Name + ' to device group ' + mesh.name), domain: sender.domainid });
157 // The device exists, update it
159 const device = nodes[0];
160 if (device.rname != port.Name) { device.rname = port.Name; changed = true; } // Update the device port name
161 if ((mesh.flags) && (mesh.flags & 2) && (device.name != port.Name)) { device.name = port.Name; changed = true; } // Sync device name to port name
163 // Update the database and event the node change
164 parent.db.Set(device);
165 parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'changenode', nodeid: nodeid, node: device, domain: sender.domainid, nolog: 1 });
169 // Set the connectivity state if needed
170 if (obj.managedPorts[nodeid] == null) {
171 parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, port.State ? 1 : 8, null, null);
172 obj.managedPorts[nodeid] = { name: port.Name, meshid: sender.meshid, portid: port.PortId, portType: port.PortType, portNo: port.PortIndex };
176 // Update connectivity state
177 parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, port.State ? 1 : 8, null, null);
179 } else if ((port.Status == 1) && (port.Class == 'KVM')) {
180 //console.log(port.PortNumber + ', ' + port.PortId + ', ' + port.Name + ', ' + port.Type + ', ' + ((port.StatAvailable == 0) ? 'Idle' : 'Connected'));
181 if ((obj.managedPorts[nodeid] == null) || (obj.managedPorts[nodeid].name != port.Name)) {
182 parent.db.Get(nodeid, function (err, nodes) {
183 if ((err != null) || (nodes == null)) return;
184 const mesh = parent.webserver.meshes[sender.meshid];
185 if (nodes.length == 0) {
186 // The device does not exist, create it
187 const device = { type: 'node', mtype: 4, _id: nodeid, icon: 1, meshid: sender.meshid, name: port.Name, rname: port.Name, domain: sender.domainid, porttype: port.Type, portid: port.PortId, portnum: port.PortNumber };
188 parent.db.Set(device);
190 // Event the new node
191 parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'addnode', nodeid: nodeid, node: device, msgid: 57, msgArgs: [port.Name, mesh.name], msg: ('Added device ' + port.Name + ' to device group ' + mesh.name), domain: sender.domainid });
193 // The device exists, update it
195 const device = nodes[0];
196 if (device.rname != port.Name) { device.rname = port.Name; changed = true; } // Update the device port name
197 if ((mesh.flags) && (mesh.flags & 2) && (device.name != port.Name)) { device.name = port.Name; changed = true; } // Sync device name to port name
199 // Update the database and event the node change
200 parent.db.Set(device);
201 parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'changenode', nodeid: nodeid, node: device, domain: sender.domainid, nolog: 1 });
205 // Set the connectivity state if needed
206 if (obj.managedPorts[nodeid] == null) {
207 parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, 1, null, null);
208 obj.managedPorts[nodeid] = { name: port.Name, meshid: sender.meshid, portid: port.PortId, portType: port.PortType, portNo: port.PortIndex };
212 const portInfo = obj.managedPorts[nodeid];
213 if ((portInfo.sessions != null) != (port.StatAvailable != 0)) {
214 if (port.StatAvailable != 0) { portInfo.sessions = { kvm: { 'busy': 1 } } } else { delete portInfo.sessions; }
216 // Event the new sessions, this will notify everyone that agent sessions have changed
217 var event = { etype: 'node', action: 'devicesessions', nodeid: nodeid, domain: sender.domainid, sessions: portInfo.sessions, nolog: 1 };
218 parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, event);
223 const portInfo = obj.managedPorts[nodeid];
224 if ((portInfo.sessions != null) != (port.StatAvailable != 0)) {
225 if (port.StatAvailable != 0) { portInfo.sessions = { kvm: { 'busy': 1 } } } else { delete portInfo.sessions; }
227 // Event the new sessions, this will notify everyone that agent sessions have changed
228 var event = { etype: 'node', action: 'devicesessions', nodeid: nodeid, domain: sender.domainid, sessions: portInfo.sessions, nolog: 1 };
229 parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, event);
233 if (obj.managedPorts[nodeid] != null) {
234 // This port is no longer connected
235 parent.ClearConnectivityState(sender.meshid, nodeid, 1, null, null);
236 const mesh = parent.webserver.meshes[sender.meshid];
238 // If the device group policy is set to auto-remove devices, remove it now
239 if ((mesh != null) && (mesh.flags) && (mesh.flags & 1)) { // Auto-remove devices
240 parent.db.Remove(nodeid); // Remove node with that id
241 parent.db.Remove('nt' + nodeid); // Remove notes
242 parent.db.Remove('lc' + nodeid); // Remove last connect time
243 parent.db.Remove('al' + nodeid); // Remove error log last time
244 parent.db.RemoveAllNodeEvents(nodeid); // Remove all events for this node
245 parent.db.removeAllPowerEventsForNode(nodeid); // Remove all power events for this node
247 // Event node deletion
248 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'removenode', nodeid: nodeid, domain: domain.id, nolog: 1 });
251 // Remove the managed port
252 delete obj.managedPorts[nodeid];
258 // Generate the nodeid from the device group and device identifier
259 function generateIpKvmNodeId(meshid, portid, domainid) {
260 return 'node/' + domainid + '/' + parent.crypto.createHash('sha384').update(Buffer.from(meshid + '/' + portid)).digest().toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
263 // Parse an incoming HTTP request URL
264 function parseIpKvmUrl(domain, url) {
265 const q = require('url').parse(url, true);
266 const i = q.path.indexOf('/ipkvm.ashx/');
267 if (i == -1) return null;
268 const urlargs = q.path.substring(i + 12).split('/');
269 if (urlargs[0].length != 64) return null;
270 const nodeid = 'node/' + domain.id + '/' + urlargs[0];
271 const nid = urlargs[0];
272 const kvmport = obj.managedPorts[nodeid];
273 if (kvmport == null) return null;
274 const kvmmanager = obj.managedGroups[kvmport.meshid];
275 if (kvmmanager == null) return null;
277 var relurl = '/' + urlargs.join('/');
278 if (relurl.endsWith('/.websocket')) { relurl = relurl.substring(0, relurl.length - 11); }
279 return { domain: domain.id, relurl: relurl, preurl: q.path.substring(0, i + 76), nodeid: nodeid, nid: nid, kvmmanager: kvmmanager, kvmport: kvmport };
282 // Handle a IP-KVM HTTP get request
283 obj.handleIpKvmGet = function (domain, req, res, next) {
284 // Parse the URL and get information about this KVM port
285 const reqinfo = parseIpKvmUrl(domain, req.url);
286 if (reqinfo == null) { next(); return; }
289 if ((req.session == null) || (req.session.userid == null)) { next(); return; }
290 const user = parent.webserver.users[req.session.userid];
291 if (user == null) { next(); return; }
292 const rights = parent.webserver.GetNodeRights(user, reqinfo.kvmmanager.meshid, reqinfo.nodeid);
293 if ((rights & MESHRIGHT_REMOTECONTROL) == 0) { next(); return; }
295 // Process the request
296 reqinfo.kvmmanager.handleIpKvmGet(domain, reqinfo, req, res, next);
299 // Handle a IP-KVM HTTP websocket request
300 obj.handleIpKvmWebSocket = function (domain, ws, req) {
301 // Parse the URL and get information about this KVM port
302 const reqinfo = parseIpKvmUrl(domain, req.url);
303 if (reqinfo == null) { try { ws.close(); } catch (ex) { } return; }
306 if ((req.session == null) || (req.session.userid == null)) { try { ws.close(); } catch (ex) { } return; }
307 const user = parent.webserver.users[req.session.userid];
308 if (user == null) { try { ws.close(); } catch (ex) { } return; }
309 const rights = parent.webserver.GetNodeRights(user, reqinfo.kvmmanager.meshid, reqinfo.nodeid);
310 if ((rights & MESHRIGHT_REMOTECONTROL) == 0) { try { ws.close(); } catch (ex) { } return; }
312 // Add more logging data to the request information
313 reqinfo.clientIp = req.clientIp;
314 reqinfo.userid = req.session.userid;
315 reqinfo.username = user.name;
317 // Process the request
318 reqinfo.kvmmanager.handleIpKvmWebSocket(domain, reqinfo, ws, req);
326// Create Raritan Dominion KX III Manager
327function CreateRaritanKX3Manager(parent, hostname, port, username, password) {
328 const https = require('https');
330 var updateTimer = null;
331 var retryTimer = null;
333 obj.authCookie = null;
334 obj.state = 0; // 0 = Disconnected, 1 = Connecting, 2 = Connected
339 obj.deviceHash = null;
343 obj.onStateChanged = null;
344 obj.onPortsChanged = null;
346 function onCheckServerIdentity(cert) {
347 console.log('TODO: Certificate Check');
350 obj.start = function () {
351 if (obj.started) return;
354 obj.router = CreateMiniRouter(parent, obj.relayid, hostname, port);
355 obj.router.start(function () { connect(); });
361 obj.stop = function () {
362 if (!obj.started) return;
364 if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
366 if (obj.router) { obj.router.stop(); delete obj.router; }
369 // If the relay device has changed, update our router
370 obj.updateRelayId = function (relayid) {
371 obj.relayid = relayid;
372 if (obj.router != null) { obj.router.nodeid = relayid; }
375 function setState(newState) {
376 if (obj.state == newState) return;
377 obj.state = newState;
378 if (obj.onStateChanged != null) { obj.onStateChanged(obj, newState); }
379 if ((newState == 2) && (updateTimer == null)) { updateTimer = setInterval(obj.update, 10000); }
380 if ((newState != 2) && (updateTimer != null)) { clearInterval(updateTimer); updateTimer = null; }
381 if ((newState == 0) && (obj.started == true) && (retryTimer == null)) { retryTimer = setTimeout(connect, 20000); }
382 if (newState == 0) { obj.ports = []; obj.portCount = 0; obj.deviceCount = 0; }
386 if (obj.state != 0) return;
387 setState(1); // 1 = Connecting
388 obj.authCookie = null;
389 if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
390 const data = Buffer.from('is_dotnet=0&is_javafree=0&is_standalone_client=0&is_javascript_kvm_client=1&is_javascript_rsc_client=1&login=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password) + '&action_login=Login');
394 rejectUnauthorized: false,
395 checkServerIdentity: onCheckServerIdentity,
396 path: '/auth.asp?client=javascript', // ?client=standalone
399 'Content-Type': 'text/html; charset=UTF-8',
400 'Content-Length': data.length
403 const req = https.request(options, function (res) {
404 if (obj.state == 0) return;
405 if ((res.statusCode != 302) || (res.headers['set-cookie'] == null) || (res.headers['location'] == null)) { setState(0); return; }
406 for (var i in res.headers['set-cookie']) { if (res.headers['set-cookie'][i].startsWith('pp_session_id=')) { obj.authCookie = res.headers['set-cookie'][i].substring(14).split(';')[0]; } }
407 if (obj.authCookie == null) { setState(0); return; }
408 res.on('data', function (d) { })
409 fetchInitialInformation();
411 req.on('error', function (error) { setState(0); });
412 req.on('timeout', function () { setState(0); });
417 function checkCookie() {
418 if (obj.state != 2) return;
422 rejectUnauthorized: false,
423 checkServerIdentity: onCheckServerIdentity,
424 path: '/cookiecheck.asp',
427 'Content-Type': 'text/html; charset=UTF-8',
428 'Cookie': 'pp_session_id=' + obj.authCookie
431 const req = https.request(options, function (res) {
432 if (obj.state == 0) return;
433 if (res.statusCode != 302) { setState(0); return; }
434 if (res.headers['set-cookie'] != null) { for (var i in res.headers['set-cookie']) { if (res.headers['set-cookie'][i].startsWith('pp_session_id=')) { obj.authCookie = res.headers['set-cookie'][i].substring(14).split(';')[0]; } } }
435 res.on('data', function (d) { })
437 req.on('error', function (error) { setState(0); });
438 req.on('timeout', function () { setState(0); });
442 function fetchInitialInformation() {
443 obj.fetch('/webs_cron.asp?_portsstatushash=&_devicesstatushash=&webs_job=sidebarupdates', null, null, function (server, tag, data) {
444 data = data.toString();
445 const parsed = parseJsScript(data);
446 for (var i in parsed['updateSidebarPanel']) {
447 if (parsed['updateSidebarPanel'][i][0] == "cron_device") {
448 obj.firmwareVersion = getSubString(parsed['updateSidebarPanel'][i][1], "Firmware: ", "<");
449 obj.deviceModel = getSubString(parsed['updateSidebarPanel'][i][1], "<div class=\"device-model\">", "<");
452 obj.fetch('/sidebar.asp', null, null, function (server, tag, data) {
453 data = data.toString();
454 var dataBlock = getSubString(data, "updateKVMLinkHintOnContainer();", "devices.resetDevicesNew(1);");
455 if (dataBlock == null) { setState(0); return; }
456 const parsed = parseJsScript(dataBlock);
457 obj.portCount = parseInt(parsed['updatePortStatus'][0][0]) - 2;
458 obj.portHash = parsed['updatePortStatus'][0][1];
459 obj.deviceCount = parseInt(parsed['updateDeviceStatus'][0][0]);
460 obj.deviceHash = parsed['updateDeviceStatus'][0][1];
461 var updatedPorts = [];
462 for (var i = 0; i < parsed['addPortNew'].length; i++) {
463 const portInfo = parsePortInfo(parsed['addPortNew'][i]);
464 obj.ports[portInfo.hIndex] = portInfo;
465 updatedPorts.push(portInfo.hIndex);
468 if (obj.onPortsChanged != null) { obj.onPortsChanged(obj, updatedPorts); }
473 obj.update = function () {
474 obj.fetch('/webs_cron.asp?_portsstatushash=' + obj.portHash + '&_devicesstatushash=' + obj.deviceHash, null, null, function (server, tag, data) {
475 data = data.toString();
476 const parsed = parseJsScript(data);
477 if (parsed['updatePortStatus']) {
478 obj.portCount = parseInt(parsed['updatePortStatus'][0][0]) - 2;
479 obj.portHash = parsed['updatePortStatus'][0][1];
481 if (parsed['updateDeviceStatus']) {
482 obj.deviceCount = parseInt(parsed['updateDeviceStatus'][0][0]);
483 obj.deviceHash = parsed['updateDeviceStatus'][0][1];
485 if (parsed['updatePort']) {
486 var updatedPorts = [];
487 for (var i = 0; i < parsed['updatePort'].length; i++) {
488 const portInfo = parsePortInfo(parsed['updatePort'][i]);
489 obj.ports[portInfo.hIndex] = portInfo;
490 updatedPorts.push(portInfo.hIndex);
492 if ((updatedPorts.length > 0) && (obj.onPortsChanged != null)) { obj.onPortsChanged(obj, updatedPorts); }
497 function parsePortInfo(args) {
499 for (var i = 0; i < args.length; i++) {
500 var parsed = parseJsScript(args[i]);
501 var v = parsed.J[0][1], vv = parseInt(v);
502 out[parsed.J[0][0]] = (v == vv) ? vv : v;
507 function getSubString(str, start, end) {
508 var i = str.indexOf(start);
509 if (i < 0) return null;
510 str = str.substring(i + start.length);
511 i = str.indexOf(end);
512 if (i >= 0) { str = str.substring(0, i); }
516 // Parse JavaScript code calls
517 function parseJsScript(str) {
519 var functionName = '';
523 for (var i = 0; i < str.length; i++) {
524 if (stack.length == 0) {
526 if (isAlphaNumeric(str[i])) { functionName += str[i]; } else { functionName = ''; }
531 if (str[i] == stack[stack.length - 1]) {
532 if (stack.length > 1) { if (arg == null) { arg = str[i]; } else { arg += str[i]; } }
533 if (stack.length == 2) {
534 if (arg != null) { args.push(trimQuotes(arg)); }
536 } else if (stack.length == 1) {
537 if (arg != null) { args.push(trimQuotes(arg)); arg = null; }
538 if (args.length > 0) {
539 if (out[functionName] == null) {
540 out[functionName] = [args];
542 out[functionName].push(args);
548 } else if ((str[i] == '\'') || (str[i] == '"') || (str[i] == '(')) {
549 if (str[i] == '(') { stack.push(')'); } else { stack.push(str[i]); }
550 if (stack.length > 0) {
551 if (arg == null) { arg = str[i]; } else { arg += str[i]; }
554 if ((stack.length == 1) && (str[i] == ',')) {
555 if (arg != null) { args.push(trimQuotes(arg)); arg = null; }
557 if (stack.length > 0) { if (arg == null) { arg = str[i]; } else { arg += str[i]; } }
565 function trimQuotes(str) {
566 if ((str == null) || (str.length < 2)) return str;
568 if ((str[0] == '\'') && (str[str.length - 1] == '\'')) { return str.substring(1, str.length - 1); }
569 if ((str[0] == '"') && (str[str.length - 1] == '"')) { return str.substring(1, str.length - 1); }
573 function isAlphaNumeric(char) {
574 return ((char >= 'A') && (char <= 'Z')) || ((char >= 'a') && (char <= 'z')) || ((char >= '0') && (char <= '9'));
577 obj.fetch = function (url, postdata, tag, func) {
578 if (obj.state == 0) return;
582 hostname: obj.router ? 'localhost' : hostname,
583 port: obj.router ? obj.router.tcpServerPort : port,
584 rejectUnauthorized: false,
585 checkServerIdentity: onCheckServerIdentity,
587 method: (postdata != null) ? 'POST' : 'GET',
589 'Content-Type': 'text/html; charset=UTF-8',
590 'Cookie': 'pp_session_id=' + obj.authCookie
593 const req = https.request(options, function (res) {
594 if (obj.state == 0) return;
595 if (res.statusCode != 200) { setState(0); return; }
596 if (res.headers['set-cookie'] != null) { for (var i in res.headers['set-cookie']) { if (res.headers['set-cookie'][i].startsWith('pp_session_id=')) { obj.authCookie = res.headers['set-cookie'][i].substring(14).split(';')[0]; } } }
597 res.on('data', function (d) { data.push(d); });
598 res.on('end', function () {
599 // This line is used for debugging only, used to swap a file.
600 //if (url.endsWith('js_kvm_client.1604062083669.min.js')) { data = [ parent.parent.fs.readFileSync('c:\\tmp\\js_kvm_client.1604062083669.min.js') ] ; }
601 func(obj, tag, Buffer.concat(data), res);
604 req.on('error', function (error) { setState(0); });
605 req.on('timeout', function () { setState(0); });
609 // Handle a IP-KVM HTTP get request
610 obj.handleIpKvmGet = function (domain, reqinfo, req, res, next) {
611 if (reqinfo.relurl == '/') { res.redirect(reqinfo.preurl + '/jsclient/Client.asp'); return; }
613 // Example: /jsclient/Client.asp#portId=P_000d5d20f64c_1
614 obj.fetch(reqinfo.relurl, null, [res, reqinfo], function (server, args, data, rres) {
615 const resx = args[0], xreqinfo = args[1];
616 if (rres.headers['content-type']) { resx.set('content-type', rres.headers['content-type']); }
617 if (xreqinfo.relurl.startsWith('/js/js_kvm_client.')) {
618 data = data.toString();
619 // Since our cookies can't be read from the html page for security, we embed a dummy cookie into the page.
620 data = data.replace('module$js$helper$Extensions.Utils.getCookieValue("pp_session_id")', '"DUMMCOOKIEY"');
621 // Add the connection information directly into the file.
622 data = data.replace('\'use strict\';', '\'use strict\';sessionStorage.setItem("portPermission","CCC");sessionStorage.setItem("appId","1638838693725_3965868704642470");sessionStorage.setItem("portId","' + xreqinfo.kvmport.portid + '");sessionStorage.setItem("channelName","' + xreqinfo.kvmport.name + '");sessionStorage.setItem("portType","' + xreqinfo.kvmport.portType + '");sessionStorage.setItem("portNo","' + xreqinfo.kvmport.portNo + '");');
623 // Replace the WebSocket code in one of the files to make it work with our server.
624 data = data.replace('b=new WebSocket(e+"//"+c+"/"+g);', 'b=new WebSocket(e+"//"+c+"/ipkvm.ashx/' + xreqinfo.nid + '/"+g);');
630 function logConnection(wsClient) {
631 const kvmport = wsClient.kvmport
632 const reqinfo = wsClient.reqinfo;
633 var event = { etype: 'relay', action: 'relaylog', domain: reqinfo.domain, userid: reqinfo.userid, username: reqinfo.username, msgid: 15, msgArgs: [kvmport.portid, reqinfo.clientIp, kvmport.portNo], msg: 'Started desktop session' + ' \"' + kvmport.portid + '\" from ' + reqinfo.clientIp + ' to ' + kvmport.portNo, protocol: 2, nodeid: reqinfo.nodeid };
634 parent.parent.DispatchEvent(['*', reqinfo.userid, reqinfo.nodeid, kvmport.meshid], obj, event);
637 function logDisconnection(wsClient) {
638 const kvmport = wsClient.kvmport
639 const reqinfo = wsClient.reqinfo;
640 var event = { etype: 'relay', action: 'relaylog', domain: reqinfo.domain, userid: reqinfo.userid, username: reqinfo.username, msgid: 11, msgArgs: [kvmport.portid, reqinfo.clientIp, kvmport.portNo, Math.floor((Date.now() - kvmport.connectionStart) / 1000)], msg: 'Ended desktop session' + ' \"' + kvmport.portid + '\" from ' + reqinfo.clientIp + ' to ' + kvmport.portNo + ', ' + Math.floor((Date.now() - kvmport.connectionStart) / 1000) + ' second(s)', protocol: 2, nodeid: reqinfo.nodeid, bytesin: kvmport.bytesIn, bytesout: kvmport.bytesOut };
641 parent.parent.DispatchEvent(['*', reqinfo.userid, reqinfo.nodeid, kvmport.meshid], obj, event);
643 delete kvmport.bytesIn;
644 delete kvmport.bytesOut;
645 delete kvmport.connectionStart;
646 delete wsClient.reqinfo;
649 // Handle a IP-KVM HTTP websocket request
650 obj.handleIpKvmWebSocket = function (domain, reqinfo, ws, req) {
652 //console.log('handleIpKvmWebSocket', reqinfo.preurl);
654 if (reqinfo.kvmport.wsClient != null) {
655 // Relay already open
656 //console.log('IPKVM Relay already present');
657 try { ws.close(); } catch (ex) { }
659 // Setup a websocket-to-websocket relay
662 rejectUnauthorized: false,
663 servername: 'raritan', // We set this to remove the IP address warning from NodeJS.
664 headers: { Cookie: 'pp_session_id=' + obj.authCookie + '; view_length=32' }
666 parent.parent.debug('relay', 'IPKVM: Relay connecting to: wss://' + hostname + ':' + port + '/rfb');
667 const WebSocket = require('ws');
668 reqinfo.kvmport.wsClient = new WebSocket('wss://' + hostname + ':' + port + '/rfb', options);
669 reqinfo.kvmport.wsClient.wsBrowser = ws;
670 ws.wsClient = reqinfo.kvmport.wsClient;
671 reqinfo.kvmport.wsClient.kvmport = reqinfo.kvmport;
672 reqinfo.kvmport.wsClient.reqinfo = reqinfo;
673 reqinfo.kvmport.connectionStart = Date.now();
674 reqinfo.kvmport.bytesIn = 0;
675 reqinfo.kvmport.bytesOut = 0;
676 logConnection(reqinfo.kvmport.wsClient);
678 reqinfo.kvmport.wsClient.on('open', function () {
679 parent.parent.debug('relay', 'IPKVM: Relay websocket open');
680 this.wsBrowser.on('message', function (data) {
681 //console.log('KVM browser data', data.toString('hex'), data.toString('utf8'));
683 // Replace the authentication command that used the dummy cookie with a command that has the correct hash
684 if ((this.xAuthNonce != null) && (this.xAuthNonce != 1) && (data.length == 67) && (data[0] == 0x21) && (data[1] == 0x41)) {
685 const hash = Buffer.from(require('crypto').createHash('sha256').update(this.xAuthNonce + obj.authCookie).digest().toString('hex'));
686 data = Buffer.alloc(67);
687 data[0] = 0x21; // Auth Command
688 data[1] = 0x41; // Length
689 hash.copy(data, 2); // Hash
693 // Check the port name
694 if ((data[0] == 0x89) && (data.length > 4)) {
695 const portNameLen = (data[2] << 8) + data[3];
696 if (data.length == (4 + portNameLen)) {
697 const portName = data.slice(4).toString('utf8');
698 if (reqinfo.kvmport.portid != portName) {
699 // The browser required an unexpected port for remote control, disconnect not.
700 try { this._socket.close(); } catch (ex) { }
706 try { this.wsClient.kvmport.bytesOut += data.length; } catch (ex) { }
707 this._socket.pause();
708 try { this.wsClient.send(data); } catch (ex) { }
709 this._socket.resume();
711 this.wsBrowser.on('close', function () {
712 parent.parent.debug('relay', 'IPKVM: Relay browser websocket closed');
716 logDisconnection(this.wsClient);
717 try { this.wsClient.close(); } catch (ex) { }
719 if (this.wsClient.kvmport) {
720 delete this.wsClient.kvmport.wsClient;
721 delete this.wsClient.kvmport;
723 delete this.wsClient.wsBrowser;
724 delete this.wsClient;
725 } catch (ex) { console.log(ex); }
728 this.wsBrowser.on('error', function (err) {
729 parent.parent.debug('relay', 'IPKVM: Relay browser websocket error: ' + err);
731 this.wsBrowser._socket.resume();
733 reqinfo.kvmport.wsClient.on('message', function (data) { // Make sure to handle flow control.
734 //console.log('KVM switch data', data, data.length, data.toString('hex'));
736 // If the data start with 0x21 and 0x41 followed by {SHA256}, store the authenticate nonce
737 if ((this.wsBrowser.xAuthNonce == null) && (data.length == 67) && (data[0] == 0x21) && (data[1] == 0x41) && (data[2] == 0x7b) && (data[3] == 0x53) && (data[4] == 0x48)) {
738 this.wsBrowser.xAuthNonce = data.slice(2).toString().substring(0, 64);
741 try { this.wsBrowser.wsClient.kvmport.bytesIn += data.length; } catch (ex) { }
742 this._socket.pause();
743 try { this.wsBrowser.send(data); } catch (ex) { }
744 this._socket.resume();
746 reqinfo.kvmport.wsClient.on('close', function () {
747 parent.parent.debug('relay', 'IPKVM: Relay websocket closed');
751 if (this.wsBrowser) {
752 logDisconnection(this.wsBrowser.wsClient);
753 try { this.wsBrowser.close(); } catch (ex) { }
754 delete this.wsBrowser.wsClient; delete this.wsBrowser;
756 if (this.kvmport) { delete this.kvmport.wsClient; delete this.kvmport; }
757 } catch (ex) { console.log(ex); }
759 reqinfo.kvmport.wsClient.on('error', function (err) {
760 parent.parent.debug('relay', 'IPKVM: Relay websocket error: ' + err);
763 } catch (ex) { console.log(ex); }
773// Create WebPowerSwitch Manager
774function CreateWebPowerSwitch(parent, hostname, port, username, password) {
776 const https = require('http');
777 const crypto = require('crypto');
779 var updateTimer = null;
780 var retryTimer = null;
781 var challenge = null;
782 var challengeRetry = 0;
783 var nonceCounter = 1;
785 obj.state = 0; // 0 = Disconnected, 1 = Connecting, 2 = Connected
790 obj.onStateChanged = null;
791 obj.onPortsChanged = null;
793 function onCheckServerIdentity(cert) {
794 console.log('TODO: Certificate Check');
797 obj.start = function () {
798 if (obj.started) return;
800 if (obj.state == 0) {
802 obj.router = CreateMiniRouter(parent, obj.relayid, hostname, port);
803 obj.router.start(function () { connect(); });
810 obj.stop = function () {
811 if (!obj.started) return;
813 if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
816 if (obj.router) { obj.router.stop(); delete obj.router; }
819 // If the relay device has changed, update our router
820 obj.updateRelayId = function (relayid) {
821 obj.relayid = relayid;
822 if (obj.router != null) { obj.router.nodeid = relayid; }
825 function setState(newState) {
826 if (obj.state == newState) return;
827 obj.state = newState;
828 if (obj.onStateChanged != null) { obj.onStateChanged(obj, newState); }
829 if ((newState == 2) && (updateTimer == null)) { updateTimer = setInterval(obj.update, 10000); }
830 if ((newState != 2) && (updateTimer != null)) { clearInterval(updateTimer); updateTimer = null; }
831 if ((newState == 0) && (obj.started == true) && (retryTimer == null)) { retryTimer = setTimeout(connect, 20000); }
832 if (newState == 0) { obj.ports = []; obj.portCount = 0; }
836 if (obj.state != 0) return;
837 if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
838 setState(1); // 1 = Connecting
842 obj.update = function () {
843 obj.fetch('/restapi/relay/outlets/all;/=name,physical_state/', 'GET', null, null, function (sender, tag, rdata, res) {
844 if (res.statusCode == 207) {
846 if (rdata != null) { try { rdata2 = JSON.parse(rdata); } catch (ex) { } }
847 if (Array.isArray(rdata2)) {
848 obj.portCount = (rdata2.length / 2);
849 setState(2); // 2 = Connected
850 const updatedPorts = [];
851 for (var i = 0; i < (rdata2.length / 2); i++) {
852 const portname = rdata2[i * 2];
853 const portstate = rdata2[(i * 2) + 1];
854 var portchanged = false;
855 if (obj.ports[i] == null) {
857 obj.ports[i] = { PortNumber: i + 1, PortId: 'p' + i, Name: portname, Status: 1, State: portstate, Class: 'PDU' };
861 const port = obj.ports[i];
862 if (port.Name != portname) { port.Name = portname; portchanged = true; }
863 if (port.State != portstate) { port.State = portstate; portchanged = true; }
865 if (portchanged) { updatedPorts.push(i); }
867 if ((updatedPorts.length > 0) && (obj.onPortsChanged != null)) { obj.onPortsChanged(obj, updatedPorts); }
869 setState(0); // 0 = Disconnected
872 setState(0); // 0 = Disconnected
877 obj.powerOperation = function (event) {
878 if (typeof event.portnum != 'number') return;
879 if (event.action == 'turnon') { setPowerState(event.portnum - 1, true); }
880 else if (event.action == 'turnoff') { setPowerState(event.portnum - 1, false); }
883 function setPowerState(port, state, func) {
884 obj.fetch('/restapi/relay/outlets/' + port + '/state/', 'PUT', 'value=' + state, null, function (sender, tag, rdata, res) {
885 if (res.statusCode == 204) { obj.update(); }
889 obj.fetch = function (url, method, data, tag, func) {
890 if (obj.state == 0) return;
891 if (typeof data == 'string') { data = Buffer.from(data); }
895 hostname: obj.router ? 'localhost' : hostname,
896 port: obj.router ? obj.router.tcpServerPort : port,
897 rejectUnauthorized: false,
898 checkServerIdentity: onCheckServerIdentity,
902 'Content-Type': 'application/x-www-form-urlencoded',
903 'accept': 'application/json',
908 if (data != null) { options.headers['Content-Length'] = data.length; }
910 if (challenge != null) {
911 const buf = Buffer.alloc(10);
912 challenge.cnonce = crypto.randomFillSync(buf).toString('hex');
913 challenge.nc = nonceCounter++;
914 const ha1 = crypto.createHash('md5');
915 ha1.update([username, challenge.realm, password].join(':'));
916 var xha1 = ha1.digest('hex')
917 const ha2 = crypto.createHash('md5');
918 ha2.update([options.method, options.path].join(':'));
919 var xha2 = ha2.digest('hex');
920 const response = crypto.createHash('md5');
921 response.update([xha1, challenge.nonce, challenge.nc, challenge.cnonce, challenge.qop, xha2].join(':'));
922 var requestParams = {
923 "username": username,
924 "realm": challenge.realm,
925 "nonce": challenge.nonce,
927 "response": response.digest('hex'),
928 "cnonce": challenge.cnonce,
929 "opaque": challenge.opaque
931 options.headers = options.headers || {};
932 options.headers.Authorization = renderDigest(requestParams) + ', algorithm=MD5, nc=' + challenge.nc + ', qop=' + challenge.qop;
935 const req = https.request(options, function (res) {
936 if (obj.state == 0) return;
937 //console.log('res.statusCode', res.statusCode);
938 //if (res.statusCode != 200) { console.log(res.statusCode, res.headers, Buffer.concat(data).toString()); setState(0); return; }
940 res.on('data', function (d) { rdata.push(d); });
941 res.on('end', function () {
942 if (res.statusCode == 401) {
944 if (challengeRetry > 4) { setState(0); return; }
945 challenge = parseChallenge(res.headers['www-authenticate']);
946 obj.fetch(url, method, data, tag, func);
949 // This line is used for debugging only, used to swap a file.
950 func(obj, tag, Buffer.concat(rdata), res);
954 req.on('error', function (error) { setState(0); });
955 req.on('timeout', function () { setState(0); });
956 if (data) { req.write(data); }
960 function parseChallenge(header) {
961 header = header.replace('qop="auth,auth-int"', 'qop="auth"'); // We don't support auth-int yet, easiest way to get rid of it.
962 const prefix = 'Digest ';
963 const challenge = header.substr(header.indexOf(prefix) + prefix.length);
964 const parts = challenge.split(',');
965 const length = parts.length;
967 for (var i = 0; i < length; i++) {
968 var part = parts[i].match(/^\s*?([a-zA-Z0-0]+)="(.*)"\s*?$/);
969 if (part && part.length > 2) { params[part[1]] = part[2]; }
974 function renderDigest(params) {
976 for (var i in params) { parts.push(i + '="' + params[i] + '"'); }
977 return 'Digest ' + parts.join(', ');
984// Mini TCP port router
985function CreateMiniRouter(parent, nodeid, targetHost, targetPort) {
986 const Net = require('net');
987 const WebSocket = require('ws');
989 const tcpSockets = {}
990 obj.tcpServerPort = 0;
992 obj.targetHost = targetHost;
993 obj.targetPort = targetPort;
995 parent.parent.debug('relay', 'MiniRouter: Request relay for ' + obj.targetHost + ':' + obj.targetPort + ' thru ' + nodeid + '.');
997 // Close a TCP socket and the coresponding web socket.
998 function closeTcpSocket(tcpSocket) {
999 if (tcpSockets[tcpSocket]) {
1000 delete tcpSockets[tcpSocket];
1001 try { tcpSocket.end(); } catch (ex) { console.log(ex); }
1002 if (tcpSocket.relaySocket) { try { tcpSocket.relaySocket.close(); } catch (ex) { console.log(ex); } }
1003 try { delete tcpSocket.relaySocket.tcpSocket; } catch (ex) { }
1004 try { delete tcpSocket.relaySocket; } catch (ex) { }
1008 // Close a web socket and the coresponding TCP socket.
1009 function closeWebSocket(webSocket) {
1010 const tcpSocket = webSocket.tcpSocket;
1011 if (tcpSocket) { closeTcpSocket(tcpSocket); }
1014 // Start the looppback server
1015 obj.start = function(onReadyFunc) {
1016 obj.tcpServer = new Net.Server();
1017 obj.tcpServer.listen(0, 'localhost', function () {
1018 obj.tcpServerPort = obj.tcpServer.address().port;
1019 parent.parent.debug('relay', 'MiniRouter: Request for relay ' + obj.targetHost + ':' + obj.targetPort + ' started on port ' + obj.tcpServerPort);
1020 onReadyFunc(obj.tcpServerPort, obj);
1022 obj.tcpServer.on('connection', function (socket) {
1023 tcpSockets[socket] = 1;
1025 socket.on('data', function (chunk) { // Make sure to handle flow control.
1026 const f = function sendDone() { sendDone.tcpSocket.resume(); }
1028 if (this.relaySocket && this.relaySocket.active) { this.pause(); this.relaySocket.send(chunk, f); }
1030 socket.on('end', function () { closeTcpSocket(this); });
1031 socket.on('close', function () { closeTcpSocket(this); });
1032 socket.on('error', function (err) { closeTcpSocket(this); });
1034 // Encode the device relay cookie. Note that there is no userid in this cookie.
1035 const domainid = obj.nodeid.split('/')[1];
1036 const cookie = parent.parent.encodeCookie({ nouser: 1, domainid: domainid, nodeid: obj.nodeid, tcpaddr: obj.targetHost, tcpport: obj.targetPort }, parent.parent.loginCookieEncryptionKey);
1037 const domain = parent.parent.config.domains[domainid];
1039 // Setup the correct URL with domain and use TLS only if needed.
1040 const options = { rejectUnauthorized: false };
1041 const protocol = (parent.parent.args.tlsoffload) ? 'ws' : 'wss';
1043 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
1044 const url = protocol + '://localhost:' + parent.parent.args.port + '/' + domainadd + 'meshrelay.ashx?noping=1&hd=1&auth=' + cookie; // TODO: &p=10, Protocol 10 is Web-RDP, Specify TCP routing protocol?
1045 parent.parent.debug('relay', 'MiniRouter: Connection websocket to ' + url);
1046 socket.relaySocket = new WebSocket(url, options);
1047 socket.relaySocket.tcpSocket = socket;
1048 socket.relaySocket.on('open', function () { parent.parent.debug('relay', 'MiniRouter: Relay websocket open'); });
1049 socket.relaySocket.on('message', function (data) { // Make sure to handle flow control.
1052 // Relay Web socket is connected, start data relay
1054 this.tcpSocket.resume();
1056 // Could not connect web socket, close it
1057 closeWebSocket(this);
1061 this._socket.pause();
1062 const f = function sendDone() { sendDone.webSocket._socket.resume(); }
1064 this.tcpSocket.write(data, f);
1067 socket.relaySocket.on('close', function (reasonCode, description) { parent.parent.debug('relay', 'MiniRouter: Relay websocket closed'); closeWebSocket(this); });
1068 socket.relaySocket.on('error', function (err) { parent.parent.debug('relay', 'MiniRouter: Relay websocket error: ' + err); closeWebSocket(this); });
1072 // Stop the looppback server and all relay sockets
1073 obj.stop = function () {
1074 for (var tcpSocket in tcpSockets) { closeTcpSocket(tcpSocket); }
1075 obj.tcpServer.close();
1076 obj.tcpServer = null;
1082module.exports.CreateIPKVMManager = CreateIPKVMManager;