meshipkvm.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. function CreateIPKVMManager(parent) {
  9. const obj = {};
  10. obj.parent = parent;
  11. obj.managedGroups = {} // meshid --> Manager
  12. obj.managedPorts = {} // nodeid --> PortInfo
  13. // Mesh Rights
  14. const MESHRIGHT_EDITMESH = 0x00000001; // 1
  15. const MESHRIGHT_MANAGEUSERS = 0x00000002; // 2
  16. const MESHRIGHT_MANAGECOMPUTERS = 0x00000004; // 4
  17. const MESHRIGHT_REMOTECONTROL = 0x00000008; // 8
  18. const MESHRIGHT_AGENTCONSOLE = 0x00000010; // 16
  19. const MESHRIGHT_SERVERFILES = 0x00000020; // 32
  20. const MESHRIGHT_WAKEDEVICE = 0x00000040; // 64
  21. const MESHRIGHT_SETNOTES = 0x00000080; // 128
  22. const MESHRIGHT_REMOTEVIEWONLY = 0x00000100; // 256
  23. const MESHRIGHT_NOTERMINAL = 0x00000200; // 512
  24. const MESHRIGHT_NOFILES = 0x00000400; // 1024
  25. const MESHRIGHT_NOAMT = 0x00000800; // 2048
  26. const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000; // 4096
  27. const MESHRIGHT_LIMITEVENTS = 0x00002000; // 8192
  28. const MESHRIGHT_CHATNOTIFY = 0x00004000; // 16384
  29. const MESHRIGHT_UNINSTALL = 0x00008000; // 32768
  30. const MESHRIGHT_NODESKTOP = 0x00010000; // 65536
  31. const MESHRIGHT_REMOTECOMMAND = 0x00020000; // 131072
  32. const MESHRIGHT_RESETOFF = 0x00040000; // 262144
  33. const MESHRIGHT_GUESTSHARING = 0x00080000; // 524288
  34. const MESHRIGHT_DEVICEDETAILS = 0x00100000; // ?1048576?
  35. const MESHRIGHT_ADMIN = 0xFFFFFFFF;
  36. // Subscribe for mesh creation events
  37. parent.AddEventDispatch(['server-createmesh', 'server-deletemesh', 'server-editmesh', 'devport-operation'], obj);
  38. obj.HandleEvent = function (source, event, ids, id) {
  39. if ((event == null) || (event.mtype != 4)) return;
  40. if (event.action == 'createmesh') {
  41. // Start managing this new device group
  42. startManagement(parent.webserver.meshes[event.meshid]);
  43. } else if (event.action == 'deletemesh') {
  44. // Stop managing this device group
  45. stopManagement(event.meshid);
  46. } else if ((event.action == 'meshchange') && (event.relayid != null)) {
  47. // See if the relayid changed
  48. changeManagementRelayId(event.meshid, event.relayid);
  49. } else if ((event.action == 'turnon') || (event.action == 'turnoff')) {
  50. // Perform power operation
  51. const manager = obj.managedGroups[event.meshid];
  52. if ((manager) && (manager.powerOperation)) { manager.powerOperation(event); }
  53. }
  54. }
  55. // Run thru the list of device groups that require
  56. for (var i in parent.webserver.meshes) {
  57. const mesh = parent.webserver.meshes[i];
  58. if ((mesh.mtype == 4) && (mesh.deleted == null)) { startManagement(mesh); }
  59. }
  60. // Start managing a IP KVM device
  61. function startManagement(mesh) {
  62. if ((mesh == null) || (mesh.mtype != 4) || (mesh.kvm == null) || (mesh.deleted != null) || (obj.managedGroups[mesh._id] != null)) return;
  63. var port = 443, hostSplit = mesh.kvm.host.split(':'), host = hostSplit[0];
  64. if (hostSplit.length == 2) { port = parseInt(hostSplit[1]); }
  65. if (mesh.kvm.model == 1) { // Raritan KX III
  66. const manager = CreateRaritanKX3Manager(obj, host, port, mesh.kvm.user, mesh.kvm.pass);
  67. manager.meshid = mesh._id;
  68. manager.relayid = mesh.relayid;
  69. manager.domainid = mesh._id.split('/')[1];
  70. obj.managedGroups[mesh._id] = manager;
  71. manager.onStateChanged = onStateChanged;
  72. manager.onPortsChanged = onPortsChanged;
  73. manager.start();
  74. } else if (mesh.kvm.model == 2) { // WebPowerSwitch 7
  75. const manager = CreateWebPowerSwitch(obj, host, port, mesh.kvm.user, mesh.kvm.pass);
  76. manager.meshid = mesh._id;
  77. manager.relayid = mesh.relayid;
  78. manager.domainid = mesh._id.split('/')[1];
  79. obj.managedGroups[mesh._id] = manager;
  80. manager.onStateChanged = onStateChanged;
  81. manager.onPortsChanged = onPortsChanged;
  82. manager.start();
  83. }
  84. }
  85. // Stop managing a IP KVM device
  86. function stopManagement(meshid) {
  87. const manager = obj.managedGroups[meshid];
  88. if (manager != null) {
  89. // Remove all managed ports
  90. for (var i = 0; i < manager.ports.length; i++) {
  91. const port = manager.ports[i];
  92. const nodeid = generateIpKvmNodeId(manager.meshid, port.PortId, manager.domainid);
  93. delete obj.managedPorts[nodeid]; // Remove the managed port
  94. }
  95. // Remove the manager
  96. delete obj.managedGroups[meshid];
  97. manager.stop();
  98. }
  99. }
  100. // Change the relayid of a managed device if needed
  101. function changeManagementRelayId(meshid, relayid) {
  102. const manager = obj.managedGroups[meshid];
  103. if ((manager != null) && (manager.relayid != null) && (manager.relayid != relayid)) { manager.updateRelayId(relayid); }
  104. }
  105. // Called when a KVM device changes state
  106. function onStateChanged(sender, state) {
  107. /*
  108. console.log('State: ' + ['Disconnected', 'Connecting', 'Connected'][state]);
  109. if (state == 2) {
  110. if (sender.deviceModel) { console.log('DeviceModel:', sender.deviceModel); }
  111. if (sender.firmwareVersion) { console.log('FirmwareVersion:', sender.firmwareVersion); }
  112. }
  113. */
  114. if (state == 0) {
  115. // Disconnect all nodes for this device group
  116. for (var i in sender.ports) {
  117. const port = sender.ports[i];
  118. const nodeid = generateIpKvmNodeId(sender.meshid, port.PortId, sender.domainid);
  119. if (obj.managedPorts[nodeid] != null) {
  120. parent.ClearConnectivityState(sender.meshid, nodeid, 1, null, null);
  121. delete obj.managedPorts[nodeid];
  122. }
  123. }
  124. }
  125. }
  126. // Called when a KVM device changes state
  127. function onPortsChanged(sender, updatedPorts) {
  128. for (var i = 0; i < updatedPorts.length; i++) {
  129. const port = sender.ports[updatedPorts[i]];
  130. const nodeid = generateIpKvmNodeId(sender.meshid, port.PortId, sender.domainid);
  131. if ((port.Status == 1) && (port.Class == 'PDU')) {
  132. //console.log(port.PortNumber + ', ' + port.PortId + ', ' + port.Name + ', ' + port.State);
  133. if ((obj.managedPorts[nodeid] == null) || (obj.managedPorts[nodeid].name != port.Name)) {
  134. parent.db.Get(nodeid, function (err, nodes) {
  135. if ((err != null) || (nodes == null)) return;
  136. const mesh = parent.webserver.meshes[sender.meshid];
  137. if (nodes.length == 0) {
  138. // The device does not exist, create it
  139. 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' };
  140. parent.db.Set(device);
  141. // Event the new node
  142. 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 });
  143. } else {
  144. // The device exists, update it
  145. var changed = false;
  146. const device = nodes[0];
  147. if (device.rname != port.Name) { device.rname = port.Name; changed = true; } // Update the device port name
  148. if ((mesh.flags) && (mesh.flags & 2) && (device.name != port.Name)) { device.name = port.Name; changed = true; } // Sync device name to port name
  149. if (changed) {
  150. // Update the database and event the node change
  151. parent.db.Set(device);
  152. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'changenode', nodeid: nodeid, node: device, domain: sender.domainid, nolog: 1 });
  153. }
  154. }
  155. // Set the connectivity state if needed
  156. if (obj.managedPorts[nodeid] == null) {
  157. parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, port.State ? 1 : 8, null, null);
  158. obj.managedPorts[nodeid] = { name: port.Name, meshid: sender.meshid, portid: port.PortId, portType: port.PortType, portNo: port.PortIndex };
  159. }
  160. });
  161. } else {
  162. // Update connectivity state
  163. parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, port.State ? 1 : 8, null, null);
  164. }
  165. } else if ((port.Status == 1) && (port.Class == 'KVM')) {
  166. //console.log(port.PortNumber + ', ' + port.PortId + ', ' + port.Name + ', ' + port.Type + ', ' + ((port.StatAvailable == 0) ? 'Idle' : 'Connected'));
  167. if ((obj.managedPorts[nodeid] == null) || (obj.managedPorts[nodeid].name != port.Name)) {
  168. parent.db.Get(nodeid, function (err, nodes) {
  169. if ((err != null) || (nodes == null)) return;
  170. const mesh = parent.webserver.meshes[sender.meshid];
  171. if (nodes.length == 0) {
  172. // The device does not exist, create it
  173. 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 };
  174. parent.db.Set(device);
  175. // Event the new node
  176. 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 });
  177. } else {
  178. // The device exists, update it
  179. var changed = false;
  180. const device = nodes[0];
  181. if (device.rname != port.Name) { device.rname = port.Name; changed = true; } // Update the device port name
  182. if ((mesh.flags) && (mesh.flags & 2) && (device.name != port.Name)) { device.name = port.Name; changed = true; } // Sync device name to port name
  183. if (changed) {
  184. // Update the database and event the node change
  185. parent.db.Set(device);
  186. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'changenode', nodeid: nodeid, node: device, domain: sender.domainid, nolog: 1 });
  187. }
  188. }
  189. // Set the connectivity state if needed
  190. if (obj.managedPorts[nodeid] == null) {
  191. parent.SetConnectivityState(sender.meshid, nodeid, Date.now(), 1, 1, null, null);
  192. obj.managedPorts[nodeid] = { name: port.Name, meshid: sender.meshid, portid: port.PortId, portType: port.PortType, portNo: port.PortIndex };
  193. }
  194. // Update busy state
  195. const portInfo = obj.managedPorts[nodeid];
  196. if ((portInfo.sessions != null) != (port.StatAvailable != 0)) {
  197. if (port.StatAvailable != 0) { portInfo.sessions = { kvm: { 'busy': 1 } } } else { delete portInfo.sessions; }
  198. // Event the new sessions, this will notify everyone that agent sessions have changed
  199. var event = { etype: 'node', action: 'devicesessions', nodeid: nodeid, domain: sender.domainid, sessions: portInfo.sessions, nolog: 1 };
  200. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, event);
  201. }
  202. });
  203. } else {
  204. // Update busy state
  205. const portInfo = obj.managedPorts[nodeid];
  206. if ((portInfo.sessions != null) != (port.StatAvailable != 0)) {
  207. if (port.StatAvailable != 0) { portInfo.sessions = { kvm: { 'busy': 1 } } } else { delete portInfo.sessions; }
  208. // Event the new sessions, this will notify everyone that agent sessions have changed
  209. var event = { etype: 'node', action: 'devicesessions', nodeid: nodeid, domain: sender.domainid, sessions: portInfo.sessions, nolog: 1 };
  210. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, event);
  211. }
  212. }
  213. } else {
  214. if (obj.managedPorts[nodeid] != null) {
  215. // This port is no longer connected
  216. parent.ClearConnectivityState(sender.meshid, nodeid, 1, null, null);
  217. const mesh = parent.webserver.meshes[sender.meshid];
  218. // If the device group policy is set to auto-remove devices, remove it now
  219. if ((mesh != null) && (mesh.flags) && (mesh.flags & 1)) { // Auto-remove devices
  220. parent.db.Remove(nodeid); // Remove node with that id
  221. parent.db.Remove('nt' + nodeid); // Remove notes
  222. parent.db.Remove('lc' + nodeid); // Remove last connect time
  223. parent.db.Remove('al' + nodeid); // Remove error log last time
  224. parent.db.RemoveAllNodeEvents(nodeid); // Remove all events for this node
  225. parent.db.removeAllPowerEventsForNode(nodeid); // Remove all power events for this node
  226. // Event node deletion
  227. parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(sender.meshid, [nodeid]), obj, { etype: 'node', action: 'removenode', nodeid: nodeid, domain: domain.id, nolog: 1 });
  228. }
  229. // Remove the managed port
  230. delete obj.managedPorts[nodeid];
  231. }
  232. }
  233. }
  234. }
  235. // Generate the nodeid from the device group and device identifier
  236. function generateIpKvmNodeId(meshid, portid, domainid) {
  237. return 'node/' + domainid + '/' + parent.crypto.createHash('sha384').update(Buffer.from(meshid + '/' + portid)).digest().toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
  238. }
  239. // Parse an incoming HTTP request URL
  240. function parseIpKvmUrl(domain, url) {
  241. const q = require('url').parse(url, true);
  242. const i = q.path.indexOf('/ipkvm.ashx/');
  243. if (i == -1) return null;
  244. const urlargs = q.path.substring(i + 12).split('/');
  245. if (urlargs[0].length != 64) return null;
  246. const nodeid = 'node/' + domain.id + '/' + urlargs[0];
  247. const nid = urlargs[0];
  248. const kvmport = obj.managedPorts[nodeid];
  249. if (kvmport == null) return null;
  250. const kvmmanager = obj.managedGroups[kvmport.meshid];
  251. if (kvmmanager == null) return null;
  252. urlargs.shift();
  253. var relurl = '/' + urlargs.join('/');
  254. if (relurl.endsWith('/.websocket')) { relurl = relurl.substring(0, relurl.length - 11); }
  255. return { domain: domain.id, relurl: relurl, preurl: q.path.substring(0, i + 76), nodeid: nodeid, nid: nid, kvmmanager: kvmmanager, kvmport: kvmport };
  256. }
  257. // Handle a IP-KVM HTTP get request
  258. obj.handleIpKvmGet = function (domain, req, res, next) {
  259. // Parse the URL and get information about this KVM port
  260. const reqinfo = parseIpKvmUrl(domain, req.url);
  261. if (reqinfo == null) { next(); return; }
  262. // Check node rights
  263. if ((req.session == null) || (req.session.userid == null)) { next(); return; }
  264. const user = parent.webserver.users[req.session.userid];
  265. if (user == null) { next(); return; }
  266. const rights = parent.webserver.GetNodeRights(user, reqinfo.kvmmanager.meshid, reqinfo.nodeid);
  267. if ((rights & MESHRIGHT_REMOTECONTROL) == 0) { next(); return; }
  268. // Process the request
  269. reqinfo.kvmmanager.handleIpKvmGet(domain, reqinfo, req, res, next);
  270. }
  271. // Handle a IP-KVM HTTP websocket request
  272. obj.handleIpKvmWebSocket = function (domain, ws, req) {
  273. // Parse the URL and get information about this KVM port
  274. const reqinfo = parseIpKvmUrl(domain, req.url);
  275. if (reqinfo == null) { try { ws.close(); } catch (ex) { } return; }
  276. // Check node rights
  277. if ((req.session == null) || (req.session.userid == null)) { try { ws.close(); } catch (ex) { } return; }
  278. const user = parent.webserver.users[req.session.userid];
  279. if (user == null) { try { ws.close(); } catch (ex) { } return; }
  280. const rights = parent.webserver.GetNodeRights(user, reqinfo.kvmmanager.meshid, reqinfo.nodeid);
  281. if ((rights & MESHRIGHT_REMOTECONTROL) == 0) { try { ws.close(); } catch (ex) { } return; }
  282. // Add more logging data to the request information
  283. reqinfo.clientIp = req.clientIp;
  284. reqinfo.userid = req.session.userid;
  285. reqinfo.username = user.name;
  286. // Process the request
  287. reqinfo.kvmmanager.handleIpKvmWebSocket(domain, reqinfo, ws, req);
  288. }
  289. return obj;
  290. }
  291. // Create Raritan Dominion KX III Manager
  292. function CreateRaritanKX3Manager(parent, hostname, port, username, password) {
  293. const https = require('https');
  294. const obj = {};
  295. var updateTimer = null;
  296. var retryTimer = null;
  297. obj.authCookie = null;
  298. obj.state = 0; // 0 = Disconnected, 1 = Connecting, 2 = Connected
  299. obj.ports = [];
  300. obj.portCount = 0;
  301. obj.portHash = null;
  302. obj.deviceCount = 0;
  303. obj.deviceHash = null;
  304. obj.started = false;
  305. // Events
  306. obj.onStateChanged = null;
  307. obj.onPortsChanged = null;
  308. function onCheckServerIdentity(cert) {
  309. console.log('TODO: Certificate Check');
  310. }
  311. obj.start = function () {
  312. if (obj.started) return;
  313. obj.started = true;
  314. if (obj.relayid) {
  315. obj.router = CreateMiniRouter(parent, obj.relayid, hostname, port);
  316. obj.router.start(function () { connect(); });
  317. } else {
  318. connect();
  319. }
  320. }
  321. obj.stop = function () {
  322. if (!obj.started) return;
  323. obj.started = false;
  324. if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
  325. setState(0);
  326. if (obj.router) { obj.router.stop(); delete obj.router; }
  327. }
  328. // If the relay device has changed, update our router
  329. obj.updateRelayId = function (relayid) {
  330. obj.relayid = relayid;
  331. if (obj.router != null) { obj.router.nodeid = relayid; }
  332. }
  333. function setState(newState) {
  334. if (obj.state == newState) return;
  335. obj.state = newState;
  336. if (obj.onStateChanged != null) { obj.onStateChanged(obj, newState); }
  337. if ((newState == 2) && (updateTimer == null)) { updateTimer = setInterval(obj.update, 10000); }
  338. if ((newState != 2) && (updateTimer != null)) { clearInterval(updateTimer); updateTimer = null; }
  339. if ((newState == 0) && (obj.started == true) && (retryTimer == null)) { retryTimer = setTimeout(connect, 20000); }
  340. if (newState == 0) { obj.ports = []; obj.portCount = 0; obj.deviceCount = 0; }
  341. }
  342. function connect() {
  343. if (obj.state != 0) return;
  344. setState(1); // 1 = Connecting
  345. obj.authCookie = null;
  346. if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
  347. 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');
  348. const options = {
  349. hostname: hostname,
  350. port: port,
  351. rejectUnauthorized: false,
  352. checkServerIdentity: onCheckServerIdentity,
  353. path: '/auth.asp?client=javascript', // ?client=standalone
  354. method: 'POST',
  355. headers: {
  356. 'Content-Type': 'text/html; charset=UTF-8',
  357. 'Content-Length': data.length
  358. }
  359. }
  360. const req = https.request(options, function (res) {
  361. if (obj.state == 0) return;
  362. if ((res.statusCode != 302) || (res.headers['set-cookie'] == null) || (res.headers['location'] == null)) { setState(0); return; }
  363. 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]; } }
  364. if (obj.authCookie == null) { setState(0); return; }
  365. res.on('data', function (d) { })
  366. fetchInitialInformation();
  367. })
  368. req.on('error', function (error) { setState(0); });
  369. req.on('timeout', function () { setState(0); });
  370. req.write(data);
  371. req.end();
  372. }
  373. function checkCookie() {
  374. if (obj.state != 2) return;
  375. const options = {
  376. hostname: hostname,
  377. port: port,
  378. rejectUnauthorized: false,
  379. checkServerIdentity: onCheckServerIdentity,
  380. path: '/cookiecheck.asp',
  381. method: 'GET',
  382. headers: {
  383. 'Content-Type': 'text/html; charset=UTF-8',
  384. 'Cookie': 'pp_session_id=' + obj.authCookie
  385. }
  386. }
  387. const req = https.request(options, function (res) {
  388. if (obj.state == 0) return;
  389. if (res.statusCode != 302) { setState(0); return; }
  390. 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]; } } }
  391. res.on('data', function (d) { })
  392. });
  393. req.on('error', function (error) { setState(0); });
  394. req.on('timeout', function () { setState(0); });
  395. req.end();
  396. }
  397. function fetchInitialInformation() {
  398. obj.fetch('/webs_cron.asp?_portsstatushash=&_devicesstatushash=&webs_job=sidebarupdates', null, null, function (server, tag, data) {
  399. data = data.toString();
  400. const parsed = parseJsScript(data);
  401. for (var i in parsed['updateSidebarPanel']) {
  402. if (parsed['updateSidebarPanel'][i][0] == "cron_device") {
  403. obj.firmwareVersion = getSubString(parsed['updateSidebarPanel'][i][1], "Firmware: ", "<");
  404. obj.deviceModel = getSubString(parsed['updateSidebarPanel'][i][1], "<div class=\"device-model\">", "<");
  405. }
  406. }
  407. obj.fetch('/sidebar.asp', null, null, function (server, tag, data) {
  408. data = data.toString();
  409. var dataBlock = getSubString(data, "updateKVMLinkHintOnContainer();", "devices.resetDevicesNew(1);");
  410. if (dataBlock == null) { setState(0); return; }
  411. const parsed = parseJsScript(dataBlock);
  412. obj.portCount = parseInt(parsed['updatePortStatus'][0][0]) - 2;
  413. obj.portHash = parsed['updatePortStatus'][0][1];
  414. obj.deviceCount = parseInt(parsed['updateDeviceStatus'][0][0]);
  415. obj.deviceHash = parsed['updateDeviceStatus'][0][1];
  416. var updatedPorts = [];
  417. for (var i = 0; i < parsed['addPortNew'].length; i++) {
  418. const portInfo = parsePortInfo(parsed['addPortNew'][i]);
  419. obj.ports[portInfo.hIndex] = portInfo;
  420. updatedPorts.push(portInfo.hIndex);
  421. }
  422. setState(2);
  423. if (obj.onPortsChanged != null) { obj.onPortsChanged(obj, updatedPorts); }
  424. });
  425. });
  426. }
  427. obj.update = function () {
  428. obj.fetch('/webs_cron.asp?_portsstatushash=' + obj.portHash + '&_devicesstatushash=' + obj.deviceHash, null, null, function (server, tag, data) {
  429. data = data.toString();
  430. const parsed = parseJsScript(data);
  431. if (parsed['updatePortStatus']) {
  432. obj.portCount = parseInt(parsed['updatePortStatus'][0][0]) - 2;
  433. obj.portHash = parsed['updatePortStatus'][0][1];
  434. }
  435. if (parsed['updateDeviceStatus']) {
  436. obj.deviceCount = parseInt(parsed['updateDeviceStatus'][0][0]);
  437. obj.deviceHash = parsed['updateDeviceStatus'][0][1];
  438. }
  439. if (parsed['updatePort']) {
  440. var updatedPorts = [];
  441. for (var i = 0; i < parsed['updatePort'].length; i++) {
  442. const portInfo = parsePortInfo(parsed['updatePort'][i]);
  443. obj.ports[portInfo.hIndex] = portInfo;
  444. updatedPorts.push(portInfo.hIndex);
  445. }
  446. if ((updatedPorts.length > 0) && (obj.onPortsChanged != null)) { obj.onPortsChanged(obj, updatedPorts); }
  447. }
  448. });
  449. }
  450. function parsePortInfo(args) {
  451. var out = {};
  452. for (var i = 0; i < args.length; i++) {
  453. var parsed = parseJsScript(args[i]);
  454. var v = parsed.J[0][1], vv = parseInt(v);
  455. out[parsed.J[0][0]] = (v == vv) ? vv : v;
  456. }
  457. return out;
  458. }
  459. function getSubString(str, start, end) {
  460. var i = str.indexOf(start);
  461. if (i < 0) return null;
  462. str = str.substring(i + start.length);
  463. i = str.indexOf(end);
  464. if (i >= 0) { str = str.substring(0, i); }
  465. return str;
  466. }
  467. // Parse JavaScript code calls
  468. function parseJsScript(str) {
  469. const out = {};
  470. var functionName = '';
  471. var args = [];
  472. var arg = null;
  473. var stack = [];
  474. for (var i = 0; i < str.length; i++) {
  475. if (stack.length == 0) {
  476. if (str[i] != '(') {
  477. if (isAlphaNumeric(str[i])) { functionName += str[i]; } else { functionName = ''; }
  478. } else {
  479. stack.push(')');
  480. }
  481. } else {
  482. if (str[i] == stack[stack.length - 1]) {
  483. if (stack.length > 1) { if (arg == null) { arg = str[i]; } else { arg += str[i]; } }
  484. if (stack.length == 2) {
  485. if (arg != null) { args.push(trimQuotes(arg)); }
  486. arg = null;
  487. } else if (stack.length == 1) {
  488. if (arg != null) { args.push(trimQuotes(arg)); arg = null; }
  489. if (args.length > 0) {
  490. if (out[functionName] == null) {
  491. out[functionName] = [args];
  492. } else {
  493. out[functionName].push(args);
  494. }
  495. }
  496. args = [];
  497. }
  498. stack.pop();
  499. } else if ((str[i] == '\'') || (str[i] == '"') || (str[i] == '(')) {
  500. if (str[i] == '(') { stack.push(')'); } else { stack.push(str[i]); }
  501. if (stack.length > 0) {
  502. if (arg == null) { arg = str[i]; } else { arg += str[i]; }
  503. }
  504. } else {
  505. if ((stack.length == 1) && (str[i] == ',')) {
  506. if (arg != null) { args.push(trimQuotes(arg)); arg = null; }
  507. } else {
  508. if (stack.length > 0) { if (arg == null) { arg = str[i]; } else { arg += str[i]; } }
  509. }
  510. }
  511. }
  512. }
  513. return out;
  514. }
  515. function trimQuotes(str) {
  516. if ((str == null) || (str.length < 2)) return str;
  517. str = str.trim();
  518. if ((str[0] == '\'') && (str[str.length - 1] == '\'')) { return str.substring(1, str.length - 1); }
  519. if ((str[0] == '"') && (str[str.length - 1] == '"')) { return str.substring(1, str.length - 1); }
  520. return str;
  521. }
  522. function isAlphaNumeric(char) {
  523. return ((char >= 'A') && (char <= 'Z')) || ((char >= 'a') && (char <= 'z')) || ((char >= '0') && (char <= '9'));
  524. }
  525. obj.fetch = function (url, postdata, tag, func) {
  526. if (obj.state == 0) return;
  527. var data = [];
  528. const options = {
  529. hostname: obj.router ? 'localhost' : hostname,
  530. port: obj.router ? obj.router.tcpServerPort : port,
  531. rejectUnauthorized: false,
  532. checkServerIdentity: onCheckServerIdentity,
  533. path: url,
  534. method: (postdata != null) ? 'POST' : 'GET',
  535. headers: {
  536. 'Content-Type': 'text/html; charset=UTF-8',
  537. 'Cookie': 'pp_session_id=' + obj.authCookie
  538. }
  539. }
  540. const req = https.request(options, function (res) {
  541. if (obj.state == 0) return;
  542. if (res.statusCode != 200) { setState(0); return; }
  543. 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]; } } }
  544. res.on('data', function (d) { data.push(d); });
  545. res.on('end', function () {
  546. // This line is used for debugging only, used to swap a file.
  547. //if (url.endsWith('js_kvm_client.1604062083669.min.js')) { data = [ parent.parent.fs.readFileSync('c:\\tmp\\js_kvm_client.1604062083669.min.js') ] ; }
  548. func(obj, tag, Buffer.concat(data), res);
  549. });
  550. });
  551. req.on('error', function (error) { setState(0); });
  552. req.on('timeout', function () { setState(0); });
  553. req.end();
  554. }
  555. // Handle a IP-KVM HTTP get request
  556. obj.handleIpKvmGet = function (domain, reqinfo, req, res, next) {
  557. if (reqinfo.relurl == '/') { res.redirect(reqinfo.preurl + '/jsclient/Client.asp'); return; }
  558. // Example: /jsclient/Client.asp#portId=P_000d5d20f64c_1
  559. obj.fetch(reqinfo.relurl, null, [res, reqinfo], function (server, args, data, rres) {
  560. const resx = args[0], xreqinfo = args[1];
  561. if (rres.headers['content-type']) { resx.set('content-type', rres.headers['content-type']); }
  562. if (xreqinfo.relurl.startsWith('/js/js_kvm_client.')) {
  563. data = data.toString();
  564. // Since our cookies can't be read from the html page for security, we embed a dummy cookie into the page.
  565. data = data.replace('module$js$helper$Extensions.Utils.getCookieValue("pp_session_id")', '"DUMMCOOKIEY"');
  566. // Add the connection information directly into the file.
  567. 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 + '");');
  568. // Replace the WebSocket code in one of the files to make it work with our server.
  569. data = data.replace('b=new WebSocket(e+"//"+c+"/"+g);', 'b=new WebSocket(e+"//"+c+"/ipkvm.ashx/' + xreqinfo.nid + '/"+g);');
  570. }
  571. resx.end(data);
  572. });
  573. }
  574. function logConnection(wsClient) {
  575. const kvmport = wsClient.kvmport
  576. const reqinfo = wsClient.reqinfo;
  577. 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 };
  578. parent.parent.DispatchEvent(['*', reqinfo.userid, reqinfo.nodeid, kvmport.meshid], obj, event);
  579. }
  580. function logDisconnection(wsClient) {
  581. const kvmport = wsClient.kvmport
  582. const reqinfo = wsClient.reqinfo;
  583. 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 };
  584. parent.parent.DispatchEvent(['*', reqinfo.userid, reqinfo.nodeid, kvmport.meshid], obj, event);
  585. delete kvmport.bytesIn;
  586. delete kvmport.bytesOut;
  587. delete kvmport.connectionStart;
  588. delete wsClient.reqinfo;
  589. }
  590. // Handle a IP-KVM HTTP websocket request
  591. obj.handleIpKvmWebSocket = function (domain, reqinfo, ws, req) {
  592. ws._socket.pause();
  593. //console.log('handleIpKvmWebSocket', reqinfo.preurl);
  594. if (reqinfo.kvmport.wsClient != null) {
  595. // Relay already open
  596. //console.log('IPKVM Relay already present');
  597. try { ws.close(); } catch (ex) { }
  598. } else {
  599. // Setup a websocket-to-websocket relay
  600. try {
  601. const options = {
  602. rejectUnauthorized: false,
  603. servername: 'raritan', // We set this to remove the IP address warning from NodeJS.
  604. headers: { Cookie: 'pp_session_id=' + obj.authCookie + '; view_length=32' }
  605. };
  606. parent.parent.debug('relay', 'IPKVM: Relay connecting to: wss://' + hostname + ':' + port + '/rfb');
  607. const WebSocket = require('ws');
  608. reqinfo.kvmport.wsClient = new WebSocket('wss://' + hostname + ':' + port + '/rfb', options);
  609. reqinfo.kvmport.wsClient.wsBrowser = ws;
  610. ws.wsClient = reqinfo.kvmport.wsClient;
  611. reqinfo.kvmport.wsClient.kvmport = reqinfo.kvmport;
  612. reqinfo.kvmport.wsClient.reqinfo = reqinfo;
  613. reqinfo.kvmport.connectionStart = Date.now();
  614. reqinfo.kvmport.bytesIn = 0;
  615. reqinfo.kvmport.bytesOut = 0;
  616. logConnection(reqinfo.kvmport.wsClient);
  617. reqinfo.kvmport.wsClient.on('open', function () {
  618. parent.parent.debug('relay', 'IPKVM: Relay websocket open');
  619. this.wsBrowser.on('message', function (data) {
  620. //console.log('KVM browser data', data.toString('hex'), data.toString('utf8'));
  621. // Replace the authentication command that used the dummy cookie with a command that has the correct hash
  622. if ((this.xAuthNonce != null) && (this.xAuthNonce != 1) && (data.length == 67) && (data[0] == 0x21) && (data[1] == 0x41)) {
  623. const hash = Buffer.from(require('crypto').createHash('sha256').update(this.xAuthNonce + obj.authCookie).digest().toString('hex'));
  624. data = Buffer.alloc(67);
  625. data[0] = 0x21; // Auth Command
  626. data[1] = 0x41; // Length
  627. hash.copy(data, 2); // Hash
  628. this.xAuthNonce = 1;
  629. }
  630. // Check the port name
  631. if ((data[0] == 0x89) && (data.length > 4)) {
  632. const portNameLen = (data[2] << 8) + data[3];
  633. if (data.length == (4 + portNameLen)) {
  634. const portName = data.slice(4).toString('utf8');
  635. if (reqinfo.kvmport.portid != portName) {
  636. // The browser required an unexpected port for remote control, disconnect not.
  637. try { this._socket.close(); } catch (ex) { }
  638. return;
  639. }
  640. }
  641. }
  642. try { this.wsClient.kvmport.bytesOut += data.length; } catch (ex) { }
  643. this._socket.pause();
  644. try { this.wsClient.send(data); } catch (ex) { }
  645. this._socket.resume();
  646. });
  647. this.wsBrowser.on('close', function () {
  648. parent.parent.debug('relay', 'IPKVM: Relay browser websocket closed');
  649. // Clean up
  650. if (this.wsClient) {
  651. logDisconnection(this.wsClient);
  652. try { this.wsClient.close(); } catch (ex) { }
  653. try {
  654. if (this.wsClient.kvmport) {
  655. delete this.wsClient.kvmport.wsClient;
  656. delete this.wsClient.kvmport;
  657. }
  658. delete this.wsClient.wsBrowser;
  659. delete this.wsClient;
  660. } catch (ex) { console.log(ex); }
  661. }
  662. });
  663. this.wsBrowser.on('error', function (err) {
  664. parent.parent.debug('relay', 'IPKVM: Relay browser websocket error: ' + err);
  665. });
  666. this.wsBrowser._socket.resume();
  667. });
  668. reqinfo.kvmport.wsClient.on('message', function (data) { // Make sure to handle flow control.
  669. //console.log('KVM switch data', data, data.length, data.toString('hex'));
  670. // If the data start with 0x21 and 0x41 followed by {SHA256}, store the authenticate nonce
  671. if ((this.wsBrowser.xAuthNonce == null) && (data.length == 67) && (data[0] == 0x21) && (data[1] == 0x41) && (data[2] == 0x7b) && (data[3] == 0x53) && (data[4] == 0x48)) {
  672. this.wsBrowser.xAuthNonce = data.slice(2).toString().substring(0, 64);
  673. }
  674. try { this.wsBrowser.wsClient.kvmport.bytesIn += data.length; } catch (ex) { }
  675. this._socket.pause();
  676. try { this.wsBrowser.send(data); } catch (ex) { }
  677. this._socket.resume();
  678. });
  679. reqinfo.kvmport.wsClient.on('close', function () {
  680. parent.parent.debug('relay', 'IPKVM: Relay websocket closed');
  681. // Clean up
  682. try {
  683. if (this.wsBrowser) {
  684. logDisconnection(this.wsBrowser.wsClient);
  685. try { this.wsBrowser.close(); } catch (ex) { }
  686. delete this.wsBrowser.wsClient; delete this.wsBrowser;
  687. }
  688. if (this.kvmport) { delete this.kvmport.wsClient; delete this.kvmport; }
  689. } catch (ex) { console.log(ex); }
  690. });
  691. reqinfo.kvmport.wsClient.on('error', function (err) {
  692. parent.parent.debug('relay', 'IPKVM: Relay websocket error: ' + err);
  693. });
  694. } catch (ex) { console.log(ex); }
  695. }
  696. }
  697. return obj;
  698. }
  699. // Create WebPowerSwitch Manager
  700. function CreateWebPowerSwitch(parent, hostname, port, username, password) {
  701. port = 80;
  702. const https = require('http');
  703. const crypto = require('crypto');
  704. const obj = {};
  705. var updateTimer = null;
  706. var retryTimer = null;
  707. var challenge = null;
  708. var challengeRetry = 0;
  709. var nonceCounter = 1;
  710. obj.state = 0; // 0 = Disconnected, 1 = Connecting, 2 = Connected
  711. obj.ports = [];
  712. obj.portCount = 0;
  713. obj.started = false;
  714. obj.onStateChanged = null;
  715. obj.onPortsChanged = null;
  716. function onCheckServerIdentity(cert) {
  717. console.log('TODO: Certificate Check');
  718. }
  719. obj.start = function () {
  720. if (obj.started) return;
  721. obj.started = true;
  722. if (obj.state == 0) {
  723. if (obj.relayid) {
  724. obj.router = CreateMiniRouter(parent, obj.relayid, hostname, port);
  725. obj.router.start(function () { connect(); });
  726. } else {
  727. connect();
  728. }
  729. }
  730. }
  731. obj.stop = function () {
  732. if (!obj.started) return;
  733. obj.started = false;
  734. if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
  735. setState(0);
  736. obj.ports = [];
  737. if (obj.router) { obj.router.stop(); delete obj.router; }
  738. }
  739. // If the relay device has changed, update our router
  740. obj.updateRelayId = function (relayid) {
  741. obj.relayid = relayid;
  742. if (obj.router != null) { obj.router.nodeid = relayid; }
  743. }
  744. function setState(newState) {
  745. if (obj.state == newState) return;
  746. obj.state = newState;
  747. if (obj.onStateChanged != null) { obj.onStateChanged(obj, newState); }
  748. if ((newState == 2) && (updateTimer == null)) { updateTimer = setInterval(obj.update, 10000); }
  749. if ((newState != 2) && (updateTimer != null)) { clearInterval(updateTimer); updateTimer = null; }
  750. if ((newState == 0) && (obj.started == true) && (retryTimer == null)) { retryTimer = setTimeout(connect, 20000); }
  751. if (newState == 0) { obj.ports = []; obj.portCount = 0; }
  752. }
  753. function connect() {
  754. if (obj.state != 0) return;
  755. if (retryTimer != null) { clearTimeout(retryTimer); retryTimer = null; }
  756. setState(1); // 1 = Connecting
  757. obj.update();
  758. }
  759. obj.update = function () {
  760. obj.fetch('/restapi/relay/outlets/all;/=name,physical_state/', 'GET', null, null, function (sender, tag, rdata, res) {
  761. if (res.statusCode == 207) {
  762. var rdata2 = null;
  763. if (rdata != null) { try { rdata2 = JSON.parse(rdata); } catch (ex) { } }
  764. if (Array.isArray(rdata2)) {
  765. obj.portCount = (rdata2.length / 2);
  766. setState(2); // 2 = Connected
  767. const updatedPorts = [];
  768. for (var i = 0; i < (rdata2.length / 2); i++) {
  769. const portname = rdata2[i * 2];
  770. const portstate = rdata2[(i * 2) + 1];
  771. var portchanged = false;
  772. if (obj.ports[i] == null) {
  773. // Add the port
  774. obj.ports[i] = { PortNumber: i + 1, PortId: 'p' + i, Name: portname, Status: 1, State: portstate, Class: 'PDU' };
  775. portchanged = true;
  776. } else {
  777. // Update the port
  778. const port = obj.ports[i];
  779. if (port.Name != portname) { port.Name = portname; portchanged = true; }
  780. if (port.State != portstate) { port.State = portstate; portchanged = true; }
  781. }
  782. if (portchanged) { updatedPorts.push(i); }
  783. }
  784. if ((updatedPorts.length > 0) && (obj.onPortsChanged != null)) { obj.onPortsChanged(obj, updatedPorts); }
  785. } else {
  786. setState(0); // 0 = Disconnected
  787. }
  788. } else {
  789. setState(0); // 0 = Disconnected
  790. }
  791. });
  792. }
  793. obj.powerOperation = function (event) {
  794. if (typeof event.portnum != 'number') return;
  795. if (event.action == 'turnon') { setPowerState(event.portnum - 1, true); }
  796. else if (event.action == 'turnoff') { setPowerState(event.portnum - 1, false); }
  797. }
  798. function setPowerState(port, state, func) {
  799. obj.fetch('/restapi/relay/outlets/' + port + '/state/', 'PUT', 'value=' + state, null, function (sender, tag, rdata, res) {
  800. if (res.statusCode == 204) { obj.update(); }
  801. });
  802. }
  803. obj.fetch = function (url, method, data, tag, func) {
  804. if (obj.state == 0) return;
  805. if (typeof data == 'string') { data = Buffer.from(data); }
  806. var rdata = [];
  807. const options = {
  808. hostname: obj.router ? 'localhost' : hostname,
  809. port: obj.router ? obj.router.tcpServerPort : port,
  810. rejectUnauthorized: false,
  811. checkServerIdentity: onCheckServerIdentity,
  812. path: url,
  813. method: method,
  814. headers: {
  815. 'Content-Type': 'application/x-www-form-urlencoded',
  816. 'accept': 'application/json',
  817. 'X-CSRF': 'x'
  818. }
  819. }
  820. if (data != null) { options.headers['Content-Length'] = data.length; }
  821. if (challenge != null) {
  822. const buf = Buffer.alloc(10);
  823. challenge.cnonce = crypto.randomFillSync(buf).toString('hex');
  824. challenge.nc = nonceCounter++;
  825. const ha1 = crypto.createHash('md5');
  826. ha1.update([username, challenge.realm, password].join(':'));
  827. var xha1 = ha1.digest('hex')
  828. const ha2 = crypto.createHash('md5');
  829. ha2.update([options.method, options.path].join(':'));
  830. var xha2 = ha2.digest('hex');
  831. const response = crypto.createHash('md5');
  832. response.update([xha1, challenge.nonce, challenge.nc, challenge.cnonce, challenge.qop, xha2].join(':'));
  833. var requestParams = {
  834. "username": username,
  835. "realm": challenge.realm,
  836. "nonce": challenge.nonce,
  837. "uri": options.path,
  838. "response": response.digest('hex'),
  839. "cnonce": challenge.cnonce,
  840. "opaque": challenge.opaque
  841. };
  842. options.headers = options.headers || {};
  843. options.headers.Authorization = renderDigest(requestParams) + ', algorithm=MD5, nc=' + challenge.nc + ', qop=' + challenge.qop;
  844. }
  845. const req = https.request(options, function (res) {
  846. if (obj.state == 0) return;
  847. //console.log('res.statusCode', res.statusCode);
  848. //if (res.statusCode != 200) { console.log(res.statusCode, res.headers, Buffer.concat(data).toString()); setState(0); return; }
  849. challengeRetry = 0;
  850. res.on('data', function (d) { rdata.push(d); });
  851. res.on('end', function () {
  852. if (res.statusCode == 401) {
  853. challengeRetry++;
  854. if (challengeRetry > 4) { setState(0); return; }
  855. challenge = parseChallenge(res.headers['www-authenticate']);
  856. obj.fetch(url, method, data, tag, func);
  857. return;
  858. } else {
  859. // This line is used for debugging only, used to swap a file.
  860. func(obj, tag, Buffer.concat(rdata), res);
  861. }
  862. });
  863. });
  864. req.on('error', function (error) { setState(0); });
  865. req.on('timeout', function () { setState(0); });
  866. if (data) { req.write(data); }
  867. req.end();
  868. }
  869. function parseChallenge(header) {
  870. header = header.replace('qop="auth,auth-int"', 'qop="auth"'); // We don't support auth-int yet, easiest way to get rid of it.
  871. const prefix = 'Digest ';
  872. const challenge = header.substr(header.indexOf(prefix) + prefix.length);
  873. const parts = challenge.split(',');
  874. const length = parts.length;
  875. const params = {};
  876. for (var i = 0; i < length; i++) {
  877. var part = parts[i].match(/^\s*?([a-zA-Z0-0]+)="(.*)"\s*?$/);
  878. if (part && part.length > 2) { params[part[1]] = part[2]; }
  879. }
  880. return params;
  881. }
  882. function renderDigest(params) {
  883. const parts = [];
  884. for (var i in params) { parts.push(i + '="' + params[i] + '"'); }
  885. return 'Digest ' + parts.join(', ');
  886. }
  887. return obj;
  888. }
  889. // Mini TCP port router
  890. function CreateMiniRouter(parent, nodeid, targetHost, targetPort) {
  891. const Net = require('net');
  892. const WebSocket = require('ws');
  893. const obj = {};
  894. const tcpSockets = {}
  895. obj.tcpServerPort = 0;
  896. obj.nodeid = nodeid;
  897. obj.targetHost = targetHost;
  898. obj.targetPort = targetPort;
  899. parent.parent.debug('relay', 'MiniRouter: Request relay for ' + obj.targetHost + ':' + obj.targetPort + ' thru ' + nodeid + '.');
  900. // Close a TCP socket and the coresponding web socket.
  901. function closeTcpSocket(tcpSocket) {
  902. if (tcpSockets[tcpSocket]) {
  903. delete tcpSockets[tcpSocket];
  904. try { tcpSocket.end(); } catch (ex) { console.log(ex); }
  905. if (tcpSocket.relaySocket) { try { tcpSocket.relaySocket.close(); } catch (ex) { console.log(ex); } }
  906. try { delete tcpSocket.relaySocket.tcpSocket; } catch (ex) { }
  907. try { delete tcpSocket.relaySocket; } catch (ex) { }
  908. }
  909. }
  910. // Close a web socket and the coresponding TCP socket.
  911. function closeWebSocket(webSocket) {
  912. const tcpSocket = webSocket.tcpSocket;
  913. if (tcpSocket) { closeTcpSocket(tcpSocket); }
  914. }
  915. // Start the looppback server
  916. obj.start = function(onReadyFunc) {
  917. obj.tcpServer = new Net.Server();
  918. obj.tcpServer.listen(0, 'localhost', function () {
  919. obj.tcpServerPort = obj.tcpServer.address().port;
  920. parent.parent.debug('relay', 'MiniRouter: Request for relay ' + obj.targetHost + ':' + obj.targetPort + ' started on port ' + obj.tcpServerPort);
  921. onReadyFunc(obj.tcpServerPort, obj);
  922. });
  923. obj.tcpServer.on('connection', function (socket) {
  924. tcpSockets[socket] = 1;
  925. socket.pause();
  926. socket.on('data', function (chunk) { // Make sure to handle flow control.
  927. const f = function sendDone() { sendDone.tcpSocket.resume(); }
  928. f.tcpSocket = this;
  929. if (this.relaySocket && this.relaySocket.active) { this.pause(); this.relaySocket.send(chunk, f); }
  930. });
  931. socket.on('end', function () { closeTcpSocket(this); });
  932. socket.on('close', function () { closeTcpSocket(this); });
  933. socket.on('error', function (err) { closeTcpSocket(this); });
  934. // Encode the device relay cookie. Note that there is no userid in this cookie.
  935. const domainid = obj.nodeid.split('/')[1];
  936. const cookie = parent.parent.encodeCookie({ nouser: 1, domainid: domainid, nodeid: obj.nodeid, tcpaddr: obj.targetHost, tcpport: obj.targetPort }, parent.parent.loginCookieEncryptionKey);
  937. const domain = parent.parent.config.domains[domainid];
  938. // Setup the correct URL with domain and use TLS only if needed.
  939. const options = { rejectUnauthorized: false };
  940. const protocol = (parent.parent.args.tlsoffload) ? 'ws' : 'wss';
  941. var domainadd = '';
  942. if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
  943. 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?
  944. parent.parent.debug('relay', 'MiniRouter: Connection websocket to ' + url);
  945. socket.relaySocket = new WebSocket(url, options);
  946. socket.relaySocket.tcpSocket = socket;
  947. socket.relaySocket.on('open', function () { parent.parent.debug('relay', 'MiniRouter: Relay websocket open'); });
  948. socket.relaySocket.on('message', function (data) { // Make sure to handle flow control.
  949. if (!this.active) {
  950. if (data == 'c') {
  951. // Relay Web socket is connected, start data relay
  952. this.active = true;
  953. this.tcpSocket.resume();
  954. } else {
  955. // Could not connect web socket, close it
  956. closeWebSocket(this);
  957. }
  958. } else {
  959. // Relay more data
  960. this._socket.pause();
  961. const f = function sendDone() { sendDone.webSocket._socket.resume(); }
  962. f.webSocket = this;
  963. this.tcpSocket.write(data, f);
  964. }
  965. });
  966. socket.relaySocket.on('close', function (reasonCode, description) { parent.parent.debug('relay', 'MiniRouter: Relay websocket closed'); closeWebSocket(this); });
  967. socket.relaySocket.on('error', function (err) { parent.parent.debug('relay', 'MiniRouter: Relay websocket error: ' + err); closeWebSocket(this); });
  968. });
  969. }
  970. // Stop the looppback server and all relay sockets
  971. obj.stop = function () {
  972. for (var tcpSocket in tcpSockets) { closeTcpSocket(tcpSocket); }
  973. obj.tcpServer.close();
  974. obj.tcpServer = null;
  975. }
  976. return obj;
  977. }
  978. module.exports.CreateIPKVMManager = CreateIPKVMManager;