| 1 | /** |
| 2 | * @description MeshCentral IP KVM Management Module |
| 3 | * @author Ylian Saint-Hilaire |
| 4 | * @copyright Intel Corporation 2021-2022 |
| 5 | * @license Apache-2.0 |
| 6 | * @version v0.0.1 |
| 7 | */ |
| 8 | |
| 9 | function CreateIPKVMManager(parent) { |
| 10 | const obj = {}; |
| 11 | obj.parent = parent; |
| 12 | obj.managedGroups = {} // meshid --> Manager |
| 13 | obj.managedPorts = {} // nodeid --> PortInfo |
| 14 | |
| 15 | // Mesh Rights |
| 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; |
| 38 | |
| 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); } |
| 56 | } |
| 57 | } |
| 58 | |
| 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); } |
| 63 | } |
| 64 | |
| 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; |
| 78 | manager.start(); |
| 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; |
| 87 | manager.start(); |
| 88 | } |
| 89 | } |
| 90 | |
| 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 |
| 100 | } |
| 101 | |
| 102 | // Remove the manager |
| 103 | delete obj.managedGroups[meshid]; |
| 104 | manager.stop(); |
| 105 | } |
| 106 | } |
| 107 | |
| 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); } |
| 112 | } |
| 113 | |
| 114 | // Called when a KVM device changes state |
| 115 | function onStateChanged(sender, state) { |
| 116 | /* |
| 117 | console.log('State: ' + ['Disconnected', 'Connecting', 'Connected'][state]); |
| 118 | if (state == 2) { |
| 119 | if (sender.deviceModel) { console.log('DeviceModel:', sender.deviceModel); } |
| 120 | if (sender.firmwareVersion) { console.log('FirmwareVersion:', sender.firmwareVersion); } |
| 121 | } |
| 122 | */ |
| 123 | |
| 124 | if (state == 0) { |
| 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]; |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | } |
| 137 | |
| 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); |
| 153 | |
| 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 }); |
| 156 | } else { |
| 157 | // The device exists, update it |
| 158 | var changed = false; |
| 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 |
| 162 | if (changed) { |
| 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 }); |
| 166 | } |
| 167 | } |
| 168 | |
| 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 }; |
| 173 | } |
| 174 | }); |
| 175 | } else { |
| 176 | // Update connectivity state |
| 177 | parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, port.State ? 1 : 8, null, null); |
| 178 | } |
| 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); |
| 189 | |
| 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 }); |
| 192 | } else { |
| 193 | // The device exists, update it |
| 194 | var changed = false; |
| 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 |
| 198 | if (changed) { |
| 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 }); |
| 202 | } |
| 203 | } |
| 204 | |
| 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 }; |
| 209 | } |
| 210 | |
| 211 | // Update busy state |
| 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; } |
| 215 | |
| 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); |
| 219 | } |
| 220 | }); |
| 221 | } else { |
| 222 | // Update busy state |
| 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; } |
| 226 | |
| 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); |
| 230 | } |
| 231 | } |
| 232 | } else { |
| 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]; |
| 237 | |
| 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 |
| 246 | |
| 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 }); |
| 249 | } |
| 250 | |
| 251 | // Remove the managed port |
| 252 | delete obj.managedPorts[nodeid]; |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 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, '$'); |
| 261 | } |
| 262 | |
| 263 | // Parse an incoming HTTP request URL |
| 264 | function parseIpKvmUrl(domain, url) { |
| 265 | const q = new URL(url, 'http://localhost'); |
| 266 | const i = q.pathname.indexOf('/ipkvm.ashx/'); |
| 267 | if (i == -1) return null; |
| 268 | const urlargs = q.pathname.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; |
| 276 | urlargs.shift(); |
| 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 }; |
| 280 | } |
| 281 | |
| 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; } |
| 287 | |
| 288 | // Check node rights |
| 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; } |
| 294 | |
| 295 | // Process the request |
| 296 | reqinfo.kvmmanager.handleIpKvmGet(domain, reqinfo, req, res, next); |
| 297 | } |
| 298 | |
| 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; } |
| 304 | |
| 305 | // Check node rights |
| 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; } |
| 311 | |
| 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; |
| 316 | |
| 317 | // Process the request |
| 318 | reqinfo.kvmmanager.handleIpKvmWebSocket(domain, reqinfo, ws, req); |
| 319 | } |
| 320 | |
| 321 | return obj; |
| 322 | } |
| 323 | |
| 324 | |
| 325 | |
| 326 | // Create Raritan Dominion KX III Manager |
| 327 | function CreateRaritanKX3Manager(parent, hostname, port, username, password) { |
| 328 | const https = require('https'); |
| 329 | const obj = {}; |
| 330 | var updateTimer = null; |
| 331 | var retryTimer = null; |
| 332 | |
| 333 | obj.authCookie = null; |
| 334 | obj.state = 0; // 0 = Disconnected, 1 = Connecting, 2 = Connected |
| 335 | obj.ports = []; |
| 336 | obj.portCount = 0; |
| 337 | obj.portHash = null; |
| 338 | obj.deviceCount = 0; |
| 339 | obj.deviceHash = null; |
| 340 | obj.started = false; |
| 341 | |
| 342 | // Events |
| 343 | obj.onStateChanged = null; |
| 344 | obj.onPortsChanged = null; |
| 345 | |
| 346 | function onCheckServerIdentity(cert) { |
| 347 | console.log('TODO: Certificate Check'); |
| 348 | } |
| 349 | |
| 350 | obj.start = function () { |
| 351 | if (obj.started) return; |
| 352 | obj.started = true; |
| 353 | if (obj.relayid) { |
| 354 | obj.router = CreateMiniRouter(parent, obj.relayid, hostname, port); |
| 355 | obj.router.start(function () { connect(); }); |
| 356 | } else { |
| 357 | connect(); |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | obj.stop = function () { |
| 362 | if (!obj.started) return; |
| 363 | obj.started = false; |
| 364 | if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; } |
| 365 | setState(0); |
| 366 | if (obj.router) { obj.router.stop(); delete obj.router; } |
| 367 | } |
| 368 | |
| 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; } |
| 373 | } |
| 374 | |
| 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; } |
| 383 | } |
| 384 | |
| 385 | function connect() { |
| 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'); |
| 391 | const options = { |
| 392 | hostname: hostname, |
| 393 | port: port, |
| 394 | rejectUnauthorized: false, |
| 395 | checkServerIdentity: onCheckServerIdentity, |
| 396 | path: '/auth.asp?client=javascript', // ?client=standalone |
| 397 | method: 'POST', |
| 398 | headers: { |
| 399 | 'Content-Type': 'text/html; charset=UTF-8', |
| 400 | 'Content-Length': data.length |
| 401 | } |
| 402 | } |
| 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(); |
| 410 | }) |
| 411 | req.on('error', function (error) { setState(0); }); |
| 412 | req.on('timeout', function () { setState(0); }); |
| 413 | req.write(data); |
| 414 | req.end(); |
| 415 | } |
| 416 | |
| 417 | function checkCookie() { |
| 418 | if (obj.state != 2) return; |
| 419 | const options = { |
| 420 | hostname: hostname, |
| 421 | port: port, |
| 422 | rejectUnauthorized: false, |
| 423 | checkServerIdentity: onCheckServerIdentity, |
| 424 | path: '/cookiecheck.asp', |
| 425 | method: 'GET', |
| 426 | headers: { |
| 427 | 'Content-Type': 'text/html; charset=UTF-8', |
| 428 | 'Cookie': 'pp_session_id=' + obj.authCookie |
| 429 | } |
| 430 | } |
| 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) { }) |
| 436 | }); |
| 437 | req.on('error', function (error) { setState(0); }); |
| 438 | req.on('timeout', function () { setState(0); }); |
| 439 | req.end(); |
| 440 | } |
| 441 | |
| 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\">", "<"); |
| 450 | } |
| 451 | } |
| 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); |
| 466 | } |
| 467 | setState(2); |
| 468 | if (obj.onPortsChanged != null) { obj.onPortsChanged(obj, updatedPorts); } |
| 469 | }); |
| 470 | }); |
| 471 | } |
| 472 | |
| 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]; |
| 480 | } |
| 481 | if (parsed['updateDeviceStatus']) { |
| 482 | obj.deviceCount = parseInt(parsed['updateDeviceStatus'][0][0]); |
| 483 | obj.deviceHash = parsed['updateDeviceStatus'][0][1]; |
| 484 | } |
| 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); |
| 491 | } |
| 492 | if ((updatedPorts.length > 0) && (obj.onPortsChanged != null)) { obj.onPortsChanged(obj, updatedPorts); } |
| 493 | } |
| 494 | }); |
| 495 | } |
| 496 | |
| 497 | function parsePortInfo(args) { |
| 498 | var out = {}; |
| 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; |
| 503 | } |
| 504 | return out; |
| 505 | } |
| 506 | |
| 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); } |
| 513 | return str; |
| 514 | } |
| 515 | |
| 516 | // Parse JavaScript code calls |
| 517 | function parseJsScript(str) { |
| 518 | const out = {}; |
| 519 | var functionName = ''; |
| 520 | var args = []; |
| 521 | var arg = null; |
| 522 | var stack = []; |
| 523 | for (var i = 0; i < str.length; i++) { |
| 524 | if (stack.length == 0) { |
| 525 | if (str[i] != '(') { |
| 526 | if (isAlphaNumeric(str[i])) { functionName += str[i]; } else { functionName = ''; } |
| 527 | } else { |
| 528 | stack.push(')'); |
| 529 | } |
| 530 | } else { |
| 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)); } |
| 535 | arg = null; |
| 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]; |
| 541 | } else { |
| 542 | out[functionName].push(args); |
| 543 | } |
| 544 | } |
| 545 | args = []; |
| 546 | } |
| 547 | stack.pop(); |
| 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]; } |
| 552 | } |
| 553 | } else { |
| 554 | if ((stack.length == 1) && (str[i] == ',')) { |
| 555 | if (arg != null) { args.push(trimQuotes(arg)); arg = null; } |
| 556 | } else { |
| 557 | if (stack.length > 0) { if (arg == null) { arg = str[i]; } else { arg += str[i]; } } |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | } |
| 562 | return out; |
| 563 | } |
| 564 | |
| 565 | function trimQuotes(str) { |
| 566 | if ((str == null) || (str.length < 2)) return str; |
| 567 | str = str.trim(); |
| 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); } |
| 570 | return str; |
| 571 | } |
| 572 | |
| 573 | function isAlphaNumeric(char) { |
| 574 | return ((char >= 'A') && (char <= 'Z')) || ((char >= 'a') && (char <= 'z')) || ((char >= '0') && (char <= '9')); |
| 575 | } |
| 576 | |
| 577 | obj.fetch = function (url, postdata, tag, func) { |
| 578 | if (obj.state == 0) return; |
| 579 | |
| 580 | var data = []; |
| 581 | const options = { |
| 582 | hostname: obj.router ? 'localhost' : hostname, |
| 583 | port: obj.router ? obj.router.tcpServerPort : port, |
| 584 | rejectUnauthorized: false, |
| 585 | checkServerIdentity: onCheckServerIdentity, |
| 586 | path: url, |
| 587 | method: (postdata != null) ? 'POST' : 'GET', |
| 588 | headers: { |
| 589 | 'Content-Type': 'text/html; charset=UTF-8', |
| 590 | 'Cookie': 'pp_session_id=' + obj.authCookie |
| 591 | } |
| 592 | } |
| 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); |
| 602 | }); |
| 603 | }); |
| 604 | req.on('error', function (error) { setState(0); }); |
| 605 | req.on('timeout', function () { setState(0); }); |
| 606 | req.end(); |
| 607 | } |
| 608 | |
| 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; } |
| 612 | |
| 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);'); |
| 625 | } |
| 626 | resx.end(data); |
| 627 | }); |
| 628 | } |
| 629 | |
| 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); |
| 635 | } |
| 636 | |
| 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); |
| 642 | |
| 643 | delete kvmport.bytesIn; |
| 644 | delete kvmport.bytesOut; |
| 645 | delete kvmport.connectionStart; |
| 646 | delete wsClient.reqinfo; |
| 647 | } |
| 648 | |
| 649 | // Handle a IP-KVM HTTP websocket request |
| 650 | obj.handleIpKvmWebSocket = function (domain, reqinfo, ws, req) { |
| 651 | ws._socket.pause(); |
| 652 | //console.log('handleIpKvmWebSocket', reqinfo.preurl); |
| 653 | |
| 654 | if (reqinfo.kvmport.wsClient != null) { |
| 655 | // Relay already open |
| 656 | //console.log('IPKVM Relay already present'); |
| 657 | try { ws.close(); } catch (ex) { } |
| 658 | } else { |
| 659 | // Setup a websocket-to-websocket relay |
| 660 | try { |
| 661 | const options = { |
| 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' } |
| 665 | }; |
| 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); |
| 677 | |
| 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')); |
| 682 | |
| 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 |
| 690 | this.xAuthNonce = 1; |
| 691 | } |
| 692 | |
| 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) { } |
| 701 | return; |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | |
| 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(); |
| 710 | }); |
| 711 | this.wsBrowser.on('close', function () { |
| 712 | parent.parent.debug('relay', 'IPKVM: Relay browser websocket closed'); |
| 713 | |
| 714 | // Clean up |
| 715 | if (this.wsClient) { |
| 716 | logDisconnection(this.wsClient); |
| 717 | try { this.wsClient.close(); } catch (ex) { } |
| 718 | try { |
| 719 | if (this.wsClient.kvmport) { |
| 720 | delete this.wsClient.kvmport.wsClient; |
| 721 | delete this.wsClient.kvmport; |
| 722 | } |
| 723 | delete this.wsClient.wsBrowser; |
| 724 | delete this.wsClient; |
| 725 | } catch (ex) { console.log(ex); } |
| 726 | } |
| 727 | }); |
| 728 | this.wsBrowser.on('error', function (err) { |
| 729 | parent.parent.debug('relay', 'IPKVM: Relay browser websocket error: ' + err); |
| 730 | }); |
| 731 | this.wsBrowser._socket.resume(); |
| 732 | }); |
| 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')); |
| 735 | |
| 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); |
| 739 | } |
| 740 | |
| 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(); |
| 745 | }); |
| 746 | reqinfo.kvmport.wsClient.on('close', function () { |
| 747 | parent.parent.debug('relay', 'IPKVM: Relay websocket closed'); |
| 748 | |
| 749 | // Clean up |
| 750 | try { |
| 751 | if (this.wsBrowser) { |
| 752 | logDisconnection(this.wsBrowser.wsClient); |
| 753 | try { this.wsBrowser.close(); } catch (ex) { } |
| 754 | delete this.wsBrowser.wsClient; delete this.wsBrowser; |
| 755 | } |
| 756 | if (this.kvmport) { delete this.kvmport.wsClient; delete this.kvmport; } |
| 757 | } catch (ex) { console.log(ex); } |
| 758 | }); |
| 759 | reqinfo.kvmport.wsClient.on('error', function (err) { |
| 760 | parent.parent.debug('relay', 'IPKVM: Relay websocket error: ' + err); |
| 761 | |
| 762 | }); |
| 763 | } catch (ex) { console.log(ex); } |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | return obj; |
| 768 | } |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | // Create WebPowerSwitch Manager |
| 774 | function CreateWebPowerSwitch(parent, hostname, port, username, password) { |
| 775 | port = 80; |
| 776 | const https = require('http'); |
| 777 | const crypto = require('crypto'); |
| 778 | const obj = {}; |
| 779 | var updateTimer = null; |
| 780 | var retryTimer = null; |
| 781 | var challenge = null; |
| 782 | var challengeRetry = 0; |
| 783 | var nonceCounter = 1; |
| 784 | |
| 785 | obj.state = 0; // 0 = Disconnected, 1 = Connecting, 2 = Connected |
| 786 | obj.ports = []; |
| 787 | obj.portCount = 0; |
| 788 | obj.started = false; |
| 789 | |
| 790 | obj.onStateChanged = null; |
| 791 | obj.onPortsChanged = null; |
| 792 | |
| 793 | function onCheckServerIdentity(cert) { |
| 794 | console.log('TODO: Certificate Check'); |
| 795 | } |
| 796 | |
| 797 | obj.start = function () { |
| 798 | if (obj.started) return; |
| 799 | obj.started = true; |
| 800 | if (obj.state == 0) { |
| 801 | if (obj.relayid) { |
| 802 | obj.router = CreateMiniRouter(parent, obj.relayid, hostname, port); |
| 803 | obj.router.start(function () { connect(); }); |
| 804 | } else { |
| 805 | connect(); |
| 806 | } |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | obj.stop = function () { |
| 811 | if (!obj.started) return; |
| 812 | obj.started = false; |
| 813 | if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; } |
| 814 | setState(0); |
| 815 | obj.ports = []; |
| 816 | if (obj.router) { obj.router.stop(); delete obj.router; } |
| 817 | } |
| 818 | |
| 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; } |
| 823 | } |
| 824 | |
| 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; } |
| 833 | } |
| 834 | |
| 835 | function connect() { |
| 836 | if (obj.state != 0) return; |
| 837 | if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; } |
| 838 | setState(1); // 1 = Connecting |
| 839 | obj.update(); |
| 840 | } |
| 841 | |
| 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) { |
| 845 | var rdata2 = null; |
| 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) { |
| 856 | // Add the port |
| 857 | obj.ports[i] = { PortNumber: i + 1, PortId: 'p' + i, Name: portname, Status: 1, State: portstate, Class: 'PDU' }; |
| 858 | portchanged = true; |
| 859 | } else { |
| 860 | // Update the port |
| 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; } |
| 864 | } |
| 865 | if (portchanged) { updatedPorts.push(i); } |
| 866 | } |
| 867 | if ((updatedPorts.length > 0) && (obj.onPortsChanged != null)) { obj.onPortsChanged(obj, updatedPorts); } |
| 868 | } else { |
| 869 | setState(0); // 0 = Disconnected |
| 870 | } |
| 871 | } else { |
| 872 | setState(0); // 0 = Disconnected |
| 873 | } |
| 874 | }); |
| 875 | } |
| 876 | |
| 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); } |
| 881 | } |
| 882 | |
| 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(); } |
| 886 | }); |
| 887 | } |
| 888 | |
| 889 | obj.fetch = function (url, method, data, tag, func) { |
| 890 | if (obj.state == 0) return; |
| 891 | if (typeof data == 'string') { data = Buffer.from(data); } |
| 892 | |
| 893 | var rdata = []; |
| 894 | const options = { |
| 895 | hostname: obj.router ? 'localhost' : hostname, |
| 896 | port: obj.router ? obj.router.tcpServerPort : port, |
| 897 | rejectUnauthorized: false, |
| 898 | checkServerIdentity: onCheckServerIdentity, |
| 899 | path: url, |
| 900 | method: method, |
| 901 | headers: { |
| 902 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 903 | 'accept': 'application/json', |
| 904 | 'X-CSRF': 'x' |
| 905 | } |
| 906 | } |
| 907 | |
| 908 | if (data != null) { options.headers['Content-Length'] = data.length; } |
| 909 | |
| 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, |
| 926 | "uri": options.path, |
| 927 | "response": response.digest('hex'), |
| 928 | "cnonce": challenge.cnonce, |
| 929 | "opaque": challenge.opaque |
| 930 | }; |
| 931 | options.headers = options.headers || {}; |
| 932 | options.headers.Authorization = renderDigest(requestParams) + ', algorithm=MD5, nc=' + challenge.nc + ', qop=' + challenge.qop; |
| 933 | } |
| 934 | |
| 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; } |
| 939 | challengeRetry = 0; |
| 940 | res.on('data', function (d) { rdata.push(d); }); |
| 941 | res.on('end', function () { |
| 942 | if (res.statusCode == 401) { |
| 943 | challengeRetry++; |
| 944 | if (challengeRetry > 4) { setState(0); return; } |
| 945 | challenge = parseChallenge(res.headers['www-authenticate']); |
| 946 | obj.fetch(url, method, data, tag, func); |
| 947 | return; |
| 948 | } else { |
| 949 | // This line is used for debugging only, used to swap a file. |
| 950 | func(obj, tag, Buffer.concat(rdata), res); |
| 951 | } |
| 952 | }); |
| 953 | }); |
| 954 | req.on('error', function (error) { setState(0); }); |
| 955 | req.on('timeout', function () { setState(0); }); |
| 956 | if (data) { req.write(data); } |
| 957 | req.end(); |
| 958 | } |
| 959 | |
| 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; |
| 966 | const params = {}; |
| 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]; } |
| 970 | } |
| 971 | return params; |
| 972 | } |
| 973 | |
| 974 | function renderDigest(params) { |
| 975 | const parts = []; |
| 976 | for (var i in params) { parts.push(i + '="' + params[i] + '"'); } |
| 977 | return 'Digest ' + parts.join(', '); |
| 978 | } |
| 979 | |
| 980 | return obj; |
| 981 | } |
| 982 | |
| 983 | |
| 984 | // Mini TCP port router |
| 985 | function CreateMiniRouter(parent, nodeid, targetHost, targetPort) { |
| 986 | const Net = require('net'); |
| 987 | const WebSocket = require('ws'); |
| 988 | const obj = {}; |
| 989 | const tcpSockets = {} |
| 990 | obj.tcpServerPort = 0; |
| 991 | obj.nodeid = nodeid; |
| 992 | obj.targetHost = targetHost; |
| 993 | obj.targetPort = targetPort; |
| 994 | |
| 995 | parent.parent.debug('relay', 'MiniRouter: Request relay for ' + obj.targetHost + ':' + obj.targetPort + ' thru ' + nodeid + '.'); |
| 996 | |
| 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) { } |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | // Close a web socket and the coresponding TCP socket. |
| 1009 | function closeWebSocket(webSocket) { |
| 1010 | const tcpSocket = webSocket.tcpSocket; |
| 1011 | if (tcpSocket) { closeTcpSocket(tcpSocket); } |
| 1012 | } |
| 1013 | |
| 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); |
| 1021 | }); |
| 1022 | obj.tcpServer.on('connection', function (socket) { |
| 1023 | tcpSockets[socket] = 1; |
| 1024 | socket.pause(); |
| 1025 | socket.on('data', function (chunk) { // Make sure to handle flow control. |
| 1026 | const f = function sendDone() { sendDone.tcpSocket.resume(); } |
| 1027 | f.tcpSocket = this; |
| 1028 | if (this.relaySocket && this.relaySocket.active) { this.pause(); this.relaySocket.send(chunk, f); } |
| 1029 | }); |
| 1030 | socket.on('end', function () { closeTcpSocket(this); }); |
| 1031 | socket.on('close', function () { closeTcpSocket(this); }); |
| 1032 | socket.on('error', function (err) { closeTcpSocket(this); }); |
| 1033 | |
| 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]; |
| 1038 | |
| 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'; |
| 1042 | var domainadd = ''; |
| 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. |
| 1050 | if (!this.active) { |
| 1051 | if (data == 'c') { |
| 1052 | // Relay Web socket is connected, start data relay |
| 1053 | this.active = true; |
| 1054 | this.tcpSocket.resume(); |
| 1055 | } else { |
| 1056 | // Could not connect web socket, close it |
| 1057 | closeWebSocket(this); |
| 1058 | } |
| 1059 | } else { |
| 1060 | // Relay more data |
| 1061 | this._socket.pause(); |
| 1062 | const f = function sendDone() { sendDone.webSocket._socket.resume(); } |
| 1063 | f.webSocket = this; |
| 1064 | this.tcpSocket.write(data, f); |
| 1065 | } |
| 1066 | }); |
| 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); }); |
| 1069 | }); |
| 1070 | } |
| 1071 | |
| 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; |
| 1077 | } |
| 1078 | |
| 1079 | return obj; |
| 1080 | } |
| 1081 | |
| 1082 | module.exports.CreateIPKVMManager = CreateIPKVMManager; |