meshdesktopmultiplex.js 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. /**
  2. * @description MeshCentral remote desktop multiplexor
  3. * @author Ylian Saint-Hilaire
  4. * @copyright Intel Corporation 2018-2022
  5. * @license Apache-2.0
  6. * @version v0.0.1
  7. */
  8. /*jslint node: true */
  9. /*jshint node: true */
  10. /*jshint strict:false */
  11. /*jshint -W097 */
  12. /*jshint esversion: 6 */
  13. "use strict";
  14. /*
  15. --- KVM Commands ---
  16. MNG_KVM_NOP = 0,
  17. MNG_KVM_KEY = 1,
  18. MNG_KVM_MOUSE = 2,
  19. MNG_KVM_MOUSE_CURSOR = 88,
  20. MNG_KVM_MOUSE_MOVE = 89,
  21. MNG_KVM_PICTURE = 3,
  22. MNG_KVM_COPY = 4,
  23. MNG_KVM_COMPRESSION = 5,
  24. MNG_KVM_REFRESH = 6,
  25. MNG_KVM_SCREEN = 7,
  26. MNG_KVM_PAUSE = 8,
  27. MNG_TERMTEXT = 9,
  28. MNG_CTRLALTDEL = 10,
  29. MNG_KVM_GET_DISPLAYS = 11,
  30. MNG_KVM_SET_DISPLAY = 12,
  31. MNG_KVM_FRAME_RATE_TIMER = 13,
  32. MNG_KVM_INIT_TOUCH = 14,
  33. MNG_KVM_TOUCH = 15,
  34. MNG_KVM_CONNECTCOUNT = 16,
  35. MNG_KVM_MESSAGE = 17,
  36. MNG_KVM_KEYSTATE = 18,
  37. MNG_ECHO = 21,
  38. MNG_JUMBO = 27,
  39. MNG_GETDIR = 50,
  40. MNG_FILEMOVE = 51,
  41. MNG_FILEDELETE = 52,
  42. MNG_FILECOPY = 53,
  43. MNG_FILECREATEDIR = 54,
  44. MNG_FILETRANSFER = 55,
  45. MNG_FILEUPLOAD = 56,
  46. MNG_FILESEARCH = 57,
  47. MNG_FILETRANSFER2 = 58,
  48. MNG_KVM_DISCONNECT = 59,
  49. MNG_GETDIR2 = 60, // Same as MNG_GETDIR but with date/time.
  50. MNG_FILEUPLOAD2 = 61, // Used for slot based fast upload.
  51. MNG_FILEDELETEREC = 62, // Same as MNG_FILEDELETE but recursive
  52. MNG_USERCONSENT = 63, // Used to notify management console of user consent state
  53. MNG_DEBUG = 64, // Debug/Logging Message for ILibRemoteLogging
  54. MNG_ERROR = 65,
  55. MNG_ENCAPSULATE_AGENT_COMMAND = 70,
  56. MNG_KVM_DISPLAY_INFO = 82
  57. */
  58. function CreateDesktopMultiplexor(parent, domain, nodeid, id, func) {
  59. var obj = {};
  60. obj.id = id; // Unique identifier for this session
  61. obj.nodeid = nodeid; // Remote device nodeid for this session
  62. obj.parent = parent; // Parent web server instance
  63. obj.agent = null; // Reference to the connection object that is the agent.
  64. obj.viewers = []; // Array of references to all viewers.
  65. obj.viewersOverflowCount = 0; // Number of viewers currently in overflow state.
  66. obj.width = 0; // Current width of the display in pixels.
  67. obj.height = 0; // Current height of the display in pixels.
  68. obj.swidth = 0; // Current width of the display in tiles.
  69. obj.sheight = 0; // Current height of the display in tiles.
  70. obj.screen = null; // The main screen, (x * y) --> tile index. Indicates this image is covering each tile on the screen.
  71. obj.counter = 1; // The main counter, used as index for the obj.images table when now images come in.
  72. obj.imagesCount = 0; // Total number of images in the obj.images table.
  73. obj.imagesCounters = {}; // Main table of indexes --> tile count, the number of tiles still using this image.
  74. obj.images = {}; // Main table of indexes --> image data object.
  75. obj.lastScreenSizeCmd = null; // Pointer to the last screen size command from the agent.
  76. obj.lastScreenSizeCounter = 0; // Index into the image table of the screen size command, this is generally also the first command.
  77. obj.lastConsoleMessage = null; // Last agent console message.
  78. obj.firstData = null; // Index in the image table of the first image in the table, generally this points to the display resolution command.
  79. obj.lastData = null; // Index in the images table of the last image in the table.
  80. obj.lastDisplayInfoData = null; // Pointer to the last display information command from the agent (Number of displays).
  81. obj.lastDisplayLocationData = null; // Pointer to the last display location and size command from the agent.
  82. obj.lastKeyState = null; // Pointer to the last key state command from the agent.
  83. obj.desktopPaused = true; // Current desktop pause state, it's true if all viewers are paused.
  84. obj.imageType = 1; // Current image type, 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = WebP
  85. obj.imageCompression = 50; // Current image compression, this is the highest value of all viewers.
  86. obj.imageScaling = 1024; // Current image scaling, this is the highest value of all viewers.
  87. obj.imageFrameRate = 50; // Current framerate setting, this is the lowest values of all viewers.
  88. obj.protocolOptions = null; // Set to the protocol options of the first viewer that connected.
  89. obj.viewerConnected = false; // Set to true if one viewer attempted to connect to the agent.
  90. obj.recordingFile = null; // Present if we are recording to file.
  91. obj.recordingFileSize = 0; // Current size of the recording file.
  92. obj.recordingFileWriting = false; // Set to true is we are in the process if writing to the recording file.
  93. obj.startTime = null; // Starting time of the multiplex session.
  94. obj.userIds = []; // List of userid's that have intertracted with this session.
  95. //obj.autoLock = false; // Automatically lock the remote device once disconnected
  96. // Accounting
  97. parent.trafficStats.desktopMultiplex.sessions++;
  98. // Add an agent or viewer
  99. obj.addPeer = function (peer) {
  100. if (obj.viewers == null) { parent.parent.debug('relay', 'DesktopRelay: Error, addingPeer on disposed session'); return; }
  101. if (peer.req == null) return; // This peer is already disposed, don't add it.
  102. if (peer.req.query.browser) {
  103. //console.log('addPeer-viewer', obj.nodeid);
  104. // Setup the viewer
  105. if (obj.viewers.indexOf(peer) >= 0) return true;
  106. obj.viewers.push(peer);
  107. peer.desktopPaused = true;
  108. peer.imageType = 1;
  109. peer.imageCompression = 30;
  110. peer.imageScaling = 1024;
  111. peer.imageFrameRate = 100;
  112. peer.lastImageNumberSent = null;
  113. peer.dataPtr = obj.firstData;
  114. peer.sending = false;
  115. peer.overflow = false;
  116. peer.sendQueue = [];
  117. peer.paused = false;
  118. peer.startTime = Date.now();
  119. // Add the user to the userids list if needed
  120. if ((peer.user != null) && (obj.userIds.indexOf(peer.user._id) == -1)) { obj.userIds.push(peer.user._id); }
  121. // Setup slow relay is requested. This will show down sending any data to this viewer.
  122. if ((peer.req.query.slowrelay != null)) {
  123. var sr = null;
  124. try { sr = parseInt(peer.req.query.slowrelay); } catch (ex) { }
  125. if ((typeof sr == 'number') && (sr > 0) && (sr < 1000)) { peer.slowRelay = sr; }
  126. }
  127. // Update user last access time
  128. if ((peer.user != null) && (peer.guestName == null)) {
  129. const user = parent.users[peer.user._id];
  130. if (user != null) {
  131. const timeNow = Math.floor(Date.now() / 1000);
  132. if (user.access < (timeNow - 300)) { // Only update user access time if longer than 5 minutes
  133. user.access = timeNow;
  134. parent.db.SetUser(user);
  135. // Event the change
  136. var message = { etype: 'user', userid: user._id, username: user.name, account: parent.CloneSafeUser(user), action: 'accountchange', domain: domain.id, nolog: 1 };
  137. if (parent.db.changeStream) { message.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
  138. var targets = ['*', 'server-users', user._id];
  139. if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
  140. parent.parent.DispatchEvent(targets, obj, message);
  141. }
  142. }
  143. }
  144. // Check session recording
  145. var startRecord = false;
  146. if (typeof domain.sessionrecording == 'object') {
  147. // Check if this user is set to record all sessions
  148. if ((domain.sessionrecording.onlyselectedusers === true) && (peer.user != null) && (peer.user.flags != null) && ((peer.user.flags & 2) != 0)) { startRecord = true; }
  149. else if (domain.sessionrecording.onlyselectedusergroups === true) {
  150. // Check if there is a usergroup that requires recording of the session
  151. var user = null;
  152. if (peer.user != null) { user = parent.users[peer.user._id]; }
  153. if ((user != null) && (user.links != null) && (user.links[obj.meshid] == null) && (user.links[obj.nodeid] == null)) {
  154. // This user does not have a direct link to the device group or device. Find all user groups the would cause the link.
  155. for (var i in user.links) {
  156. var ugrp = parent.userGroups[i];
  157. if ((ugrp != null) && (typeof ugrp.flags == 'number') && ((ugrp.flags & 2) != 0) && (ugrp.links != null) && ((ugrp.links[obj.meshid] != null) || (ugrp.links[obj.nodeid] != null))) { startRecord = true; }
  158. }
  159. }
  160. }
  161. }
  162. startRecording(domain, startRecord, function () {
  163. // Indicated we are connected
  164. obj.sendToViewer(peer, obj.recordingFile ? 'cr' : 'c');
  165. // If the agent sent display information or console message, send it to the viewer
  166. if (obj.lastDisplayInfoData != null) { obj.sendToViewer(peer, obj.lastDisplayInfoData); }
  167. if (obj.lastDisplayLocationData != null) { obj.sendToViewer(peer, obj.lastDisplayLocationData); }
  168. if (obj.lastConsoleMessage != null) { obj.sendToViewer(peer, obj.lastConsoleMessage); }
  169. if (obj.lastKeyState != null) { obj.sendToViewer(peer, obj.lastKeyState); }
  170. // Log joining the multiplex session
  171. if (obj.startTime != null) {
  172. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: peer.user ? peer.user._id : null, username: peer.user.name, msgid: 143, msgArgs: [obj.id], msg: "Joined desktop multiplex session \"" + obj.id + "\"", protocol: 2 };
  173. parent.parent.DispatchEvent(['*', obj.nodeid, peer.user._id, obj.meshid], obj, event);
  174. }
  175. // Send an updated list of all peers to all viewers
  176. obj.sendSessionMetadata();
  177. });
  178. } else {
  179. //console.log('addPeer-agent', obj.nodeid);
  180. if (obj.agent != null) { parent.parent.debug('relay', 'DesktopRelay: Error, duplicate agent connection'); return false; }
  181. // Setup the agent
  182. obj.agent = peer;
  183. peer.sending = false;
  184. peer.overflow = false;
  185. peer.sendQueue = [];
  186. peer.paused = false;
  187. // Indicated we are connected and send connection options and protocol if needed
  188. obj.sendToAgent(obj.recordingFile?'cr':'c');
  189. if (obj.viewerConnected == true) {
  190. if (obj.protocolOptions != null) { obj.sendToAgent(JSON.stringify(obj.protocolOptions)); } // Send connection options
  191. obj.sendToAgent('2'); // Send remote desktop connect
  192. }
  193. }
  194. // Log multiplex session start
  195. if ((obj.agent != null) && (obj.viewers.length > 0) && (obj.startTime == null)) {
  196. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, msgid: 145, msgArgs: [obj.id], msg: "Started desktop multiplex session \"" + obj.id + "\"", protocol: 2 };
  197. if (obj.viewers[0].user != null) { event.userid = obj.viewers[0].user._id; event.username = obj.viewers[0].user.name; }
  198. const targets = ['*', obj.nodeid, obj.meshid];
  199. if (obj.viewers[0].user != null) { targets.push(obj.viewers[0].user._id); }
  200. parent.parent.DispatchEvent(targets, obj, event);
  201. obj.startTime = Date.now();
  202. }
  203. return true;
  204. }
  205. // Remove an agent or viewer
  206. // Return true if this multiplexor is no longer needed.
  207. obj.removePeer = function (peer) {
  208. if (obj.viewers == null) return;
  209. if (peer == obj.agent) {
  210. //console.log('removePeer-agent', obj.nodeid);
  211. // Agent has disconnected, disconnect everyone.
  212. if (obj.viewers != null) { for (var i in obj.viewers) { obj.viewers[i].close(); } }
  213. // Clean up the agent
  214. obj.agent = null;
  215. dispose();
  216. return true;
  217. } else {
  218. //console.log('removePeer-viewer', obj.nodeid);
  219. // Remove a viewer
  220. if (obj.viewers != null) {
  221. var i = obj.viewers.indexOf(peer);
  222. if (i == -1) return false;
  223. obj.viewers.splice(i, 1);
  224. }
  225. // Resume flow control if this was the peer that was limiting traffic (because it was the fastest one).
  226. if (peer.overflow == true) {
  227. obj.viewersOverflowCount--;
  228. peer.overflow = false;
  229. if ((obj.viewersOverflowCount < obj.viewers.length) && (obj.recordingFileWriting == false) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
  230. }
  231. // Log leaving the multiplex session
  232. if (obj.startTime != null) { // Used to check if the agent has connected. If not, don't log this event since the session never really started.
  233. // In this code, we want to compute the share of in/out traffic that belongs to this viewer. It includes all of the viewers in/out traffic + all or a portion of the agents in/out traffic.
  234. // The agent traffic needs to get divided out between the viewers fairly. For the time that multiple viewers are present, the agent traffic is divided between the viewers.
  235. // Compute traffic to and from the browser
  236. var inTraffc, outTraffc;
  237. try { inTraffc = peer.ws._socket.bytesRead; } catch (ex) { }
  238. try { outTraffc = peer.ws._socket.bytesWritten; } catch (ex) { }
  239. // Add any previous agent traffic accounting
  240. if (peer.agentInTraffic) { inTraffc += peer.agentInTraffic; }
  241. if (peer.outTraffc) { inTraffc += peer.agentOutTraffic; }
  242. // Compute traffic to and from the agent
  243. if (obj.agent != null) {
  244. // Get unaccounted bytes from/to the agent
  245. var agentInTraffc, agentOutTraffc, agentInTraffc2, agentOutTraffc2;
  246. try { agentInTraffc = agentInTraffc2 = obj.agent.ws._socket.bytesRead; } catch (ex) { }
  247. try { agentOutTraffc = agentOutTraffc2 = obj.agent.ws._socket.bytesWritten; } catch (ex) { }
  248. if (obj.agent.accountedBytesRead) { agentInTraffc -= obj.agent.accountedBytesRead; }
  249. if (obj.agent.accountedBytesWritten) { agentOutTraffc -= obj.agent.accountedBytesWritten; }
  250. obj.agent.accountedBytesRead = agentInTraffc2;
  251. obj.agent.accountedBytesWritten = agentOutTraffc2;
  252. // Devide up the agent traffic amoung the viewers
  253. var viewerPartIn = Math.floor(agentInTraffc / (obj.viewers.length + 1));
  254. var viewerPartOut = Math.floor(agentOutTraffc / (obj.viewers.length + 1));
  255. // Add the portion to this viewer and all other viewer
  256. inTraffc += viewerPartIn;
  257. outTraffc += viewerPartOut;
  258. for (var i in obj.viewers) {
  259. if (obj.viewers[i].agentInTraffic) { obj.viewers[i].agentInTraffic += viewerPartIn; } else { obj.viewers[i].agentInTraffic = viewerPartIn; }
  260. if (obj.viewers[i].agentOutTraffic) { obj.viewers[i].agentOutTraffic += viewerPartOut; } else { obj.viewers[i].agentOutTraffic = viewerPartOut; }
  261. }
  262. }
  263. //var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: peer.user._id, username: peer.user.name, msgid: 5, msg: "Left the desktop multiplex session", protocol: 2 };
  264. const sessionSeconds = Math.floor((Date.now() - peer.startTime) / 1000);
  265. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, msgid: 144, msgArgs: [obj.id, sessionSeconds], msg: "Left the desktop multiplex session \"" + obj.id + "\" after " + sessionSeconds + " second(s).", protocol: 2, bytesin: inTraffc, bytesout: outTraffc };
  266. if (peer.user != null) { event.userid = peer.user._id; event.username = peer.user.name; }
  267. if (peer.guestName) { event.guestname = peer.guestName; }
  268. const targets = ['*', obj.nodeid, obj.meshid];
  269. if (peer.user != null) { targets.push(peer.user._id); }
  270. parent.parent.DispatchEvent(targets, obj, event);
  271. }
  272. // Aggressive clean up of the viewer
  273. delete peer.desktopPaused;
  274. delete peer.imageType;
  275. delete peer.imageCompression;
  276. delete peer.imageScaling;
  277. delete peer.imageFrameRate;
  278. delete peer.lastImageNumberSent;
  279. delete peer.dataPtr;
  280. delete peer.sending;
  281. delete peer.overflow;
  282. delete peer.sendQueue;
  283. delete peer.startTime;
  284. // If this is the last viewer, disconnect the agent
  285. if ((obj.viewers != null) && (obj.viewers.length == 0) && (obj.agent != null)) { obj.agent.close(); dispose(); return true; }
  286. // Send an updated list of all peers to all viewers
  287. obj.sendSessionMetadata();
  288. }
  289. return false;
  290. }
  291. // Clean up ourselves
  292. function dispose() {
  293. if (obj.viewers == null) return;
  294. //console.log('dispose', obj.nodeid);
  295. delete obj.viewers;
  296. delete obj.imagesCounters;
  297. delete obj.images;
  298. // Close the recording file if needed
  299. if (obj.recordingFile != null) {
  300. // Compute session length
  301. if (obj.startTime != null) { obj.sessionStart = obj.startTime; obj.sessionLength = Math.round((Date.now() - obj.startTime) / 1000); }
  302. // Write the last record of the recording file
  303. var rf = obj.recordingFile;
  304. delete obj.recordingFile;
  305. recordingEntry(rf.fd, 3, 0, 'MeshCentralMCREC', function (fd, filename) {
  306. parent.parent.fs.close(fd);
  307. // Now that the recording file is closed, check if we need to index this file.
  308. if (domain.sessionrecording.index && domain.sessionrecording.index !== false) { parent.parent.certificateOperations.acceleratorPerformOperation('indexMcRec', filename); }
  309. // Add a event entry about this recording
  310. var basefile = parent.parent.path.basename(filename);
  311. var event = { etype: 'relay', action: 'recording', domain: domain.id, nodeid: obj.nodeid, msgid: 146, msgArgs: [obj.id, obj.sessionLength], msg: "Finished recording session \"" + obj.id + "\", " + obj.sessionLength + " second(s)", filename: basefile, size: obj.recordingFileSize, protocol: 2, icon: obj.icon, name: obj.name, meshid: obj.meshid, userids: obj.userIds, multiplex: true };
  312. var mesh = parent.meshes[obj.meshid];
  313. if (mesh != null) { event.meshname = mesh.name; }
  314. if (obj.sessionStart) { event.startTime = obj.sessionStart; event.lengthTime = obj.sessionLength; }
  315. parent.parent.DispatchEvent(['*', 'recording', obj.nodeid, obj.meshid], obj, event);
  316. cleanUpRecordings();
  317. }, rf.filename);
  318. }
  319. // Log end of multiplex session
  320. if (obj.startTime != null) {
  321. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, msgid: 147, msgArgs: [obj.id, Math.floor((Date.now() - obj.startTime) / 1000)], msg: "Closed desktop multiplex session \"" + obj.id + "\", " + Math.floor((Date.now() - obj.startTime) / 1000) + ' second(s)', protocol: 2 };
  322. parent.parent.DispatchEvent(['*', obj.nodeid, obj.meshid], obj, event);
  323. obj.startTime = null;
  324. }
  325. // Send an updated list of all peers to all viewers
  326. obj.sendSessionMetadata();
  327. parent.parent.debug('relay', 'DesktopRelay: Disposing desktop multiplexor');
  328. }
  329. // Send data to the agent or queue it up for sending
  330. obj.sendToAgent = function (data) {
  331. if ((obj.viewers == null) || (obj.agent == null)) return;
  332. //console.log('SendToAgent', data.length);
  333. if (obj.agent.sending) {
  334. obj.agent.sendQueue.push(data);
  335. // Flow control, pause all viewers is the queue is backing up
  336. if (obj.agent.sendQueue > 10) {
  337. obj.agent.overflow = true;
  338. for (var i in obj.viewers) {
  339. var v = obj.viewers[i];
  340. if (v.paused == false) { v.paused = true; v.ws._socket.pause(); }
  341. }
  342. }
  343. } else {
  344. obj.agent.ws.send(data, sendAgentNext);
  345. }
  346. }
  347. // Send more data to the agent
  348. function sendAgentNext() {
  349. if ((obj.viewers == null) || (obj.agent == null)) return;
  350. if (obj.agent.sendQueue.length > 0) {
  351. // Send from the pending send queue
  352. obj.agent.ws.send(obj.agent.sendQueue.shift(), sendAgentNext);
  353. } else {
  354. // Nothing to send
  355. obj.agent.sending = false;
  356. // Flow control, resume all viewers
  357. if (obj.agent.overflow == true) {
  358. obj.agent.overflow = false;
  359. for (var i in obj.viewers) {
  360. var v = obj.viewers[i];
  361. if (v.paused == true) { v.paused = false; v.ws._socket.resume(); }
  362. }
  363. }
  364. }
  365. }
  366. // Send the list of all users currently vieweing this session to all viewers and servers
  367. obj.sendSessionMetadata = function () {
  368. var allUsers = {};
  369. if (obj.viewers != null) {
  370. for (var i in obj.viewers) {
  371. var v = obj.viewers[i];
  372. if ((v.user != null) && (v.user._id != null)) {
  373. var id = v.user._id;
  374. if (v.guestName) { id += '/guest:' + Buffer.from(v.guestName).toString('base64'); } // If this is a guest connect, add the Base64 guest name.
  375. if (allUsers[id] == null) { allUsers[id] = 1; } else { allUsers[id]++; }
  376. }
  377. }
  378. obj.sendToAllViewers(JSON.stringify({ type: 'metadata', 'ctrlChannel': '102938', users: allUsers, startTime: obj.startTime }));
  379. }
  380. // Update the sessions attached the to agent
  381. if (obj.nodeid != null) {
  382. const xagent = parent.wsagents[obj.nodeid];
  383. if (xagent != null) {
  384. if (xagent.sessions == null) { xagent.sessions = {}; }
  385. xagent.sessions.multidesk = allUsers;
  386. xagent.updateSessions();
  387. }
  388. }
  389. }
  390. // Send this command to all viewers
  391. obj.sendToAllViewers = function (data) {
  392. if (obj.viewers == null) return;
  393. for (var i in obj.viewers) { obj.sendToViewer(obj.viewers[i], data); }
  394. }
  395. // Send this command to all viewers
  396. obj.sendToAllInputViewers = function (data) {
  397. if (obj.viewers == null) return;
  398. for (var i in obj.viewers) { if (obj.viewers[i].viewOnly != true) { obj.sendToViewer(obj.viewers[i], data); } }
  399. }
  400. // Send data to the viewer or queue it up for sending
  401. obj.sendToViewer = function (viewer, data) {
  402. if ((viewer == null) || (obj.viewers == null)) return;
  403. //console.log('SendToViewer', data.length);
  404. if (viewer.sending) {
  405. viewer.sendQueue.push(data);
  406. } else {
  407. viewer.sending = true;
  408. if (viewer.slowRelay) {
  409. setTimeout(function () { try { viewer.ws.send(data, function () { sendViewerNext(viewer); }); } catch (ex) { } }, viewer.slowRelay);
  410. } else {
  411. try { viewer.ws.send(data, function () { sendViewerNext(viewer); }); } catch (ex) { }
  412. }
  413. // Flow control, pause the agent if needed
  414. checkViewerOverflow(viewer);
  415. }
  416. }
  417. // Check if a viewer is in overflow situation
  418. function checkViewerOverflow(viewer) {
  419. if ((viewer.overflow == true) || (obj.viewers == null)) return;
  420. if ((viewer.sendQueue.length > 5) || ((viewer.dataPtr != null) && (viewer.dataPtr != obj.lastData))) {
  421. viewer.overflow = true;
  422. obj.viewersOverflowCount++;
  423. if ((obj.viewersOverflowCount >= obj.viewers.length) && obj.agent && (obj.agent.paused == false)) { obj.agent.paused = true; obj.agent.ws._socket.pause(); }
  424. }
  425. }
  426. // Check if a viewer is in underflow situation
  427. function checkViewerUnderflow(viewer) {
  428. if ((viewer.overflow == false) || (obj.viewers == null)) return;
  429. if ((viewer.sendQueue.length <= 5) && ((viewer.dataPtr == null) || (viewer.dataPtr == obj.lastData))) {
  430. viewer.overflow = false;
  431. obj.viewersOverflowCount--;
  432. if ((obj.viewersOverflowCount < obj.viewers.length) && (obj.recordingFileWriting == false) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
  433. }
  434. }
  435. // Send more data to the viewer
  436. function sendViewerNext(viewer) {
  437. if ((viewer.sendQueue == null) || (obj.viewers == null)) return;
  438. if (viewer.sendQueue.length > 0) {
  439. // Send from the pending send queue
  440. if (viewer.sending == false) { viewer.sending = true; }
  441. if (viewer.slowRelay) {
  442. setTimeout(function () { try { viewer.ws.send(viewer.sendQueue.shift(), function () { sendViewerNext(viewer); }); } catch (ex) { } }, viewer.slowRelay);
  443. } else {
  444. try { viewer.ws.send(viewer.sendQueue.shift(), function () { sendViewerNext(viewer); }); } catch (ex) { }
  445. }
  446. checkViewerOverflow(viewer);
  447. } else {
  448. if (viewer.dataPtr != null) {
  449. // Send the next image
  450. //if ((viewer.lastImageNumberSent != null) && ((viewer.lastImageNumberSent + 1) != (viewer.dataPtr))) { console.log('SVIEW-S1', viewer.lastImageNumberSent, viewer.dataPtr); } // DEBUG
  451. var image = obj.images[viewer.dataPtr];
  452. viewer.lastImageNumberSent = viewer.dataPtr;
  453. //if ((image.next != null) && ((viewer.dataPtr + 1) != image.next)) { console.log('SVIEW-S2', viewer.dataPtr, image.next); } // DEBUG
  454. viewer.dataPtr = image.next;
  455. if (viewer.slowRelay) {
  456. setTimeout(function () { try { viewer.ws.send(image.data, function () { sendViewerNext(viewer); }); } catch (ex) { } }, viewer.slowRelay);
  457. } else {
  458. try { viewer.ws.send(image.data, function () { sendViewerNext(viewer); }); } catch (ex) { }
  459. }
  460. // Flow control, pause the agent if needed
  461. if (viewer.sending == false) { viewer.sending = true; }
  462. checkViewerOverflow(viewer);
  463. } else {
  464. // Nothing to send
  465. viewer.sending = false;
  466. // Flow control, resume agent if needed
  467. checkViewerUnderflow(viewer);
  468. }
  469. }
  470. }
  471. // Process data coming from the agent or any viewers
  472. obj.processData = function (peer, data) {
  473. if (obj.viewers == null) return;
  474. if (peer == obj.agent) {
  475. obj.recordingFileWriting = true;
  476. recordData(true, data, function () {
  477. if (obj.viewers == null) return;
  478. obj.recordingFileWriting = false;
  479. if ((obj.viewersOverflowCount < obj.viewers.length) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
  480. obj.processAgentData(data);
  481. });
  482. } else {
  483. obj.processViewerData(peer, data);
  484. }
  485. }
  486. // Process incoming viewer data
  487. obj.processViewerData = function (viewer, data) {
  488. if (typeof data == 'string') {
  489. if (data == '2') {
  490. if (obj.viewerConnected == false) {
  491. if (obj.agent != null) {
  492. if (obj.protocolOptions != null) { obj.sendToAgent(JSON.stringify(obj.protocolOptions)); } // Send connection options
  493. obj.sendToAgent('2'); // Send remote desktop connect
  494. }
  495. obj.viewerConnected = true;
  496. }
  497. return;
  498. }
  499. var json = null;
  500. try { json = JSON.parse(data); } catch (ex) { }
  501. if (json == null) return;
  502. if ((json.type == 'options') && (obj.protocolOptions == null)) { obj.protocolOptions = json; }
  503. if (json.ctrlChannel == '102938') {
  504. if ((json.type == 'lock') && (viewer.viewOnly == false)) { obj.sendToAgent('{"ctrlChannel":"102938","type":"lock"}'); } // Account lock support
  505. if ((json.type == 'autolock') && (viewer.viewOnly == false) && (typeof json.value == 'boolean')) { obj.sendToAgent('{"ctrlChannel":"102938","type":"autolock","value":' + json.value + '}'); } // Lock on disconnect
  506. }
  507. return;
  508. }
  509. //console.log('ViewerData', data.length, typeof data, data);
  510. if ((typeof data != 'object') || (data.length < 4)) return; // Ignore all control traffic for now (WebRTC)
  511. var command = data.readUInt16BE(0);
  512. var cmdsize = data.readUInt16BE(2);
  513. if (data.length != cmdsize) return; // Invalid command length
  514. //console.log('ViewerData', data.length, command, cmdsize);
  515. switch (command) {
  516. case 1: // Key Events, forward to agent
  517. if (viewer.viewOnly == false) { obj.sendToAgent(data); }
  518. break;
  519. case 2: // Mouse events, forward to agent
  520. if (viewer.viewOnly == false) { obj.sendToAgent(data); }
  521. break;
  522. case 5: // Compression
  523. if (data.length < 10) return;
  524. viewer.imageType = data[4]; // Image type: 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = WebP
  525. viewer.imageCompression = data[5];
  526. viewer.imageScaling = data.readUInt16BE(6);
  527. viewer.imageFrameRate = data.readUInt16BE(8);
  528. //console.log('Viewer-Compression', viewer.imageType, viewer.imageCompression, viewer.imageScaling, viewer.imageFrameRate);
  529. // See if this changes anything
  530. var viewersimageType = null;
  531. var viewersimageCompression = null;
  532. var viewersimageScaling = null;
  533. var viewersimageFrameRate = null;
  534. for (var i in obj.viewers) {
  535. if (viewersimageType == null) { viewersimageType = obj.viewers[i].imageType; } else if (obj.viewers[i].imageType != viewersimageType) { viewersimageType = 1; }; // Default to JPEG if viewers has different image formats
  536. if ((viewersimageCompression == null) || (obj.viewers[i].imageCompression > viewersimageCompression)) { viewersimageCompression = obj.viewers[i].imageCompression; };
  537. if ((viewersimageScaling == null) || (obj.viewers[i].imageScaling > viewersimageScaling)) { viewersimageScaling = obj.viewers[i].imageScaling; };
  538. if ((viewersimageFrameRate == null) || (obj.viewers[i].imageFrameRate < viewersimageFrameRate)) { viewersimageFrameRate = obj.viewers[i].imageFrameRate; };
  539. }
  540. if ((obj.imageCompression != viewersimageCompression) || (obj.imageScaling != viewersimageScaling) || (obj.imageFrameRate != viewersimageFrameRate)) {
  541. // Update and send to agent new compression settings
  542. obj.imageType = viewersimageType;
  543. obj.imageCompression = viewersimageCompression;
  544. obj.imageScaling = viewersimageScaling;
  545. obj.imageFrameRate = viewersimageFrameRate
  546. //console.log('Send-Agent-Compression', obj.imageType, obj.imageCompression, obj.imageScaling, obj.imageFrameRate);
  547. var cmd = Buffer.alloc(10);
  548. cmd.writeUInt16BE(5, 0); // Command 5, compression
  549. cmd.writeUInt16BE(10, 2); // Command size, 10 bytes long
  550. cmd[4] = obj.imageType; // Image type: 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = WebP
  551. cmd[5] = obj.imageCompression; // Image compression level
  552. cmd.writeUInt16BE(obj.imageScaling, 6); // Scaling level
  553. cmd.writeUInt16BE(obj.imageFrameRate, 8); // Frame rate timer
  554. obj.sendToAgent(cmd);
  555. }
  556. break;
  557. case 6: // Refresh, handle this on the server
  558. //console.log('Viewer-Refresh');
  559. viewer.dataPtr = obj.firstData; // Start over
  560. if (viewer.sending == false) { sendViewerNext(viewer); }
  561. break;
  562. case 8: // Pause and unpause
  563. if (data.length != 5) break;
  564. var pause = data[4]; // 0 = Unpause, 1 = Pause
  565. if (viewer.desktopPaused == (pause == 1)) break;
  566. viewer.desktopPaused = (pause == 1);
  567. //console.log('Viewer-' + ((pause == 1)?'Pause':'UnPause'));
  568. var viewersPaused = true;
  569. for (var i in obj.viewers) { if (obj.viewers[i].desktopPaused == false) { viewersPaused = false; }; }
  570. if (viewersPaused != obj.desktopPaused) {
  571. obj.desktopPaused = viewersPaused;
  572. //console.log('Send-Agent-' + ((viewersPaused == true) ? 'Pause' : 'UnPause'));
  573. data[4] = (viewersPaused == true) ? 1 : 0;
  574. obj.sendToAgent(data);
  575. }
  576. break;
  577. case 10: // CTRL-ALT-DEL, forward to agent
  578. if (viewer.viewOnly == false) { obj.sendToAgent(data); }
  579. break;
  580. case 12: // SET DISPLAY, forward to agent
  581. if (viewer.viewOnly == false) { obj.sendToAgent(data); }
  582. break;
  583. case 14: // Touch setup
  584. break;
  585. case 82: // Request display information
  586. if (obj.lastDisplayLocationData != null) { obj.sendToAgent(obj.lastDisplayLocationData); }
  587. break;
  588. case 85: // Unicode Key Events, forward to agent
  589. if (viewer.viewOnly == false) { obj.sendToAgent(data); }
  590. break;
  591. case 87: // Remote input lock, forward to agent
  592. if (viewer.viewOnly == false) { obj.sendToAgent(data); }
  593. break;
  594. default:
  595. console.log('Un-handled viewer command: ' + command);
  596. break;
  597. }
  598. }
  599. // Process incoming agent data
  600. obj.processAgentData = function (data) {
  601. if ((typeof data != 'object') || (data.length < 4)) {
  602. if (typeof data == 'string') {
  603. var json = null;
  604. try { json = JSON.parse(data); } catch (ex) { }
  605. if (json == null) return;
  606. if (json.type == 'console') {
  607. // This is a console message, store it and forward this to all viewers
  608. if (json.msg != null) { obj.lastConsoleMessage = data; } else { obj.lastConsoleMessage = null; }
  609. obj.sendToAllViewers(data);
  610. }
  611. // All other control messages (notably WebRTC), are ignored for now.
  612. }
  613. return; // Ignore all other traffic
  614. }
  615. const jumboData = data;
  616. var command = data.readUInt16BE(0);
  617. var cmdsize = data.readUInt16BE(2);
  618. //console.log('AgentData', data.length, command, cmdsize);
  619. if ((command == 27) && (cmdsize == 8)) {
  620. // Jumbo packet
  621. if (data.length >= 12) {
  622. command = data.readUInt16BE(8);
  623. cmdsize = data.readUInt32BE(4);
  624. if (data.length == (cmdsize + 8)) {
  625. data = data.slice(8, data.length);
  626. } else {
  627. console.log('TODO-PARTIAL-JUMBO', command, cmdsize, data.length);
  628. return; // TODO
  629. }
  630. }
  631. }
  632. switch (command) {
  633. case 3: // Tile, check dimentions and store
  634. if ((data.length < 10) || (obj.lastData == null)) break;
  635. var x = data.readUInt16BE(4), y = data.readUInt16BE(6);
  636. var dimensions = require('image-size')(data.slice(8));
  637. var sx = (x / 16), sy = (y / 16), sw = (dimensions.width / 16), sh = (dimensions.height / 16);
  638. obj.counter++;
  639. // Keep a reference to this image & how many tiles it covers
  640. obj.images[obj.counter] = { next: null, prev: obj.lastData, data: jumboData };
  641. obj.images[obj.lastData].next = obj.counter;
  642. obj.lastData = obj.counter;
  643. obj.imagesCounters[obj.counter] = (sw * sh);
  644. obj.imagesCount++;
  645. if (obj.imagesCount == 2000000000) { obj.imagesCount = 1; } // Loop the counter if needed
  646. //console.log('Adding Image ' + obj.counter, x, y, dimensions.width, dimensions.height);
  647. // Update the screen with the correct pointers.
  648. for (var i = 0; i < sw; i++) {
  649. for (var j = 0; j < sh; j++) {
  650. var k = ((obj.swidth * (j + sy)) + (i + sx));
  651. const oi = obj.screen[k];
  652. obj.screen[k] = obj.counter;
  653. if ((oi != null) && (--obj.imagesCounters[oi] == 0)) {
  654. // Remove data from the link list
  655. obj.imagesCount--;
  656. var d = obj.images[oi];
  657. //console.log('Removing Image', oi, obj.images[oi].prev, obj.images[oi].next);
  658. obj.images[d.prev].next = d.next;
  659. obj.images[d.next].prev = d.prev;
  660. delete obj.images[oi];
  661. delete obj.imagesCounters[oi];
  662. // If any viewers are currently on image "oi" must be moved to "d.next"
  663. for (var l in obj.viewers) { const v = obj.viewers[l]; if (v.dataPtr == oi) { v.dataPtr = d.next; } }
  664. }
  665. }
  666. }
  667. // Any viewer on dataPtr null, change to this image
  668. for (var i in obj.viewers) {
  669. const v = obj.viewers[i];
  670. if (v.dataPtr == null) { v.dataPtr = obj.counter; if (v.sending == false) { sendViewerNext(v); } }
  671. }
  672. // Debug, display the link list
  673. //var xx = '', xptr = obj.firstData;
  674. //while (xptr != null) { xx += '>' + xptr; xptr = obj.images[xptr].next; }
  675. //console.log('list', xx);
  676. //console.log('images', obj.imagesCount);
  677. break;
  678. case 4: // Tile Copy, do nothing.
  679. break;
  680. case 7: // Screen Size, clear the screen state and compute the tile count
  681. if (data.length < 8) break;
  682. if ((obj.width === data.readUInt16BE(4)) && (obj.height === data.readUInt16BE(6))) break; // Same screen size as before, skip this.
  683. obj.counter++;
  684. obj.lastScreenSizeCmd = data;
  685. obj.lastScreenSizeCounter = obj.counter;
  686. obj.width = data.readUInt16BE(4);
  687. obj.height = data.readUInt16BE(6);
  688. obj.swidth = obj.width / 16;
  689. obj.sheight = obj.height / 16;
  690. if (Math.floor(obj.swidth) != obj.swidth) { obj.swidth = Math.floor(obj.swidth) + 1; }
  691. if (Math.floor(obj.sheight) != obj.sheight) { obj.sheight = Math.floor(obj.sheight) + 1; }
  692. // Reset the display
  693. obj.screen = new Array(obj.swidth * obj.sheight);
  694. obj.imagesCount = 0;
  695. obj.imagesCounters = {};
  696. obj.images = {};
  697. obj.images[obj.counter] = { next: null, prev: null, data: data };
  698. obj.firstData = obj.counter;
  699. obj.lastData = obj.counter;
  700. // Add viewers must be set to start at "obj.counter"
  701. for (var i in obj.viewers) {
  702. const v = obj.viewers[i];
  703. v.dataPtr = obj.counter;
  704. if (v.sending == false) { sendViewerNext(v); }
  705. }
  706. //console.log("ScreenSize", obj.width, obj.height, obj.swidth, obj.sheight, obj.swidth * obj.sheight);
  707. break;
  708. case 11: // GetDisplays
  709. // Store and send this to all viewers right away
  710. obj.lastDisplayInfoData = data;
  711. obj.sendToAllInputViewers(data);
  712. break;
  713. case 12: // SetDisplay
  714. obj.sendToAllInputViewers(data);
  715. break;
  716. case 14: // KVM_INIT_TOUCH
  717. break;
  718. case 15: // KVM_TOUCH
  719. break;
  720. case 17: // MNG_KVM_MESSAGE
  721. // Send this to all viewers right away
  722. obj.sendToAllViewers(data);
  723. break;
  724. case 18: // MNG_KVM_KEYSTATE
  725. // Store and send this to all viewers right away
  726. obj.lastKeyState = data;
  727. obj.sendToAllInputViewers(data);
  728. break;
  729. case 65: // Alert
  730. // Send this to all viewers right away
  731. obj.sendToAllViewers(data);
  732. break;
  733. case 82:
  734. // Display information
  735. if ((data.length < 14) || (((data.length - 4) % 10) != 0)) break; // Command must be 14 bytes and have header + 10 byte for each display.
  736. obj.lastDisplayLocationData = data;
  737. obj.sendToAllInputViewers(data);
  738. break;
  739. case 87: // MNG_KVM_INPUT_LOCK
  740. // Send this to all viewers right away
  741. // This will update all views on the current state of the input lock
  742. obj.sendToAllInputViewers(data);
  743. break;
  744. case 88: // MNG_KVM_MOUSE_CURSOR
  745. // Send this to all viewers right away
  746. obj.sendToAllInputViewers(data);
  747. break;
  748. default:
  749. console.log('Un-handled agent command: ' + command + ', length: ' + cmdsize);
  750. break;
  751. }
  752. }
  753. function startRecording(domain, start, func) {
  754. if ((obj.pendingRecording == 1) || (obj.recordingFile != null)) { func(true); return; } // Check if already recording
  755. if (start == false) { func(false); return; } // Just skip this
  756. obj.pendingRecording = 1;
  757. var now = new Date(Date.now());
  758. var recFilename = 'desktopSession' + ((domain.id == '') ? '' : '-') + domain.id + '-' + now.getUTCFullYear() + '-' + parent.common.zeroPad(now.getUTCMonth() + 1, 2) + '-' + parent.common.zeroPad(now.getUTCDate(), 2) + '-' + parent.common.zeroPad(now.getUTCHours(), 2) + '-' + parent.common.zeroPad(now.getUTCMinutes(), 2) + '-' + parent.common.zeroPad(now.getUTCSeconds(), 2) + '-' + obj.nodeid.split('/')[2] + '.mcrec'
  759. var recFullFilename = null;
  760. if (domain.sessionrecording.filepath) {
  761. try { parent.parent.fs.mkdirSync(domain.sessionrecording.filepath); } catch (e) { }
  762. recFullFilename = parent.parent.path.join(domain.sessionrecording.filepath, recFilename);
  763. } else {
  764. try { parent.parent.fs.mkdirSync(parent.parent.recordpath); } catch (e) { }
  765. recFullFilename = parent.parent.path.join(parent.parent.recordpath, recFilename);
  766. }
  767. parent.parent.fs.open(recFullFilename, 'w', function (err, fd) {
  768. delete obj.pendingRecording;
  769. if (err != null) {
  770. parent.parent.debug('relay', 'Relay: Unable to record to file: ' + recFullFilename);
  771. func(false);
  772. return;
  773. }
  774. // Write the recording file header
  775. parent.parent.debug('relay', 'Relay: Started recoding to file: ' + recFullFilename);
  776. var metadata = { magic: 'MeshCentralRelaySession', ver: 1, nodeid: obj.nodeid, meshid: obj.meshid, time: new Date().toLocaleString(), protocol: 2, devicename: obj.name, devicegroup: obj.meshname };
  777. var firstBlock = JSON.stringify(metadata);
  778. recordingEntry(fd, 1, 0, firstBlock, function () {
  779. obj.recordingFile = { fd: fd, filename: recFullFilename };
  780. obj.recordingFileWriting = false;
  781. func(true);
  782. });
  783. });
  784. }
  785. // Here, we check if we have to record the device, regardless of what user is looking at it.
  786. function recordingSetup(domain, func) {
  787. var record = false;
  788. // Setup session recording
  789. if (((domain.sessionrecording == true) || ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.protocols == null) || (domain.sessionrecording.protocols.indexOf(2) >= 0))))) {
  790. record = true;
  791. // Check again to make sure we need to start recording
  792. if ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.onlyselecteddevicegroups === true) || (domain.sessionrecording.onlyselectedusergroups === true) || (domain.sessionrecording.onlyselectedusers === true))) {
  793. record = false;
  794. // Check device group recording
  795. if (domain.sessionrecording.onlyselecteddevicegroups === true) {
  796. var mesh = parent.meshes[obj.meshid];
  797. if ((mesh.flags != null) && ((mesh.flags & 4) != 0)) { record = true; }
  798. }
  799. }
  800. }
  801. startRecording(domain, record, func);
  802. }
  803. // Record data to the recording file
  804. function recordData(isAgent, data, func) {
  805. try {
  806. if (obj.recordingFile != null) {
  807. // Write data to recording file
  808. recordingEntry(obj.recordingFile.fd, 2, (isAgent ? 0 : 2), data, function () { func(data); });
  809. } else {
  810. func(data);
  811. }
  812. } catch (ex) { console.log(ex); }
  813. }
  814. // Record a new entry in a recording log
  815. function recordingEntry(fd, type, flags, data, func, tag) {
  816. try {
  817. if (typeof data == 'string') {
  818. // String write
  819. var blockData = Buffer.from(data), header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
  820. header.writeInt16BE(type, 0); // Type (1 = Header, 2 = Network Data)
  821. header.writeInt16BE(flags, 2); // Flags (1 = Binary, 2 = User)
  822. header.writeInt32BE(blockData.length, 4); // Size
  823. header.writeIntBE(new Date(), 10, 6); // Time
  824. var block = Buffer.concat([header, blockData]);
  825. parent.parent.fs.write(fd, block, 0, block.length, function () { func(fd, tag); });
  826. obj.recordingFileSize += block.length;
  827. } else {
  828. // Binary write
  829. var header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
  830. header.writeInt16BE(type, 0); // Type (1 = Header, 2 = Network Data)
  831. header.writeInt16BE(flags | 1, 2); // Flags (1 = Binary, 2 = User)
  832. header.writeInt32BE(data.length, 4); // Size
  833. header.writeIntBE(new Date(), 10, 6); // Time
  834. var block = Buffer.concat([header, data]);
  835. parent.parent.fs.write(fd, block, 0, block.length, function () { func(fd, tag); });
  836. obj.recordingFileSize += block.length;
  837. }
  838. } catch (ex) { console.log(ex); func(fd, tag); }
  839. }
  840. // If there is a recording quota, remove any old recordings if needed
  841. function cleanUpRecordings() {
  842. if ((parent.cleanUpRecordingsActive !== true) && domain.sessionrecording && ((typeof domain.sessionrecording.maxrecordings == 'number') || (typeof domain.sessionrecording.maxrecordingsizemegabytes == 'number') || (typeof domain.sessionrecording.maxrecordingdays == 'number'))) {
  843. parent.cleanUpRecordingsActive = true;
  844. setTimeout(function () {
  845. var recPath = null, fs = require('fs'), now = Date.now();
  846. if (domain.sessionrecording.filepath) { recPath = domain.sessionrecording.filepath; } else { recPath = parent.parent.recordpath; }
  847. fs.readdir(recPath, function (err, files) {
  848. if ((err != null) || (files == null)) { delete parent.cleanUpRecordingsActive; return; }
  849. var recfiles = [];
  850. for (var i in files) {
  851. if (files[i].endsWith('.mcrec')) {
  852. var j = files[i].indexOf('-');
  853. if (j > 0) {
  854. var stats = null;
  855. try { stats = fs.statSync(parent.parent.path.join(recPath, files[i])); } catch (ex) { }
  856. if (stats != null) { recfiles.push({ n: files[i], r: files[i].substring(j + 1), s: stats.size, t: stats.mtimeMs }); }
  857. }
  858. }
  859. }
  860. recfiles.sort(function (a, b) { if (a.r < b.r) return 1; if (a.r > b.r) return -1; return 0; });
  861. var totalFiles = 0, totalSize = 0;
  862. for (var i in recfiles) {
  863. var overQuota = false;
  864. if ((typeof domain.sessionrecording.maxrecordings == 'number') && (domain.sessionrecording.maxrecordings > 0) && (totalFiles >= domain.sessionrecording.maxrecordings)) { overQuota = true; }
  865. else if ((typeof domain.sessionrecording.maxrecordingsizemegabytes == 'number') && (domain.sessionrecording.maxrecordingsizemegabytes > 0) && (totalSize >= (domain.sessionrecording.maxrecordingsizemegabytes * 1048576))) { overQuota = true; }
  866. else if ((typeof domain.sessionrecording.maxrecordingdays == 'number') && (domain.sessionrecording.maxrecordingdays > 0) && (((now - recfiles[i].t) / 1000 / 60 / 60 / 24) >= domain.sessionrecording.maxrecordingdays)) { overQuota = true; }
  867. if (overQuota) { fs.unlinkSync(parent.parent.path.join(recPath, recfiles[i].n)); }
  868. totalFiles++;
  869. totalSize += recfiles[i].s;
  870. }
  871. delete parent.cleanUpRecordingsActive;
  872. });
  873. }, 500);
  874. }
  875. }
  876. // Get node information
  877. parent.db.Get(nodeid, function (err, nodes) {
  878. if ((err != null) || (nodes.length != 1)) { func(null); return; }
  879. obj.meshid = nodes[0].meshid;
  880. obj.icon = nodes[0].icon;
  881. obj.name = nodes[0].name;
  882. recordingSetup(domain, function () { func(obj); });
  883. });
  884. return obj;
  885. }
  886. function checkDeviceSharePublicIdentifier(parent, domain, nodeid, pid, extraKey, func) {
  887. // Check the public id
  888. parent.db.GetAllTypeNodeFiltered([nodeid], domain.id, 'deviceshare', null, function (err, docs) {
  889. if ((err != null) || (docs.length == 0)) { func(false); return; }
  890. // Search for the device share public identifier
  891. var found = false;
  892. for (var i = 0; i < docs.length; i++) { if ((docs[i].publicid == pid) && ((docs[i].extrakey == null) || (docs[i].extrakey === extraKey))) { found = true; } }
  893. func(found);
  894. });
  895. }
  896. module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie) {
  897. if ((cookie != null) && (typeof cookie.nid == 'string') && (typeof cookie.pid == 'string')) {
  898. checkDeviceSharePublicIdentifier(parent, domain, cookie.nid, cookie.pid, cookie.k, function (result) {
  899. // If the identifier if not found, close the connection
  900. if (result == false) { try { ws.close(); } catch (e) { } return; }
  901. // Public device sharing identifier found, continue as normal.
  902. CreateMeshRelayEx(parent, ws, req, domain, user, cookie);
  903. });
  904. } else {
  905. CreateMeshRelayEx(parent, ws, req, domain, user, cookie);
  906. }
  907. }
  908. // If we are in multi-server mode, the desktop multiplexor needs to be created on the server with the agent connected to it.
  909. // So, if the agent is connected to a different server, just relay the connection to that server
  910. function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
  911. // Do validation work
  912. if (cookie) {
  913. if ((typeof cookie.expire == 'number') && (cookie.expire <= Date.now())) { delete req.query.nodeid; }
  914. else if (typeof cookie.nid == 'string') { req.query.nodeid = cookie.nid; }
  915. }
  916. if ((req.query.nodeid == null) || (req.query.p != '2') || (req.query.id == null) || (domain == null)) { try { ws.close(); } catch (e) { } return; } // Not is not a valid remote desktop connection.
  917. // Check routing if in multi-server mode
  918. var nodeid = req.query.nodeid;
  919. if (parent.parent.multiServer != null) {
  920. const routing = parent.parent.GetRoutingServerIdNotSelf(nodeid, 1); // 1 = MeshAgent routing type
  921. if (routing == null) {
  922. // No need to relay the connection to a different server
  923. return CreateMeshRelayEx2(parent, ws, req, domain, user, cookie);
  924. } else {
  925. // We must relay the connection to a different server
  926. return parent.parent.multiServer.createPeerRelay(ws, req, routing.serverid, req.session.userid);
  927. }
  928. } else {
  929. // No need to relay the connection to a different server
  930. return CreateMeshRelayEx2(parent, ws, req, domain, user, cookie);
  931. }
  932. }
  933. function CreateMeshRelayEx2(parent, ws, req, domain, user, cookie) {
  934. const currentTime = Date.now();
  935. var obj = {};
  936. obj.ws = ws;
  937. obj.ws.me = obj;
  938. obj.id = req.query.id;
  939. obj.nodeid = req.query.nodeid;
  940. obj.user = user;
  941. obj.ruserid = null;
  942. obj.req = req; // Used in multi-server.js
  943. obj.viewOnly = ((cookie != null) && (cookie.vo == 1)); // set view only mode
  944. if ((cookie != null) && (cookie.nouser == 1)) { obj.nouser = true; } // This is a relay without user authentication
  945. // If the domain has remote desktop viewonly set, force everyone to be in viewonly mode.
  946. if ((typeof domain.desktop == 'object') && (domain.desktop.viewonly == true)) { obj.viewOnly = true; }
  947. // Setup traffic accounting
  948. if (parent.trafficStats.desktopMultiplex == null) { parent.trafficStats.desktopMultiplex = { connections: 1, sessions: 0, in: 0, out: 0 }; } else { parent.trafficStats.desktopMultiplex.connections++; }
  949. ws._socket.bytesReadEx = 0;
  950. ws._socket.bytesWrittenEx = 0;
  951. // Setup subscription for desktop sharing public identifier
  952. // If the identifier is removed, drop the connection
  953. if ((cookie != null) && (typeof cookie.pid == 'string')) {
  954. obj.pid = cookie.pid;
  955. obj.guestName = cookie.gn;
  956. parent.parent.AddEventDispatch([obj.nodeid], obj);
  957. obj.HandleEvent = function (source, event, ids, id) { if ((event.action == 'removedDeviceShare') && (obj.pid == event.publicid)) { obj.close(); } }
  958. }
  959. // Check relay authentication
  960. if ((user == null) && (obj.req.query != null) && (obj.req.query.rauth != null)) {
  961. const rcookie = parent.parent.decodeCookie(obj.req.query.rauth, parent.parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
  962. if (rcookie.ruserid != null) { obj.ruserid = rcookie.ruserid; } else if (rcookie.nouser === 1) { obj.rnouser = true; }
  963. if (rcookie.nodeid != null) { obj.nodeid = rcookie.nodeid; }
  964. }
  965. // If there is no authentication, drop this connection
  966. if ((obj.id != null) && (obj.user == null) && (obj.ruserid == null) && (obj.nouser !== true) && (obj.rnouser !== true)) { try { ws.close(); parent.parent.debug('relay', 'DesktopRelay: Connection with no authentication (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } return; }
  967. // Relay session count (we may remove this in the future)
  968. obj.relaySessionCounted = true;
  969. parent.relaySessionCount++;
  970. // Mesh Rights
  971. const MESHRIGHT_EDITMESH = 1;
  972. const MESHRIGHT_MANAGEUSERS = 2;
  973. const MESHRIGHT_MANAGECOMPUTERS = 4;
  974. const MESHRIGHT_REMOTECONTROL = 8;
  975. const MESHRIGHT_AGENTCONSOLE = 16;
  976. const MESHRIGHT_SERVERFILES = 32;
  977. const MESHRIGHT_WAKEDEVICE = 64;
  978. const MESHRIGHT_SETNOTES = 128;
  979. const MESHRIGHT_REMOTEVIEW = 256;
  980. // Site rights
  981. const SITERIGHT_SERVERBACKUP = 1;
  982. const SITERIGHT_MANAGEUSERS = 2;
  983. const SITERIGHT_SERVERRESTORE = 4;
  984. const SITERIGHT_FILEACCESS = 8;
  985. const SITERIGHT_SERVERUPDATE = 16;
  986. const SITERIGHT_LOCKED = 32;
  987. // Clean a IPv6 address that encodes a IPv4 address
  988. function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
  989. // Disconnect this agent
  990. obj.close = function (arg) {
  991. if (obj.ws == null) return; // Already closed.
  992. // Close the connection
  993. if ((arg == 1) || (arg == null)) { try { ws.close(); parent.parent.debug('relay', 'DesktopRelay: Soft disconnect (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } } // Soft close, close the websocket
  994. if (arg == 2) { try { ws._socket._parent.end(); parent.parent.debug('relay', 'DesktopRelay: Hard disconnect (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
  995. if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
  996. if ((obj.deskMultiplexor != null) && (typeof obj.deskMultiplexor == 'object') && (obj.deskMultiplexor.removePeer(obj) == true)) { delete parent.desktoprelays[obj.nodeid]; }
  997. // Aggressive cleanup
  998. delete obj.id;
  999. delete obj.ws;
  1000. delete obj.req;
  1001. delete obj.user;
  1002. delete obj.nodeid;
  1003. delete obj.ruserid;
  1004. delete obj.expireTimer;
  1005. delete obj.deskMultiplexor;
  1006. // Clear timers if present
  1007. if (obj.pingtimer != null) { clearInterval(obj.pingtimer); delete obj.pingtimer; }
  1008. if (obj.pongtimer != null) { clearInterval(obj.pongtimer); delete obj.pongtimer; }
  1009. // Unsubscribe
  1010. if (obj.pid != null) { parent.parent.RemoveAllEventDispatch(obj); }
  1011. };
  1012. obj.sendAgentMessage = function (command, userid, domainid) {
  1013. var rights, mesh;
  1014. if (command.nodeid == null) return false;
  1015. var user = null;
  1016. if (userid != null) { user = parent.users[userid]; if (user == null) return false; }
  1017. var splitnodeid = command.nodeid.split('/');
  1018. // Check that we are in the same domain and the user has rights over this node.
  1019. if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domainid)) {
  1020. // Get the user object
  1021. // See if the node is connected
  1022. var agent = parent.wsagents[command.nodeid];
  1023. if (agent != null) {
  1024. // Check if we have permission to send a message to that node
  1025. if (userid == null) { rights = MESHRIGHT_REMOTECONTROL; } else { rights = parent.GetNodeRights(user, agent.dbMeshKey, agent.dbNodeKey); }
  1026. mesh = parent.meshes[agent.dbMeshKey];
  1027. if ((rights != null) && (mesh != null) || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
  1028. if (ws.sessionId) { command.sessionid = ws.sessionId; } // Set the session id, required for responses.
  1029. command.rights = rights; // Add user rights flags to the message
  1030. if ((command.rights != 0xFFFFFFFF) && ((command.rights & 0x100) != 0)) { command.rights -= 0x100; } // Since the multiplexor will enforce view-only, remove MESHRIGHT_REMOTEVIEWONLY
  1031. if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
  1032. if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
  1033. if (user != null) {
  1034. command.username = user.name; // Add user name
  1035. command.realname = user.realname; // Add real name
  1036. }
  1037. if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
  1038. delete command.nodeid; // Remove the nodeid since it's implyed.
  1039. agent.send(JSON.stringify(command));
  1040. return true;
  1041. }
  1042. } else {
  1043. // Check if a peer server is connected to this agent
  1044. var routing = parent.parent.GetRoutingServerIdNotSelf(command.nodeid, 1); // 1 = MeshAgent routing type
  1045. if (routing != null) {
  1046. // Check if we have permission to send a message to that node
  1047. if (userid == null) { rights = MESHRIGHT_REMOTECONTROL; } else { rights = parent.GetNodeRights(user, routing.meshid, command.nodeid); }
  1048. mesh = parent.meshes[routing.meshid];
  1049. if (rights != null || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
  1050. if (ws.sessionId) { command.fromSessionid = ws.sessionId; } // Set the session id, required for responses.
  1051. command.rights = rights; // Add user rights flags to the message
  1052. if ((command.rights != 0xFFFFFFFF) && ((command.rights & 0x00000100) != 0)) { command.rights -= 0x00000100; } // Since the multiplexor will enforce view-only, remove MESHRIGHT_REMOTEVIEWONLY
  1053. if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
  1054. if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
  1055. if (user != null) {
  1056. command.username = user.name; // Add user name
  1057. command.realname = user.realname; // Add real name
  1058. }
  1059. if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
  1060. parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
  1061. return true;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. return false;
  1067. };
  1068. // Send a PING/PONG message
  1069. function sendPing() {
  1070. try { obj.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } catch (ex) { }
  1071. try { if (obj.peer != null) { obj.peer.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } } catch (ex) { }
  1072. }
  1073. function sendPong() {
  1074. try { obj.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } catch (ex) { }
  1075. try { if (obj.peer != null) { obj.peer.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } } catch (ex) { }
  1076. }
  1077. function performRelay(retryCount) {
  1078. if ((obj.id == null) || (retryCount > 20)) { try { obj.close(); } catch (e) { } return null; } // Attempt to connect without id, drop this.
  1079. if (retryCount == 0) { ws._socket.setKeepAlive(true, 240000); } // Set TCP keep alive
  1080. /*
  1081. // Validate that the id is valid, we only need to do this on non-authenticated sessions.
  1082. // TODO: Figure out when this needs to be done.
  1083. if (user == null) {
  1084. // Check the identifier, if running without TLS, skip this.
  1085. var ids = obj.id.split(':');
  1086. if (ids.length != 3) { ws.close(); delete obj.id; return null; } // Invalid ID, drop this.
  1087. if (parent.crypto.createHmac('SHA384', parent.relayRandom).update(ids[0] + ':' + ids[1]).digest('hex') != ids[2]) { ws.close(); delete obj.id; return null; } // Invalid HMAC, drop this.
  1088. if ((Date.now() - parseInt(ids[1])) > 120000) { ws.close(); delete obj.id; return null; } // Expired time, drop this.
  1089. obj.id = ids[0];
  1090. }
  1091. */
  1092. if (retryCount == 0) {
  1093. // Setup the agent PING/PONG timers
  1094. if ((typeof parent.parent.args.agentping == 'number') && (obj.pingtimer == null)) { obj.pingtimer = setInterval(sendPing, parent.parent.args.agentping * 1000); }
  1095. else if ((typeof parent.parent.args.agentpong == 'number') && (obj.pongtimer == null)) { obj.pongtimer = setInterval(sendPong, parent.parent.args.agentpong * 1000); }
  1096. parent.parent.debug('relay', 'DesktopRelay: Connection (' + obj.req.clientIp + ')');
  1097. }
  1098. // Create if needed and add this peer to the desktop multiplexor
  1099. obj.deskMultiplexor = parent.desktoprelays[obj.nodeid];
  1100. if (obj.deskMultiplexor == null) {
  1101. parent.desktoprelays[obj.nodeid] = 1; // Indicate that the creating of the desktop multiplexor is pending.
  1102. parent.parent.debug('relay', 'DesktopRelay: Creating new desktop multiplexor');
  1103. CreateDesktopMultiplexor(parent, domain, obj.nodeid, obj.id, function (deskMultiplexor) {
  1104. if (deskMultiplexor != null) {
  1105. // Desktop multiplexor was created, use it.
  1106. obj.deskMultiplexor = deskMultiplexor;
  1107. parent.desktoprelays[obj.nodeid] = obj.deskMultiplexor;
  1108. obj.deskMultiplexor.addPeer(obj);
  1109. ws._socket.resume(); // Release the traffic
  1110. } else {
  1111. // An error has occured, close this connection
  1112. delete parent.desktoprelays[obj.nodeid];
  1113. ws.close();
  1114. }
  1115. });
  1116. } else {
  1117. if (obj.deskMultiplexor == 1) {
  1118. // The multiplexor is being created, hold a little and try again. This is to prevent a possible race condition.
  1119. setTimeout(function () { performRelay(++retryCount); }, 50);
  1120. } else {
  1121. // Hook up this peer to the multiplexor and release the traffic
  1122. obj.deskMultiplexor.addPeer(obj);
  1123. ws._socket.resume();
  1124. }
  1125. }
  1126. }
  1127. // When data is received from the mesh relay web socket
  1128. ws.on('message', function (data) {
  1129. // Data accounting
  1130. parent.trafficStats.desktopMultiplex.in += (this._socket.bytesRead - this._socket.bytesReadEx);
  1131. parent.trafficStats.desktopMultiplex.out += (this._socket.bytesWritten - this._socket.bytesWrittenEx);
  1132. this._socket.bytesReadEx = this._socket.bytesRead;
  1133. this._socket.bytesWrittenEx = this._socket.bytesWritten;
  1134. // If this data was received by the agent, decode it.
  1135. if (this.me.deskMultiplexor != null) { this.me.deskMultiplexor.processData(this.me, data); }
  1136. });
  1137. // If error, close both sides of the relay.
  1138. ws.on('error', function (err) {
  1139. //console.log('ws-error', err);
  1140. parent.relaySessionErrorCount++;
  1141. console.log('Relay error from ' + obj.req.clientIp + ', ' + err.toString().split('\r')[0] + '.');
  1142. obj.close();
  1143. });
  1144. // If the relay web socket is closed, close both sides.
  1145. ws.on('close', function (req) {
  1146. // Data accounting
  1147. parent.trafficStats.desktopMultiplex.in += (this._socket.bytesRead - this._socket.bytesReadEx);
  1148. parent.trafficStats.desktopMultiplex.out += (this._socket.bytesWritten - this._socket.bytesWrittenEx);
  1149. this._socket.bytesReadEx = this._socket.bytesRead;
  1150. this._socket.bytesWrittenEx = this._socket.bytesWritten;
  1151. //console.log('ws-close', req);
  1152. obj.close();
  1153. });
  1154. // If this session has a expire time, setup the expire timer now.
  1155. setExpireTimer();
  1156. // Mark this relay session as authenticated if this is the user end.
  1157. obj.authenticated = ((user != null) || (obj.nouser === true));
  1158. if (obj.authenticated) {
  1159. // Kick off the routing, if we have agent routing instructions, process them here.
  1160. // Routing instructions can only be given by a authenticated user
  1161. if ((cookie != null) && (cookie.nodeid != null) && (cookie.tcpport != null) && (cookie.domainid != null)) {
  1162. // We have routing instructions in the cookie, but first, check user access for this node.
  1163. parent.db.Get(cookie.nodeid, function (err, docs) {
  1164. if (obj.req == null) return; // This connection was closed.
  1165. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  1166. const node = docs[0];
  1167. // Check if this user has permission to manage this computer
  1168. if ((obj.nouser !== true) && ((parent.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0)) { console.log('ERR: Access denied (1)'); try { obj.close(); } catch (e) { } return; }
  1169. // Send connection request to agent
  1170. const rcookieData = { nodeid: node._id };
  1171. if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
  1172. const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
  1173. if (obj.id == undefined) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
  1174. const command = { nodeid: node._id, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr };
  1175. parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
  1176. if (obj.sendAgentMessage(command, user ? user._id : null, cookie.domainid) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  1177. performRelay(0);
  1178. });
  1179. return obj;
  1180. } else if ((obj.req.query.nodeid != null) && ((obj.req.query.tcpport != null) || (obj.req.query.udpport != null))) {
  1181. // We have routing instructions in the URL arguments, but first, check user access for this node.
  1182. parent.db.Get(obj.req.query.nodeid, function (err, docs) {
  1183. if (obj.req == null) return; // This connection was closed.
  1184. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  1185. const node = docs[0];
  1186. // Check if this user has permission to manage this computer
  1187. if ((obj.nouser !== true) && ((parent.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0)) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (e) { } return; }
  1188. // Send connection request to agent
  1189. if (obj.id == null) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
  1190. const rcookieData = { nodeid: node._id };
  1191. if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
  1192. const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
  1193. if (obj.req.query.tcpport != null) {
  1194. const command = { nodeid: node._id, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: obj.req.query.tcpport, tcpaddr: ((obj.req.query.tcpaddr == null) ? '127.0.0.1' : obj.req.query.tcpaddr) };
  1195. parent.parent.debug('relay', 'Relay: Sending agent TCP tunnel command: ' + JSON.stringify(command));
  1196. if (obj.sendAgentMessage(command, user ? user._id : null, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  1197. } else if (obj.req.query.udpport != null) {
  1198. const command = { nodeid: node._id, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, udpport: obj.req.query.udpport, udpaddr: ((obj.req.query.udpaddr == null) ? '127.0.0.1' : obj.req.query.udpaddr) };
  1199. parent.parent.debug('relay', 'Relay: Sending agent UDP tunnel command: ' + JSON.stringify(command));
  1200. if (obj.sendAgentMessage(command, user ? user._id : null, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  1201. }
  1202. performRelay(0);
  1203. });
  1204. return obj;
  1205. } else if ((cookie != null) && (cookie.nid != null) && (typeof cookie.r == 'number') && (typeof cookie.cf == 'number') && (typeof cookie.gn == 'string')) {
  1206. // We have routing instructions in the cookie, but first, check user access for this node.
  1207. parent.db.Get(cookie.nid, function (err, docs) {
  1208. if (obj.req == null) return; // This connection was closed.
  1209. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  1210. const node = docs[0];
  1211. // Check if this user has permission to manage this computer
  1212. if ((obj.nouser !== true) && ((parent.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0)) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (e) { } return; }
  1213. // Send connection request to agent
  1214. if (obj.id == null) { obj.id = ('' + Math.random()).substring(2); }
  1215. const rcookieData = { nodeid: node._id };
  1216. if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
  1217. const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
  1218. const command = { nodeid: node._id, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?p=2&id=' + obj.id + '&rauth=' + rcookie + '&nodeid=' + node._id, soptions: {}, usage: 2, rights: cookie.r, guestuserid: user._id, guestname: cookie.gn, consent: cookie.cf, remoteaddr: cleanRemoteAddr(obj.req.clientIp) };
  1219. if (typeof domain.consentmessages == 'object') {
  1220. if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
  1221. if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
  1222. if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
  1223. if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
  1224. if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
  1225. if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
  1226. if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
  1227. }
  1228. if (typeof domain.notificationmessages == 'object') {
  1229. if (typeof domain.notificationmessages.title == 'string') { command.soptions.notifyTitle = domain.notificationmessages.title; }
  1230. if (typeof domain.notificationmessages.desktop == 'string') { command.soptions.notifyMsgDesktop = domain.notificationmessages.desktop; }
  1231. if (typeof domain.notificationmessages.terminal == 'string') { command.soptions.notifyMsgTerminal = domain.notificationmessages.terminal; }
  1232. if (typeof domain.notificationmessages.files == 'string') { command.soptions.notifyMsgFiles = domain.notificationmessages.files; }
  1233. }
  1234. parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
  1235. if (obj.sendAgentMessage(command, user ? user._id : null, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  1236. performRelay(0);
  1237. });
  1238. return obj;
  1239. }
  1240. }
  1241. // Set the session expire timer
  1242. function setExpireTimer() {
  1243. if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; }
  1244. if (cookie && (typeof cookie.expire == 'number')) {
  1245. const timeToExpire = (cookie.expire - Date.now());
  1246. if (timeToExpire < 1) {
  1247. obj.close();
  1248. } else if (timeToExpire >= 0x7FFFFFFF) {
  1249. obj.expireTimer = setTimeout(setExpireTimer, 0x7FFFFFFF); // Since expire timer can't be larger than 0x7FFFFFFF, reset timer after that time.
  1250. } else {
  1251. obj.expireTimer = setTimeout(obj.close, timeToExpire);
  1252. }
  1253. }
  1254. }
  1255. // Check if this user has input access on the device
  1256. if ((obj.user != null) && (obj.viewOnly == false)) {
  1257. obj.viewOnly = true; // Set a view only for now until we figure out otherwise
  1258. parent.db.Get(obj.nodeid, function (err, docs) {
  1259. if (obj.req == null) return; // This connection was closed.
  1260. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  1261. const node = docs[0];
  1262. // Check if this user has permission to manage this computer
  1263. const rights = parent.GetNodeRights(obj.user, node.meshid, node._id);
  1264. if ((rights & 0x00000008) == 0) { try { obj.close(); } catch (e) { } return; } // Check MESHRIGHT_ADMIN or MESHRIGHT_REMOTECONTROL
  1265. if ((rights != 0xFFFFFFFF) && ((rights & 0x00010000) != 0)) { try { obj.close(); } catch (e) { } return; } // Check MESHRIGHT_NODESKTOP
  1266. if ((rights == 0xFFFFFFFF) || ((rights & 0x00000100) == 0)) { obj.viewOnly = false; } // Check MESHRIGHT_REMOTEVIEWONLY
  1267. performRelay(0);
  1268. });
  1269. } else {
  1270. // If this is not an authenticated session, or the session does not have routing instructions, just go ahead an connect to existing session.
  1271. performRelay(0);
  1272. }
  1273. return obj;
  1274. };
  1275. /*
  1276. Relay session recording required that "SessionRecording":true be set in the domain section of the config.json.
  1277. Once done, a folder "meshcentral-recordings" will be created next to "meshcentral-data" that will contain all
  1278. of the recording files with the .mcrec extension.
  1279. The recording files are binary and contain a set of:
  1280. <HEADER><DATABLOCK><HEADER><DATABLOCK><HEADER><DATABLOCK><HEADER><DATABLOCK>...
  1281. The header is always 16 bytes long and is encoded like this:
  1282. TYPE 2 bytes, 1 = Header, 2 = Network Data, 3 = EndBlock
  1283. FLAGS 2 bytes, 0x0001 = Binary, 0x0002 = User
  1284. SIZE 4 bytes, Size of the data following this header.
  1285. TIME 8 bytes, Time this record was written, number of milliseconds since 1 January, 1970 UTC.
  1286. All values are BigEndian encoded. The first data block is of TYPE 1 and contains a JSON string with information
  1287. about this recording. It looks something like this:
  1288. {
  1289. magic: 'MeshCentralRelaySession',
  1290. ver: 1,
  1291. userid: "user\domain\userid",
  1292. username: "username",
  1293. sessionid: "RandomValue",
  1294. ipaddr1: 1.2.3.4,
  1295. ipaddr2: 1.2.3.5,
  1296. time: new Date().toLocaleString()
  1297. }
  1298. The rest of the data blocks are all network traffic that was relayed thru the server. They are of TYPE 2 and have
  1299. a given size and timestamp. When looking at network traffic the flags are important:
  1300. - If traffic has the first (0x0001) flag set, the data is binary otherwise it's a string.
  1301. - If the traffic has the second (0x0002) flag set, traffic is coming from the user's browser, if not, it's coming from the MeshAgent.
  1302. */