2* @description MeshCentral remote desktop multiplexor
3* @author Ylian Saint-Hilaire
4* @copyright Intel Corporation 2018-2022
11/*jshint strict:false */
13/*jshint esversion: 6 */
22MNG_KVM_MOUSE_CURSOR = 88,
23MNG_KVM_MOUSE_MOVE = 89,
26MNG_KVM_COMPRESSION = 5,
32MNG_KVM_GET_DISPLAYS = 11,
33MNG_KVM_SET_DISPLAY = 12,
34MNG_KVM_FRAME_RATE_TIMER = 13,
35MNG_KVM_INIT_TOUCH = 14,
37MNG_KVM_CONNECTCOUNT = 16,
46MNG_FILECREATEDIR = 54,
50MNG_FILETRANSFER2 = 58,
51MNG_KVM_DISCONNECT = 59,
52MNG_GETDIR2 = 60, // Same as MNG_GETDIR but with date/time.
53MNG_FILEUPLOAD2 = 61, // Used for slot based fast upload.
54MNG_FILEDELETEREC = 62, // Same as MNG_FILEDELETE but recursive
55MNG_USERCONSENT = 63, // Used to notify management console of user consent state
56MNG_DEBUG = 64, // Debug/Logging Message for ILibRemoteLogging
58MNG_ENCAPSULATE_AGENT_COMMAND = 70,
59MNG_KVM_DISPLAY_INFO = 82
62function CreateDesktopMultiplexor(parent, domain, nodeid, id, func) {
64 obj.id = id; // Unique identifier for this session
65 obj.nodeid = nodeid; // Remote device nodeid for this session
66 obj.parent = parent; // Parent web server instance
67 obj.agent = null; // Reference to the connection object that is the agent.
68 obj.viewers = []; // Array of references to all viewers.
69 obj.viewersOverflowCount = 0; // Number of viewers currently in overflow state.
70 obj.width = 0; // Current width of the display in pixels.
71 obj.height = 0; // Current height of the display in pixels.
72 obj.swidth = 0; // Current width of the display in tiles.
73 obj.sheight = 0; // Current height of the display in tiles.
74 obj.screen = null; // The main screen, (x * y) --> tile index. Indicates this image is covering each tile on the screen.
75 obj.counter = 1; // The main counter, used as index for the obj.images table when now images come in.
76 obj.imagesCount = 0; // Total number of images in the obj.images table.
77 obj.imagesCounters = {}; // Main table of indexes --> tile count, the number of tiles still using this image.
78 obj.images = {}; // Main table of indexes --> image data object.
79 obj.lastScreenSizeCmd = null; // Pointer to the last screen size command from the agent.
80 obj.lastScreenSizeCounter = 0; // Index into the image table of the screen size command, this is generally also the first command.
81 obj.lastConsoleMessage = null; // Last agent console message.
82 obj.firstData = null; // Index in the image table of the first image in the table, generally this points to the display resolution command.
83 obj.lastData = null; // Index in the images table of the last image in the table.
84 obj.lastDisplayInfoData = null; // Pointer to the last display information command from the agent (Number of displays).
85 obj.lastDisplayLocationData = null; // Pointer to the last display location and size command from the agent.
86 obj.lastKeyState = null; // Pointer to the last key state command from the agent.
87 obj.desktopPaused = true; // Current desktop pause state, it's true if all viewers are paused.
88 obj.imageType = 1; // Current image type, 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = WebP
89 obj.imageCompression = 50; // Current image compression, this is the highest value of all viewers.
90 obj.imageScaling = 1024; // Current image scaling, this is the highest value of all viewers.
91 obj.imageFrameRate = 50; // Current framerate setting, this is the lowest values of all viewers.
92 obj.protocolOptions = null; // Set to the protocol options of the first viewer that connected.
93 obj.viewerConnected = false; // Set to true if one viewer attempted to connect to the agent.
94 obj.recordingFile = null; // Present if we are recording to file.
95 obj.recordingFileSize = 0; // Current size of the recording file.
96 obj.recordingFileWriting = false; // Set to true is we are in the process if writing to the recording file.
97 obj.startTime = null; // Starting time of the multiplex session.
98 obj.userIds = []; // List of userid's that have intertracted with this session.
99 //obj.autoLock = false; // Automatically lock the remote device once disconnected
101 // Accounting - Initialize trafficStats.desktopMultiplex if it doesn't exist
102 if (parent.trafficStats.desktopMultiplex == null) {
103 parent.trafficStats.desktopMultiplex = { connections: 0, sessions: 1, in: 0, out: 0 };
105 parent.trafficStats.desktopMultiplex.sessions++;
108 // Add an agent or viewer
109 obj.addPeer = function (peer) {
110 if (obj.viewers == null) { parent.parent.debug('relay', 'DesktopRelay: Error, addingPeer on disposed session'); return; }
111 if (peer.req == null) return; // This peer is already disposed, don't add it.
112 if (peer.req.query.browser) {
113 //console.log('addPeer-viewer', obj.nodeid);
116 if (obj.viewers.indexOf(peer) >= 0) return true;
117 obj.viewers.push(peer);
118 peer.desktopPaused = true;
120 peer.imageCompression = 30;
121 peer.imageScaling = 1024;
122 peer.imageFrameRate = 100;
123 peer.lastImageNumberSent = null;
124 peer.dataPtr = obj.firstData;
125 peer.sending = false;
126 peer.overflow = false;
129 peer.startTime = Date.now();
131 // Add the user to the userids list if needed
132 if ((peer.user != null) && (obj.userIds.indexOf(peer.user._id) == -1)) { obj.userIds.push(peer.user._id); }
134 // Setup slow relay is requested. This will show down sending any data to this viewer.
135 if ((peer.req.query.slowrelay != null)) {
137 try { sr = parseInt(peer.req.query.slowrelay); } catch (ex) { }
138 if ((typeof sr == 'number') && (sr > 0) && (sr < 1000)) { peer.slowRelay = sr; }
141 // Update user last access time
142 if ((peer.user != null) && (peer.guestName == null)) {
143 const user = parent.users[peer.user._id];
145 const timeNow = Math.floor(Date.now() / 1000);
146 if (user.access < (timeNow - 300)) { // Only update user access time if longer than 5 minutes
147 user.access = timeNow;
148 parent.db.SetUser(user);
151 var message = { etype: 'user', userid: user._id, username: user.name, account: parent.CloneSafeUser(user), action: 'accountchange', domain: domain.id, nolog: 1 };
152 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.
153 var targets = ['*', 'server-users', user._id];
154 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
155 parent.parent.DispatchEvent(targets, obj, message);
160 // Check session recording
161 var startRecord = false;
162 if (typeof domain.sessionrecording == 'object') {
163 // Check if this user is set to record all sessions
164 if ((domain.sessionrecording.onlyselectedusers === true) && (peer.user != null) && (peer.user.flags != null) && ((peer.user.flags & 2) != 0)) { startRecord = true; }
165 else if (domain.sessionrecording.onlyselectedusergroups === true) {
166 // Check if there is a usergroup that requires recording of the session
168 if (peer.user != null) { user = parent.users[peer.user._id]; }
169 if ((user != null) && (user.links != null) && (user.links[obj.meshid] == null) && (user.links[obj.nodeid] == null)) {
170 // This user does not have a direct link to the device group or device. Find all user groups the would cause the link.
171 for (var i in user.links) {
172 var ugrp = parent.userGroups[i];
173 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; }
179 startRecording(domain, startRecord, function () {
180 // Indicated we are connected
181 obj.sendToViewer(peer, obj.recordingFile ? 'cr' : 'c');
183 // If the agent sent display information or console message, send it to the viewer
184 if (obj.lastDisplayInfoData != null) { obj.sendToViewer(peer, obj.lastDisplayInfoData); }
185 if (obj.lastDisplayLocationData != null) { obj.sendToViewer(peer, obj.lastDisplayLocationData); }
186 if (obj.lastConsoleMessage != null) { obj.sendToViewer(peer, obj.lastConsoleMessage); }
187 if (obj.lastKeyState != null) { obj.sendToViewer(peer, obj.lastKeyState); }
189 // Log joining the multiplex session
190 if (obj.startTime != null) {
191 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 };
192 parent.parent.DispatchEvent(['*', obj.nodeid, peer.user._id, obj.meshid], obj, event);
195 // Send an updated list of all peers to all viewers
196 obj.sendSessionMetadata();
199 //console.log('addPeer-agent', obj.nodeid);
200 if (obj.agent != null) { parent.parent.debug('relay', 'DesktopRelay: Error, duplicate agent connection'); return false; }
204 peer.sending = false;
205 peer.overflow = false;
209 // Indicated we are connected and send connection options and protocol if needed
210 obj.sendToAgent(obj.recordingFile?'cr':'c');
211 if (obj.viewerConnected == true) {
212 if (obj.protocolOptions != null) { obj.sendToAgent(JSON.stringify(obj.protocolOptions)); } // Send connection options
213 obj.sendToAgent('2'); // Send remote desktop connect
217 // Log multiplex session start
218 if ((obj.agent != null) && (obj.viewers.length > 0) && (obj.startTime == null)) {
219 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 };
220 if (obj.viewers[0].user != null) { event.userid = obj.viewers[0].user._id; event.username = obj.viewers[0].user.name; }
221 const targets = ['*', obj.nodeid, obj.meshid];
222 if (obj.viewers[0].user != null) { targets.push(obj.viewers[0].user._id); }
223 parent.parent.DispatchEvent(targets, obj, event);
224 obj.startTime = Date.now();
229 // Remove an agent or viewer
230 // Return true if this multiplexor is no longer needed.
231 obj.removePeer = function (peer) {
232 if (obj.viewers == null) return;
233 if (peer == obj.agent) {
234 //console.log('removePeer-agent', obj.nodeid);
235 // Agent has disconnected, disconnect everyone.
236 if (obj.viewers != null) { for (var i in obj.viewers) { obj.viewers[i].close(); } }
238 // Clean up the agent
244 //console.log('removePeer-viewer', obj.nodeid);
246 if (obj.viewers != null) {
247 var i = obj.viewers.indexOf(peer);
248 if (i == -1) return false;
249 obj.viewers.splice(i, 1);
252 // Resume flow control if this was the peer that was limiting traffic (because it was the fastest one).
253 if (peer.overflow == true) {
254 obj.viewersOverflowCount--;
255 peer.overflow = false;
256 if ((obj.viewersOverflowCount < obj.viewers.length) && (obj.recordingFileWriting == false) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
259 // Log leaving the multiplex session
260 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.
261 // 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.
262 // 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.
264 // Compute traffic to and from the browser
265 var inTraffc, outTraffc;
266 try { inTraffc = peer.ws._socket.bytesRead; } catch (ex) { }
267 try { outTraffc = peer.ws._socket.bytesWritten; } catch (ex) { }
269 // Add any previous agent traffic accounting
270 if (peer.agentInTraffic) { inTraffc += peer.agentInTraffic; }
271 if (peer.outTraffc) { inTraffc += peer.agentOutTraffic; }
273 // Compute traffic to and from the agent
274 if (obj.agent != null) {
275 // Get unaccounted bytes from/to the agent
276 var agentInTraffc, agentOutTraffc, agentInTraffc2, agentOutTraffc2;
277 try { agentInTraffc = agentInTraffc2 = obj.agent.ws._socket.bytesRead; } catch (ex) { }
278 try { agentOutTraffc = agentOutTraffc2 = obj.agent.ws._socket.bytesWritten; } catch (ex) { }
279 if (obj.agent.accountedBytesRead) { agentInTraffc -= obj.agent.accountedBytesRead; }
280 if (obj.agent.accountedBytesWritten) { agentOutTraffc -= obj.agent.accountedBytesWritten; }
281 obj.agent.accountedBytesRead = agentInTraffc2;
282 obj.agent.accountedBytesWritten = agentOutTraffc2;
284 // Devide up the agent traffic amoung the viewers
285 var viewerPartIn = Math.floor(agentInTraffc / (obj.viewers.length + 1));
286 var viewerPartOut = Math.floor(agentOutTraffc / (obj.viewers.length + 1));
288 // Add the portion to this viewer and all other viewer
289 inTraffc += viewerPartIn;
290 outTraffc += viewerPartOut;
291 for (var i in obj.viewers) {
292 if (obj.viewers[i].agentInTraffic) { obj.viewers[i].agentInTraffic += viewerPartIn; } else { obj.viewers[i].agentInTraffic = viewerPartIn; }
293 if (obj.viewers[i].agentOutTraffic) { obj.viewers[i].agentOutTraffic += viewerPartOut; } else { obj.viewers[i].agentOutTraffic = viewerPartOut; }
297 //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 };
298 const sessionSeconds = Math.floor((Date.now() - peer.startTime) / 1000);
299 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 };
300 if (peer.user != null) { event.userid = peer.user._id; event.username = peer.user.name; }
301 if (peer.guestName) { event.guestname = peer.guestName; }
302 const targets = ['*', obj.nodeid, obj.meshid];
303 if (peer.user != null) { targets.push(peer.user._id); }
304 parent.parent.DispatchEvent(targets, obj, event);
307 // Aggressive clean up of the viewer
308 delete peer.desktopPaused;
309 delete peer.imageType;
310 delete peer.imageCompression;
311 delete peer.imageScaling;
312 delete peer.imageFrameRate;
313 delete peer.lastImageNumberSent;
316 delete peer.overflow;
317 delete peer.sendQueue;
318 delete peer.startTime;
320 // If this is the last viewer, disconnect the agent
321 if ((obj.viewers != null) && (obj.viewers.length == 0) && (obj.agent != null)) { obj.agent.close(); dispose(); return true; }
323 // Send an updated list of all peers to all viewers
324 obj.sendSessionMetadata();
329 // Clean up ourselves
331 if (obj.viewers == null) return;
332 //console.log('dispose', obj.nodeid);
334 delete obj.imagesCounters;
337 // Close the recording file if needed
338 if (obj.recordingFile != null) {
339 // Compute session length
340 if (obj.startTime != null) { obj.sessionStart = obj.startTime; obj.sessionLength = Math.round((Date.now() - obj.startTime) / 1000); }
342 // Write the last record of the recording file
343 var rf = obj.recordingFile;
344 delete obj.recordingFile;
345 recordingEntry(rf.fd, 3, 0, 'MeshCentralMCREC', function (fd, filename) {
346 parent.parent.fs.close(fd);
348 // Now that the recording file is closed, check if we need to index this file.
349 if (domain.sessionrecording.index && domain.sessionrecording.index !== false) { parent.parent.certificateOperations.acceleratorPerformOperation('indexMcRec', filename); }
351 // Add a event entry about this recording
352 var basefile = parent.parent.path.basename(filename);
353 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 };
354 var mesh = parent.meshes[obj.meshid];
355 if (mesh != null) { event.meshname = mesh.name; }
356 if (obj.sessionStart) { event.startTime = obj.sessionStart; event.lengthTime = obj.sessionLength; }
357 parent.parent.DispatchEvent(['*', 'recording', obj.nodeid, obj.meshid], obj, event);
363 // Log end of multiplex session
364 if (obj.startTime != null) {
365 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 };
366 parent.parent.DispatchEvent(['*', obj.nodeid, obj.meshid], obj, event);
367 obj.startTime = null;
370 // Send an updated list of all peers to all viewers
371 obj.sendSessionMetadata();
373 parent.parent.debug('relay', 'DesktopRelay: Disposing desktop multiplexor');
376 // Send data to the agent or queue it up for sending
377 obj.sendToAgent = function (data) {
378 if ((obj.viewers == null) || (obj.agent == null)) return;
379 //console.log('SendToAgent', data.length);
380 if (obj.agent.sending) {
381 obj.agent.sendQueue.push(data);
383 // Flow control, pause all viewers is the queue is backing up
384 if (obj.agent.sendQueue > 10) {
385 obj.agent.overflow = true;
386 for (var i in obj.viewers) {
387 var v = obj.viewers[i];
388 if (v.paused == false) { v.paused = true; v.ws._socket.pause(); }
392 obj.agent.ws.send(data, sendAgentNext);
396 // Send more data to the agent
397 function sendAgentNext() {
398 if ((obj.viewers == null) || (obj.agent == null)) return;
399 if (obj.agent.sendQueue.length > 0) {
400 // Send from the pending send queue
401 obj.agent.ws.send(obj.agent.sendQueue.shift(), sendAgentNext);
404 obj.agent.sending = false;
406 // Flow control, resume all viewers
407 if (obj.agent.overflow == true) {
408 obj.agent.overflow = false;
409 for (var i in obj.viewers) {
410 var v = obj.viewers[i];
411 if (v.paused == true) { v.paused = false; v.ws._socket.resume(); }
417 // Send the list of all users currently vieweing this session to all viewers and servers
418 obj.sendSessionMetadata = function () {
420 if (obj.viewers != null) {
421 for (var i in obj.viewers) {
422 var v = obj.viewers[i];
423 if ((v.user != null) && (v.user._id != null)) {
425 if (v.guestName) { id += '/guest:' + Buffer.from(v.guestName).toString('base64'); } // If this is a guest connect, add the Base64 guest name.
426 if (allUsers[id] == null) { allUsers[id] = 1; } else { allUsers[id]++; }
429 obj.sendToAllViewers(JSON.stringify({ type: 'metadata', 'ctrlChannel': '102938', users: allUsers, startTime: obj.startTime }));
432 // Update the sessions attached the to agent
433 if (obj.nodeid != null) {
434 const xagent = parent.wsagents[obj.nodeid];
435 if (xagent != null) {
436 if (xagent.sessions == null) { xagent.sessions = {}; }
437 xagent.sessions.multidesk = allUsers;
438 xagent.updateSessions();
443 // Send this command to all viewers
444 obj.sendToAllViewers = function (data) {
445 if (obj.viewers == null) return;
446 for (var i in obj.viewers) { obj.sendToViewer(obj.viewers[i], data); }
449 // Send this command to all viewers
450 obj.sendToAllInputViewers = function (data) {
451 if (obj.viewers == null) return;
452 for (var i in obj.viewers) { if (obj.viewers[i].viewOnly != true) { obj.sendToViewer(obj.viewers[i], data); } }
455 // Send data to the viewer or queue it up for sending
456 obj.sendToViewer = function (viewer, data) {
457 if ((viewer == null) || (obj.viewers == null)) return;
458 //console.log('SendToViewer', data.length);
459 if (viewer.sending) {
460 viewer.sendQueue.push(data);
462 viewer.sending = true;
463 if (viewer.slowRelay) {
464 setTimeout(function () { try { viewer.ws.send(data, function () { sendViewerNext(viewer); }); } catch (ex) { } }, viewer.slowRelay);
466 try { viewer.ws.send(data, function () { sendViewerNext(viewer); }); } catch (ex) { }
469 // Flow control, pause the agent if needed
470 checkViewerOverflow(viewer);
474 // Check if a viewer is in overflow situation
475 function checkViewerOverflow(viewer) {
476 if ((viewer.overflow == true) || (obj.viewers == null)) return;
477 if ((viewer.sendQueue.length > 5) || ((viewer.dataPtr != null) && (viewer.dataPtr != obj.lastData))) {
478 viewer.overflow = true;
479 obj.viewersOverflowCount++;
480 if ((obj.viewersOverflowCount >= obj.viewers.length) && obj.agent && (obj.agent.paused == false)) { obj.agent.paused = true; obj.agent.ws._socket.pause(); }
484 // Check if a viewer is in underflow situation
485 function checkViewerUnderflow(viewer) {
486 if ((viewer.overflow == false) || (obj.viewers == null)) return;
487 if ((viewer.sendQueue.length <= 5) && ((viewer.dataPtr == null) || (viewer.dataPtr == obj.lastData))) {
488 viewer.overflow = false;
489 obj.viewersOverflowCount--;
490 if ((obj.viewersOverflowCount < obj.viewers.length) && (obj.recordingFileWriting == false) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
494 // Send more data to the viewer
495 function sendViewerNext(viewer) {
496 if ((viewer.sendQueue == null) || (obj.viewers == null)) return;
497 if (viewer.sendQueue.length > 0) {
498 // Send from the pending send queue
499 if (viewer.sending == false) { viewer.sending = true; }
500 if (viewer.slowRelay) {
501 setTimeout(function () { try { viewer.ws.send(viewer.sendQueue.shift(), function () { sendViewerNext(viewer); }); } catch (ex) { } }, viewer.slowRelay);
503 try { viewer.ws.send(viewer.sendQueue.shift(), function () { sendViewerNext(viewer); }); } catch (ex) { }
505 checkViewerOverflow(viewer);
507 if (viewer.dataPtr != null) {
508 // Send the next image
509 //if ((viewer.lastImageNumberSent != null) && ((viewer.lastImageNumberSent + 1) != (viewer.dataPtr))) { console.log('SVIEW-S1', viewer.lastImageNumberSent, viewer.dataPtr); } // DEBUG
510 var image = obj.images[viewer.dataPtr];
511 viewer.lastImageNumberSent = viewer.dataPtr;
512 //if ((image.next != null) && ((viewer.dataPtr + 1) != image.next)) { console.log('SVIEW-S2', viewer.dataPtr, image.next); } // DEBUG
513 viewer.dataPtr = image.next;
514 if (viewer.slowRelay) {
515 setTimeout(function () { try { viewer.ws.send(image.data, function () { sendViewerNext(viewer); }); } catch (ex) { } }, viewer.slowRelay);
517 try { viewer.ws.send(image.data, function () { sendViewerNext(viewer); }); } catch (ex) { }
520 // Flow control, pause the agent if needed
521 if (viewer.sending == false) { viewer.sending = true; }
522 checkViewerOverflow(viewer);
525 viewer.sending = false;
527 // Flow control, resume agent if needed
528 checkViewerUnderflow(viewer);
533 // Process data coming from the agent or any viewers
534 obj.processData = function (peer, data) {
535 if (obj.viewers == null) return;
536 if (peer == obj.agent) {
537 obj.recordingFileWriting = true;
538 recordData(true, data, function () {
539 if (obj.viewers == null) return;
540 obj.recordingFileWriting = false;
541 if ((obj.viewersOverflowCount < obj.viewers.length) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
542 obj.processAgentData(data);
545 obj.processViewerData(peer, data);
549 // Process incoming viewer data
550 obj.processViewerData = function (viewer, data) {
551 if (typeof data == 'string') {
553 if (obj.viewerConnected == false) {
554 if (obj.agent != null) {
555 if (obj.protocolOptions != null) { obj.sendToAgent(JSON.stringify(obj.protocolOptions)); } // Send connection options
556 obj.sendToAgent('2'); // Send remote desktop connect
558 obj.viewerConnected = true;
563 try { json = JSON.parse(data); } catch (ex) { }
564 if (json == null) return;
565 if ((json.type == 'options') && (obj.protocolOptions == null)) { obj.protocolOptions = json; }
566 if (json.ctrlChannel == '102938') {
567 if ((json.type == 'lock') && (viewer.viewOnly == false)) { obj.sendToAgent('{"ctrlChannel":"102938","type":"lock"}'); } // Account lock support
568 if ((json.type == 'autolock') && (viewer.viewOnly == false) && (typeof json.value == 'boolean')) { obj.sendToAgent('{"ctrlChannel":"102938","type":"autolock","value":' + json.value + '}'); } // Lock on disconnect
573 //console.log('ViewerData', data.length, typeof data, data);
574 if ((typeof data != 'object') || (data.length < 4)) return; // Ignore all control traffic for now (WebRTC)
575 var command = data.readUInt16BE(0);
576 var cmdsize = data.readUInt16BE(2);
577 if (data.length != cmdsize) return; // Invalid command length
579 //console.log('ViewerData', data.length, command, cmdsize);
581 case 1: // Key Events, forward to agent
582 if (viewer.viewOnly == false) { obj.sendToAgent(data); }
584 case 2: // Mouse events, forward to agent
585 if (viewer.viewOnly == false) { obj.sendToAgent(data); }
587 case 5: // Compression
588 if (data.length < 10) return;
589 viewer.imageType = data[4]; // Image type: 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = WebP
590 viewer.imageCompression = data[5];
591 viewer.imageScaling = data.readUInt16BE(6);
592 viewer.imageFrameRate = data.readUInt16BE(8);
593 //console.log('Viewer-Compression', viewer.imageType, viewer.imageCompression, viewer.imageScaling, viewer.imageFrameRate);
595 // See if this changes anything
596 var viewersimageType = null;
597 var viewersimageCompression = null;
598 var viewersimageScaling = null;
599 var viewersimageFrameRate = null;
600 for (var i in obj.viewers) {
601 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
602 if ((viewersimageCompression == null) || (obj.viewers[i].imageCompression > viewersimageCompression)) { viewersimageCompression = obj.viewers[i].imageCompression; };
603 if ((viewersimageScaling == null) || (obj.viewers[i].imageScaling > viewersimageScaling)) { viewersimageScaling = obj.viewers[i].imageScaling; };
604 if ((viewersimageFrameRate == null) || (obj.viewers[i].imageFrameRate < viewersimageFrameRate)) { viewersimageFrameRate = obj.viewers[i].imageFrameRate; };
606 if ((obj.imageCompression != viewersimageCompression) || (obj.imageScaling != viewersimageScaling) || (obj.imageFrameRate != viewersimageFrameRate)) {
607 // Update and send to agent new compression settings
608 obj.imageType = viewersimageType;
609 obj.imageCompression = viewersimageCompression;
610 obj.imageScaling = viewersimageScaling;
611 obj.imageFrameRate = viewersimageFrameRate
612 //console.log('Send-Agent-Compression', obj.imageType, obj.imageCompression, obj.imageScaling, obj.imageFrameRate);
613 var cmd = Buffer.alloc(10);
614 cmd.writeUInt16BE(5, 0); // Command 5, compression
615 cmd.writeUInt16BE(10, 2); // Command size, 10 bytes long
616 cmd[4] = obj.imageType; // Image type: 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = WebP
617 cmd[5] = obj.imageCompression; // Image compression level
618 cmd.writeUInt16BE(obj.imageScaling, 6); // Scaling level
619 cmd.writeUInt16BE(obj.imageFrameRate, 8); // Frame rate timer
620 obj.sendToAgent(cmd);
623 case 6: // Refresh, handle this on the server
624 //console.log('Viewer-Refresh');
625 viewer.dataPtr = obj.firstData; // Start over
626 if (viewer.sending == false) { sendViewerNext(viewer); }
628 case 8: // Pause and unpause
629 if (data.length != 5) break;
630 var pause = data[4]; // 0 = Unpause, 1 = Pause
631 if (viewer.desktopPaused == (pause == 1)) break;
632 viewer.desktopPaused = (pause == 1);
633 //console.log('Viewer-' + ((pause == 1)?'Pause':'UnPause'));
634 var viewersPaused = true;
635 for (var i in obj.viewers) { if (obj.viewers[i].desktopPaused == false) { viewersPaused = false; }; }
636 if (viewersPaused != obj.desktopPaused) {
637 obj.desktopPaused = viewersPaused;
638 //console.log('Send-Agent-' + ((viewersPaused == true) ? 'Pause' : 'UnPause'));
639 data[4] = (viewersPaused == true) ? 1 : 0;
640 obj.sendToAgent(data);
643 case 10: // CTRL-ALT-DEL, forward to agent
644 if (viewer.viewOnly == false) { obj.sendToAgent(data); }
646 case 12: // SET DISPLAY, forward to agent
647 if (viewer.viewOnly == false) { obj.sendToAgent(data); }
649 case 14: // Touch setup
651 case 82: // Request display information
652 if (obj.lastDisplayLocationData != null) { obj.sendToAgent(obj.lastDisplayLocationData); }
654 case 85: // Unicode Key Events, forward to agent
655 if (viewer.viewOnly == false) { obj.sendToAgent(data); }
657 case 87: // Remote input lock, forward to agent
658 if (viewer.viewOnly == false) { obj.sendToAgent(data); }
661 console.log('Un-handled viewer command: ' + command);
666 // Process incoming agent data
667 obj.processAgentData = function (data) {
668 if ((typeof data != 'object') || (data.length < 4)) {
669 if (typeof data == 'string') {
671 try { json = JSON.parse(data); } catch (ex) { }
672 if (json == null) return;
673 if (json.type == 'console') {
674 // This is a console message, store it and forward this to all viewers
675 if (json.msg != null) { obj.lastConsoleMessage = data; } else { obj.lastConsoleMessage = null; }
676 obj.sendToAllViewers(data);
678 // All other control messages (notably WebRTC), are ignored for now.
680 return; // Ignore all other traffic
682 const jumboData = data;
683 var command = data.readUInt16BE(0);
684 var cmdsize = data.readUInt16BE(2);
685 //console.log('AgentData', data.length, command, cmdsize);
686 if ((command == 27) && (cmdsize == 8)) {
688 if (data.length >= 12) {
689 command = data.readUInt16BE(8);
690 cmdsize = data.readUInt32BE(4);
691 if (data.length == (cmdsize + 8)) {
692 data = data.slice(8, data.length);
694 console.log('TODO-PARTIAL-JUMBO', command, cmdsize, data.length);
701 case 3: // Tile, check dimentions and store
702 if ((data.length < 10) || (obj.lastData == null)) break;
703 var x = data.readUInt16BE(4), y = data.readUInt16BE(6);
704 var dimensions = require('image-size').imageSize(data.slice(8));
705 var sx = (x / 16), sy = (y / 16), sw = (dimensions.width / 16), sh = (dimensions.height / 16);
708 // Keep a reference to this image & how many tiles it covers
709 obj.images[obj.counter] = { next: null, prev: obj.lastData, data: jumboData };
710 obj.images[obj.lastData].next = obj.counter;
711 obj.lastData = obj.counter;
712 obj.imagesCounters[obj.counter] = (sw * sh);
714 if (obj.imagesCount == 2000000000) { obj.imagesCount = 1; } // Loop the counter if needed
716 //console.log('Adding Image ' + obj.counter, x, y, dimensions.width, dimensions.height);
718 // Update the screen with the correct pointers.
719 for (var i = 0; i < sw; i++) {
720 for (var j = 0; j < sh; j++) {
721 var k = ((obj.swidth * (j + sy)) + (i + sx));
722 const oi = obj.screen[k];
723 obj.screen[k] = obj.counter;
724 if ((oi != null) && (--obj.imagesCounters[oi] == 0)) {
725 // Remove data from the link list
727 var d = obj.images[oi];
728 //console.log('Removing Image', oi, obj.images[oi].prev, obj.images[oi].next);
729 obj.images[d.prev].next = d.next;
730 obj.images[d.next].prev = d.prev;
731 delete obj.images[oi];
732 delete obj.imagesCounters[oi];
734 // If any viewers are currently on image "oi" must be moved to "d.next"
735 for (var l in obj.viewers) { const v = obj.viewers[l]; if (v.dataPtr == oi) { v.dataPtr = d.next; } }
740 // Any viewer on dataPtr null, change to this image
741 for (var i in obj.viewers) {
742 const v = obj.viewers[i];
743 if (v.dataPtr == null) { v.dataPtr = obj.counter; if (v.sending == false) { sendViewerNext(v); } }
746 // Debug, display the link list
747 //var xx = '', xptr = obj.firstData;
748 //while (xptr != null) { xx += '>' + xptr; xptr = obj.images[xptr].next; }
749 //console.log('list', xx);
750 //console.log('images', obj.imagesCount);
753 case 4: // Tile Copy, do nothing.
755 case 7: // Screen Size, clear the screen state and compute the tile count
756 if (data.length < 8) break;
757 if ((obj.width === data.readUInt16BE(4)) && (obj.height === data.readUInt16BE(6))) break; // Same screen size as before, skip this.
759 obj.lastScreenSizeCmd = data;
760 obj.lastScreenSizeCounter = obj.counter;
761 obj.width = data.readUInt16BE(4);
762 obj.height = data.readUInt16BE(6);
763 obj.swidth = obj.width / 16;
764 obj.sheight = obj.height / 16;
765 if (Math.floor(obj.swidth) != obj.swidth) { obj.swidth = Math.floor(obj.swidth) + 1; }
766 if (Math.floor(obj.sheight) != obj.sheight) { obj.sheight = Math.floor(obj.sheight) + 1; }
769 obj.screen = new Array(obj.swidth * obj.sheight);
771 obj.imagesCounters = {};
773 obj.images[obj.counter] = { next: null, prev: null, data: data };
774 obj.firstData = obj.counter;
775 obj.lastData = obj.counter;
777 // Add viewers must be set to start at "obj.counter"
778 for (var i in obj.viewers) {
779 const v = obj.viewers[i];
780 v.dataPtr = obj.counter;
781 if (v.sending == false) { sendViewerNext(v); }
784 //console.log("ScreenSize", obj.width, obj.height, obj.swidth, obj.sheight, obj.swidth * obj.sheight);
786 case 11: // GetDisplays
787 // Store and send this to all viewers right away
788 obj.lastDisplayInfoData = data;
789 obj.sendToAllInputViewers(data);
791 case 12: // SetDisplay
792 obj.sendToAllInputViewers(data);
794 case 14: // KVM_INIT_TOUCH
796 case 15: // KVM_TOUCH
798 case 17: // MNG_KVM_MESSAGE
799 // Send this to all viewers right away
800 obj.sendToAllViewers(data);
802 case 18: // MNG_KVM_KEYSTATE
803 // Store and send this to all viewers right away
804 obj.lastKeyState = data;
805 obj.sendToAllInputViewers(data);
808 // Send this to all viewers right away
809 obj.sendToAllViewers(data);
812 // Display information
813 if ((data.length < 14) || (((data.length - 4) % 10) != 0)) break; // Command must be 14 bytes and have header + 10 byte for each display.
814 obj.lastDisplayLocationData = data;
815 obj.sendToAllInputViewers(data);
817 case 87: // MNG_KVM_INPUT_LOCK
818 // Send this to all viewers right away
819 // This will update all views on the current state of the input lock
820 obj.sendToAllInputViewers(data);
822 case 88: // MNG_KVM_MOUSE_CURSOR
823 // Send this to all viewers right away
824 obj.sendToAllInputViewers(data);
827 console.log('Un-handled agent command: ' + command + ', length: ' + cmdsize);
832 function startRecording(domain, start, func) {
833 if ((obj.pendingRecording == 1) || (obj.recordingFile != null)) { func(true); return; } // Check if already recording
834 if (start == false) { func(false); return; } // Just skip this
835 obj.pendingRecording = 1;
836 var now = new Date(Date.now());
837 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'
838 var recFullFilename = null;
839 if (domain.sessionrecording.filepath) {
840 try { parent.parent.fs.mkdirSync(domain.sessionrecording.filepath); } catch (e) { }
841 recFullFilename = parent.parent.path.join(domain.sessionrecording.filepath, recFilename);
843 try { parent.parent.fs.mkdirSync(parent.parent.recordpath); } catch (e) { }
844 recFullFilename = parent.parent.path.join(parent.parent.recordpath, recFilename);
846 parent.parent.fs.open(recFullFilename, 'w', function (err, fd) {
847 delete obj.pendingRecording;
849 parent.parent.debug('relay', 'Relay: Unable to record to file: ' + recFullFilename);
853 // Write the recording file header
854 parent.parent.debug('relay', 'Relay: Started recording to file: ' + recFullFilename);
855 var metadata = { magic: 'MeshCentralRelaySession', ver: 1, nodeid: obj.nodeid, meshid: obj.meshid, time: new Date().toLocaleString(), protocol: 2, devicename: obj.name, devicegroup: obj.meshname };
856 var firstBlock = JSON.stringify(metadata);
857 recordingEntry(fd, 1, 0, firstBlock, function () {
858 obj.recordingFile = { fd: fd, filename: recFullFilename };
859 obj.recordingFileWriting = false;
865 // Here, we check if we have to record the device, regardless of what user is looking at it.
866 function recordingSetup(domain, func) {
869 // Setup session recording
870 if (((domain.sessionrecording == true) || ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.protocols == null) || (domain.sessionrecording.protocols.indexOf(2) >= 0))))) {
873 // Check again to make sure we need to start recording
874 if ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.onlyselecteddevicegroups === true) || (domain.sessionrecording.onlyselectedusergroups === true) || (domain.sessionrecording.onlyselectedusers === true))) {
877 // Check device group recording
878 if (domain.sessionrecording.onlyselecteddevicegroups === true) {
879 var mesh = parent.meshes[obj.meshid];
880 if ((mesh.flags != null) && ((mesh.flags & 4) != 0)) { record = true; }
884 startRecording(domain, record, func);
887 // Record data to the recording file
888 function recordData(isAgent, data, func) {
890 if (obj.recordingFile != null) {
891 // Write data to recording file
892 recordingEntry(obj.recordingFile.fd, 2, (isAgent ? 0 : 2), data, function () { func(data); });
896 } catch (ex) { console.log(ex); }
899 // Record a new entry in a recording log
900 function recordingEntry(fd, type, flags, data, func, tag) {
902 if (typeof data == 'string') {
904 var blockData = Buffer.from(data), header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
905 header.writeInt16BE(type, 0); // Type (1 = Header, 2 = Network Data)
906 header.writeInt16BE(flags, 2); // Flags (1 = Binary, 2 = User)
907 header.writeInt32BE(blockData.length, 4); // Size
908 header.writeIntBE(new Date(), 10, 6); // Time
909 var block = Buffer.concat([header, blockData]);
910 parent.parent.fs.write(fd, block, 0, block.length, function () { func(fd, tag); });
911 obj.recordingFileSize += block.length;
914 var header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
915 header.writeInt16BE(type, 0); // Type (1 = Header, 2 = Network Data)
916 header.writeInt16BE(flags | 1, 2); // Flags (1 = Binary, 2 = User)
917 header.writeInt32BE(data.length, 4); // Size
918 header.writeIntBE(new Date(), 10, 6); // Time
919 var block = Buffer.concat([header, data]);
920 parent.parent.fs.write(fd, block, 0, block.length, function () { func(fd, tag); });
921 obj.recordingFileSize += block.length;
923 } catch (ex) { console.log(ex); func(fd, tag); }
926 // If there is a recording quota, remove any old recordings if needed
927 function cleanUpRecordings() {
928 if ((parent.cleanUpRecordingsActive !== true) && domain.sessionrecording && ((typeof domain.sessionrecording.maxrecordings == 'number') || (typeof domain.sessionrecording.maxrecordingsizemegabytes == 'number') || (typeof domain.sessionrecording.maxrecordingdays == 'number'))) {
929 parent.cleanUpRecordingsActive = true;
930 setTimeout(function () {
931 var recPath = null, fs = require('fs'), now = Date.now();
932 if (domain.sessionrecording.filepath) { recPath = domain.sessionrecording.filepath; } else { recPath = parent.parent.recordpath; }
933 fs.readdir(recPath, function (err, files) {
934 if ((err != null) || (files == null)) { delete parent.cleanUpRecordingsActive; return; }
936 for (var i in files) {
937 if (files[i].endsWith('.mcrec')) {
938 var j = files[i].indexOf('-');
941 try { stats = fs.statSync(parent.parent.path.join(recPath, files[i])); } catch (ex) { }
942 if (stats != null) { recfiles.push({ n: files[i], r: files[i].substring(j + 1), s: stats.size, t: stats.mtimeMs }); }
946 recfiles.sort(function (a, b) { if (a.r < b.r) return 1; if (a.r > b.r) return -1; return 0; });
947 var totalFiles = 0, totalSize = 0;
948 for (var i in recfiles) {
949 var overQuota = false;
950 if ((typeof domain.sessionrecording.maxrecordings == 'number') && (domain.sessionrecording.maxrecordings > 0) && (totalFiles >= domain.sessionrecording.maxrecordings)) { overQuota = true; }
951 else if ((typeof domain.sessionrecording.maxrecordingsizemegabytes == 'number') && (domain.sessionrecording.maxrecordingsizemegabytes > 0) && (totalSize >= (domain.sessionrecording.maxrecordingsizemegabytes * 1048576))) { overQuota = true; }
952 else if ((typeof domain.sessionrecording.maxrecordingdays == 'number') && (domain.sessionrecording.maxrecordingdays > 0) && (((now - recfiles[i].t) / 1000 / 60 / 60 / 24) >= domain.sessionrecording.maxrecordingdays)) { overQuota = true; }
953 if (overQuota) { fs.unlinkSync(parent.parent.path.join(recPath, recfiles[i].n)); }
955 totalSize += recfiles[i].s;
957 delete parent.cleanUpRecordingsActive;
963 // Get node information
964 parent.db.Get(nodeid, function (err, nodes) {
965 if ((err != null) || (nodes.length != 1)) { func(null); return; }
966 obj.meshid = nodes[0].meshid;
967 obj.icon = nodes[0].icon;
968 obj.name = nodes[0].name;
969 recordingSetup(domain, function () { func(obj); });
974// Export CreateDesktopMultiplexor for use by canvas desktop endpoint
975module.exports.CreateDesktopMultiplexor = CreateDesktopMultiplexor;
977function checkDeviceSharePublicIdentifier(parent, domain, nodeid, pid, extraKey, func) {
978 // Check the public id
979 parent.db.GetAllTypeNodeFiltered([nodeid], domain.id, 'deviceshare', null, function (err, docs) {
980 if ((err != null) || (docs.length == 0)) { func(false); return; }
982 // Search for the device share public identifier
984 for (var i = 0; i < docs.length; i++) { if ((docs[i].publicid == pid) && ((docs[i].extrakey == null) || (docs[i].extrakey === extraKey))) { found = true; } }
989module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie) {
990 if ((cookie != null) && (typeof cookie.nid == 'string') && (typeof cookie.pid == 'string')) {
991 checkDeviceSharePublicIdentifier(parent, domain, cookie.nid, cookie.pid, cookie.k, function (result) {
992 // If the identifier if not found, close the connection
993 if (result == false) { try { ws.close(); } catch (e) { } return; }
994 // Public device sharing identifier found, continue as normal.
995 CreateMeshRelayEx(parent, ws, req, domain, user, cookie);
998 CreateMeshRelayEx(parent, ws, req, domain, user, cookie);
1002// If we are in multi-server mode, the desktop multiplexor needs to be created on the server with the agent connected to it.
1003// So, if the agent is connected to a different server, just relay the connection to that server
1004function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
1005 // Do validation work
1007 if ((typeof cookie.expire == 'number') && (cookie.expire <= Date.now())) { delete req.query.nodeid; }
1008 else if (typeof cookie.nid == 'string') { req.query.nodeid = cookie.nid; }
1010 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.
1012 // Check routing if in multi-server mode
1013 var nodeid = req.query.nodeid;
1014 if (parent.parent.multiServer != null) {
1015 const routing = parent.parent.GetRoutingServerIdNotSelf(nodeid, 1); // 1 = MeshAgent routing type
1016 if (routing == null) {
1017 // No need to relay the connection to a different server
1018 return CreateMeshRelayEx2(parent, ws, req, domain, user, cookie);
1020 // We must relay the connection to a different server
1021 return parent.parent.multiServer.createPeerRelay(ws, req, routing.serverid, req.session.userid);
1024 // No need to relay the connection to a different server
1025 return CreateMeshRelayEx2(parent, ws, req, domain, user, cookie);
1029function CreateMeshRelayEx2(parent, ws, req, domain, user, cookie) {
1030 const currentTime = Date.now();
1034 obj.id = req.query.id;
1035 obj.nodeid = req.query.nodeid;
1038 obj.req = req; // Used in multi-server.js
1039 obj.viewOnly = ((cookie != null) && (cookie.vo == 1)); // set view only mode
1040 if ((cookie != null) && (cookie.nouser == 1)) { obj.nouser = true; } // This is a relay without user authentication
1042 // If the domain has remote desktop viewonly set, force everyone to be in viewonly mode.
1043 if ((typeof domain.desktop == 'object') && (domain.desktop.viewonly == true)) { obj.viewOnly = true; }
1045 // Setup traffic accounting
1046 if (parent.trafficStats.desktopMultiplex == null) { parent.trafficStats.desktopMultiplex = { connections: 1, sessions: 0, in: 0, out: 0 }; } else { parent.trafficStats.desktopMultiplex.connections++; }
1047 ws._socket.bytesReadEx = 0;
1048 ws._socket.bytesWrittenEx = 0;
1050 // Setup subscription for desktop sharing public identifier
1051 // If the identifier is removed, drop the connection
1052 if ((cookie != null) && (typeof cookie.pid == 'string')) {
1053 obj.pid = cookie.pid;
1054 obj.guestName = cookie.gn;
1055 parent.parent.AddEventDispatch([obj.nodeid], obj);
1056 obj.HandleEvent = function (source, event, ids, id) { if ((event.action == 'removedDeviceShare') && (obj.pid == event.publicid)) { obj.close(); } }
1059 // Check relay authentication
1060 if ((user == null) && (obj.req.query != null) && (obj.req.query.rauth != null)) {
1061 const rcookie = parent.parent.decodeCookie(obj.req.query.rauth, parent.parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
1062 if (rcookie.ruserid != null) { obj.ruserid = rcookie.ruserid; } else if (rcookie.nouser === 1) { obj.rnouser = true; }
1063 if (rcookie.nodeid != null) { obj.nodeid = rcookie.nodeid; }
1066 // If there is no authentication, drop this connection
1067 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; }
1069 // Relay session count (we may remove this in the future)
1070 obj.relaySessionCounted = true;
1071 parent.relaySessionCount++;
1074 const MESHRIGHT_EDITMESH = 1;
1075 const MESHRIGHT_MANAGEUSERS = 2;
1076 const MESHRIGHT_MANAGECOMPUTERS = 4;
1077 const MESHRIGHT_REMOTECONTROL = 8;
1078 const MESHRIGHT_AGENTCONSOLE = 16;
1079 const MESHRIGHT_SERVERFILES = 32;
1080 const MESHRIGHT_WAKEDEVICE = 64;
1081 const MESHRIGHT_SETNOTES = 128;
1082 const MESHRIGHT_REMOTEVIEW = 256;
1085 const SITERIGHT_SERVERBACKUP = 1;
1086 const SITERIGHT_MANAGEUSERS = 2;
1087 const SITERIGHT_SERVERRESTORE = 4;
1088 const SITERIGHT_FILEACCESS = 8;
1089 const SITERIGHT_SERVERUPDATE = 16;
1090 const SITERIGHT_LOCKED = 32;
1092 // Clean a IPv6 address that encodes a IPv4 address
1093 function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
1095 // Disconnect this agent
1096 obj.close = function (arg) {
1097 if (obj.ws == null) return; // Already closed.
1099 // Close the connection
1100 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
1101 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
1102 if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
1103 if ((obj.deskMultiplexor != null) && (typeof obj.deskMultiplexor == 'object') && (obj.deskMultiplexor.removePeer(obj) == true)) { delete parent.desktoprelays[obj.nodeid]; }
1105 // Aggressive cleanup
1112 delete obj.expireTimer;
1113 delete obj.deskMultiplexor;
1115 // Clear timers if present
1116 if (obj.pingtimer != null) { clearInterval(obj.pingtimer); delete obj.pingtimer; }
1117 if (obj.pongtimer != null) { clearInterval(obj.pongtimer); delete obj.pongtimer; }
1120 if (obj.pid != null) { parent.parent.RemoveAllEventDispatch(obj); }
1123 obj.sendAgentMessage = function (command, userid, domainid) {
1125 if (command.nodeid == null) return false;
1127 if (userid != null) { user = parent.users[userid]; if (user == null) return false; }
1128 var splitnodeid = command.nodeid.split('/');
1129 // Check that we are in the same domain and the user has rights over this node.
1130 if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domainid)) {
1131 // Get the user object
1132 // See if the node is connected
1133 var agent = parent.wsagents[command.nodeid];
1134 if (agent != null) {
1135 // Check if we have permission to send a message to that node
1136 if (userid == null) { rights = MESHRIGHT_REMOTECONTROL; } else { rights = parent.GetNodeRights(user, agent.dbMeshKey, agent.dbNodeKey); }
1137 mesh = parent.meshes[agent.dbMeshKey];
1138 if ((rights != null) && (mesh != null) || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
1139 if (ws.sessionId) { command.sessionid = ws.sessionId; } // Set the session id, required for responses.
1140 command.rights = rights; // Add user rights flags to the message
1141 if ((command.rights != 0xFFFFFFFF) && ((command.rights & 0x100) != 0)) { command.rights -= 0x100; } // Since the multiplexor will enforce view-only, remove MESHRIGHT_REMOTEVIEWONLY
1142 if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
1143 if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
1145 command.username = user.name; // Add user name
1146 command.realname = user.realname; // Add real name
1148 if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
1149 delete command.nodeid; // Remove the nodeid since it's implyed.
1150 agent.send(JSON.stringify(command));
1154 // Check if a peer server is connected to this agent
1155 var routing = parent.parent.GetRoutingServerIdNotSelf(command.nodeid, 1); // 1 = MeshAgent routing type
1156 if (routing != null) {
1157 // Check if we have permission to send a message to that node
1158 if (userid == null) { rights = MESHRIGHT_REMOTECONTROL; } else { rights = parent.GetNodeRights(user, routing.meshid, command.nodeid); }
1159 mesh = parent.meshes[routing.meshid];
1160 if (rights != null || ((rights & 16) != 0)) { // TODO: 16 is console permission, may need more gradular permission checking
1161 if (ws.sessionId) { command.fromSessionid = ws.sessionId; } // Set the session id, required for responses.
1162 command.rights = rights; // Add user rights flags to the message
1163 if ((command.rights != 0xFFFFFFFF) && ((command.rights & 0x00000100) != 0)) { command.rights -= 0x00000100; } // Since the multiplexor will enforce view-only, remove MESHRIGHT_REMOTEVIEWONLY
1164 if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
1165 if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
1167 command.username = user.name; // Add user name
1168 command.realname = user.realname; // Add real name
1170 if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
1171 parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
1180 // Send a PING/PONG message
1181 function sendPing() {
1182 try { obj.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } catch (ex) { }
1183 try { if (obj.peer != null) { obj.peer.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } } catch (ex) { }
1185 function sendPong() {
1186 try { obj.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } catch (ex) { }
1187 try { if (obj.peer != null) { obj.peer.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } } catch (ex) { }
1190 function performRelay(retryCount) {
1191 if ((obj.id == null) || (retryCount > 20)) { try { obj.close(); } catch (e) { } return null; } // Attempt to connect without id, drop this.
1192 if (retryCount == 0) { ws._socket.setKeepAlive(true, 240000); } // Set TCP keep alive
1195 // Validate that the id is valid, we only need to do this on non-authenticated sessions.
1196 // TODO: Figure out when this needs to be done.
1198 // Check the identifier, if running without TLS, skip this.
1199 var ids = obj.id.split(':');
1200 if (ids.length != 3) { ws.close(); delete obj.id; return null; } // Invalid ID, drop this.
1201 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.
1202 if ((Date.now() - parseInt(ids[1])) > 120000) { ws.close(); delete obj.id; return null; } // Expired time, drop this.
1207 if (retryCount == 0) {
1208 // Setup the agent PING/PONG timers
1209 if ((typeof parent.parent.args.agentping == 'number') && (obj.pingtimer == null)) { obj.pingtimer = setInterval(sendPing, parent.parent.args.agentping * 1000); }
1210 else if ((typeof parent.parent.args.agentpong == 'number') && (obj.pongtimer == null)) { obj.pongtimer = setInterval(sendPong, parent.parent.args.agentpong * 1000); }
1212 parent.parent.debug('relay', 'DesktopRelay: Connection (' + obj.req.clientIp + ')');
1215 // Create if needed and add this peer to the desktop multiplexor
1216 obj.deskMultiplexor = parent.desktoprelays[obj.nodeid];
1217 if (obj.deskMultiplexor == null) {
1218 parent.desktoprelays[obj.nodeid] = 1; // Indicate that the creating of the desktop multiplexor is pending.
1219 parent.parent.debug('relay', 'DesktopRelay: Creating new desktop multiplexor');
1220 CreateDesktopMultiplexor(parent, domain, obj.nodeid, obj.id, function (deskMultiplexor) {
1221 if (deskMultiplexor != null) {
1222 // Desktop multiplexor was created, use it.
1223 obj.deskMultiplexor = deskMultiplexor;
1224 parent.desktoprelays[obj.nodeid] = obj.deskMultiplexor;
1225 obj.deskMultiplexor.addPeer(obj);
1226 ws._socket.resume(); // Release the traffic
1228 // An error has occured, close this connection
1229 delete parent.desktoprelays[obj.nodeid];
1234 if (obj.deskMultiplexor == 1) {
1235 // The multiplexor is being created, hold a little and try again. This is to prevent a possible race condition.
1236 setTimeout(function () { performRelay(++retryCount); }, 50);
1238 // Hook up this peer to the multiplexor and release the traffic
1239 obj.deskMultiplexor.addPeer(obj);
1240 ws._socket.resume();
1245 // When data is received from the mesh relay web socket
1246 ws.on('message', function (data) {
1248 parent.trafficStats.desktopMultiplex.in += (this._socket.bytesRead - this._socket.bytesReadEx);
1249 parent.trafficStats.desktopMultiplex.out += (this._socket.bytesWritten - this._socket.bytesWrittenEx);
1250 this._socket.bytesReadEx = this._socket.bytesRead;
1251 this._socket.bytesWrittenEx = this._socket.bytesWritten;
1253 // If this data was received by the agent, decode it.
1254 if (this.me.deskMultiplexor != null) { this.me.deskMultiplexor.processData(this.me, data); }
1257 // If error, close both sides of the relay.
1258 ws.on('error', function (err) {
1259 //console.log('ws-error', err);
1260 parent.relaySessionErrorCount++;
1261 console.log('Relay error from ' + obj.req.clientIp + ', ' + err.toString().split('\r')[0] + '.');
1265 // If the relay web socket is closed, close both sides.
1266 ws.on('close', function (req) {
1268 parent.trafficStats.desktopMultiplex.in += (this._socket.bytesRead - this._socket.bytesReadEx);
1269 parent.trafficStats.desktopMultiplex.out += (this._socket.bytesWritten - this._socket.bytesWrittenEx);
1270 this._socket.bytesReadEx = this._socket.bytesRead;
1271 this._socket.bytesWrittenEx = this._socket.bytesWritten;
1273 //console.log('ws-close', req);
1277 // If this session has a expire time, setup the expire timer now.
1280 // Mark this relay session as authenticated if this is the user end.
1281 obj.authenticated = ((user != null) || (obj.nouser === true));
1282 if (obj.authenticated) {
1283 // Kick off the routing, if we have agent routing instructions, process them here.
1284 // Routing instructions can only be given by a authenticated user
1285 if ((cookie != null) && (cookie.nodeid != null) && (cookie.tcpport != null) && (cookie.domainid != null)) {
1286 // We have routing instructions in the cookie, but first, check user access for this node.
1287 parent.db.Get(cookie.nodeid, function (err, docs) {
1288 if (obj.req == null) return; // This connection was closed.
1289 if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
1290 const node = docs[0];
1292 // Check if this user has permission to manage this computer
1293 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; }
1295 // Send connection request to agent
1296 const rcookieData = { nodeid: node._id };
1297 if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
1298 const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
1299 if (obj.id == undefined) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
1300 const command = { nodeid: node._id, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr };
1301 parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
1302 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 + ')'); }
1306 } else if ((obj.req.query.nodeid != null) && ((obj.req.query.tcpport != null) || (obj.req.query.udpport != null))) {
1307 // We have routing instructions in the URL arguments, but first, check user access for this node.
1308 parent.db.Get(obj.req.query.nodeid, function (err, docs) {
1309 if (obj.req == null) return; // This connection was closed.
1310 if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
1311 const node = docs[0];
1313 // Check if this user has permission to manage this computer
1314 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; }
1316 // Send connection request to agent
1317 if (obj.id == null) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
1318 const rcookieData = { nodeid: node._id };
1319 if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
1320 const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
1322 if (obj.req.query.tcpport != null) {
1323 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) };
1324 parent.parent.debug('relay', 'Relay: Sending agent TCP tunnel command: ' + JSON.stringify(command));
1325 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 + ')'); }
1326 } else if (obj.req.query.udpport != null) {
1327 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) };
1328 parent.parent.debug('relay', 'Relay: Sending agent UDP tunnel command: ' + JSON.stringify(command));
1329 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 + ')'); }
1334 } else if ((cookie != null) && (cookie.nid != null) && (typeof cookie.r == 'number') && (typeof cookie.cf == 'number') && (typeof cookie.gn == 'string')) {
1335 // We have routing instructions in the cookie, but first, check user access for this node.
1336 parent.db.Get(cookie.nid, function (err, docs) {
1337 if (obj.req == null) return; // This connection was closed.
1338 if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
1339 const node = docs[0];
1341 // Check if this user has permission to manage this computer
1342 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; }
1344 // Send connection request to agent
1345 if (obj.id == null) { obj.id = ('' + Math.random()).substring(2); }
1346 const rcookieData = { nodeid: node._id };
1347 if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
1348 const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
1349 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) };
1350 if (typeof domain.consentmessages == 'object') {
1351 if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
1352 if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
1353 if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
1354 if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
1355 if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
1356 if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
1357 if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
1358 if (domain.consentmessages.autoacceptifdesktopnouser === true) { command.soptions.consentAutoAcceptIfDesktopNoUser = true; }
1359 if (domain.consentmessages.autoacceptifterminalnouser === true) { command.soptions.consentAutoAcceptIfTerminalNoUser = true; }
1360 if (domain.consentmessages.autoacceptiffilenouser === true) { command.soptions.consentAautoAcceptIfFileNoUser = true; }
1361 if (domain.consentmessages.autoacceptiflocked === true) { command.soptions.consentAutoAcceptIfLocked = true; }
1362 if (domain.consentmessages.autoacceptifdesktoplocked === true) { command.soptions.consentAutoAcceptIfDesktopLocked = true; }
1363 if (domain.consentmessages.autoacceptifterminallocked === true) { command.soptions.consentAutoAcceptIfTerminalLocked = true; }
1364 if (domain.consentmessages.autoacceptiffilelocked === true) { command.soptions.consentAutoAcceptIfFileLocked = true; }
1365 if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
1367 if (typeof domain.notificationmessages == 'object') {
1368 if (typeof domain.notificationmessages.title == 'string') { command.soptions.notifyTitle = domain.notificationmessages.title; }
1369 if (typeof domain.notificationmessages.desktop == 'string') { command.soptions.notifyMsgDesktop = domain.notificationmessages.desktop; }
1370 if (typeof domain.notificationmessages.terminal == 'string') { command.soptions.notifyMsgTerminal = domain.notificationmessages.terminal; }
1371 if (typeof domain.notificationmessages.files == 'string') { command.soptions.notifyMsgFiles = domain.notificationmessages.files; }
1373 parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
1374 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 + ')'); }
1382 // Set the session expire timer
1383 function setExpireTimer() {
1384 if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; }
1385 if (cookie && (typeof cookie.expire == 'number')) {
1386 const timeToExpire = (cookie.expire - Date.now());
1387 if (timeToExpire < 1) {
1389 } else if (timeToExpire >= 0x7FFFFFFF) {
1390 obj.expireTimer = setTimeout(setExpireTimer, 0x7FFFFFFF); // Since expire timer can't be larger than 0x7FFFFFFF, reset timer after that time.
1392 obj.expireTimer = setTimeout(obj.close, timeToExpire);
1398 // Check if this user has input access on the device
1399 if ((obj.user != null) && (obj.viewOnly == false)) {
1400 obj.viewOnly = true; // Set a view only for now until we figure out otherwise
1401 parent.db.Get(obj.nodeid, function (err, docs) {
1402 if (obj.req == null) return; // This connection was closed.
1403 if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
1404 const node = docs[0];
1406 // Check if this user has permission to manage this computer
1407 const rights = parent.GetNodeRights(obj.user, node.meshid, node._id);
1408 if ((rights & 0x00000008) == 0) { try { obj.close(); } catch (e) { } return; } // Check MESHRIGHT_ADMIN or MESHRIGHT_REMOTECONTROL
1409 if ((rights != 0xFFFFFFFF) && ((rights & 0x00010000) != 0)) { try { obj.close(); } catch (e) { } return; } // Check MESHRIGHT_NODESKTOP
1410 if ((rights == 0xFFFFFFFF) || ((rights & 0x00000100) == 0)) { obj.viewOnly = false; } // Check MESHRIGHT_REMOTEVIEWONLY
1414 // If this is not an authenticated session, or the session does not have routing instructions, just go ahead an connect to existing session.
1421Relay session recording required that "SessionRecording":true be set in the domain section of the config.json.
1422Once done, a folder "meshcentral-recordings" will be created next to "meshcentral-data" that will contain all
1423of the recording files with the .mcrec extension.
1425The recording files are binary and contain a set of:
1427 <HEADER><DATABLOCK><HEADER><DATABLOCK><HEADER><DATABLOCK><HEADER><DATABLOCK>...
1429The header is always 16 bytes long and is encoded like this:
1431 TYPE 2 bytes, 1 = Header, 2 = Network Data, 3 = EndBlock
1432 FLAGS 2 bytes, 0x0001 = Binary, 0x0002 = User
1433 SIZE 4 bytes, Size of the data following this header.
1434 TIME 8 bytes, Time this record was written, number of milliseconds since 1 January, 1970 UTC.
1436All values are BigEndian encoded. The first data block is of TYPE 1 and contains a JSON string with information
1437about this recording. It looks something like this:
1440 magic: 'MeshCentralRelaySession',
1442 userid: "user\domain\userid",
1443 username: "username",
1444 sessionid: "RandomValue",
1447 time: new Date().toLocaleString()
1450The rest of the data blocks are all network traffic that was relayed thru the server. They are of TYPE 2 and have
1451a given size and timestamp. When looking at network traffic the flags are important:
1453- If traffic has the first (0x0001) flag set, the data is binary otherwise it's a string.
1454- 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.