| 1 | /** |
| 2 | * @description Mesh Agent Transport Module - using websocket relay |
| 3 | * @author Ylian Saint-Hilaire |
| 4 | * @version v0.0.1f |
| 5 | */ |
| 6 | |
| 7 | // Construct a MeshServer agent direction object |
| 8 | var CreateAgentRedirect = function (meshserver, module, serverPublicNamePort, authCookie, rauthCookie, domainUrl) { |
| 9 | var obj = {}; |
| 10 | obj.m = module; // This is the inner module (Terminal or Desktop) |
| 11 | module.parent = obj; |
| 12 | obj.meshserver = meshserver; |
| 13 | obj.authCookie = authCookie; |
| 14 | obj.rauthCookie = rauthCookie; |
| 15 | obj.State = 0; // 0 = Disconnected, 1 = Connected, 2 = Connected to server, 3 = End-to-end connection. |
| 16 | obj.nodeid = null; |
| 17 | obj.options = null; |
| 18 | obj.socket = null; |
| 19 | obj.connectstate = -1; |
| 20 | obj.tunnelid = Math.random().toString(36).substring(2); // Generate a random client tunnel id |
| 21 | obj.protocol = module.protocol; // 1 = SOL, 2 = KVM, 3 = IDER, 4 = Files, 5 = FileTransfer |
| 22 | obj.onStateChanged = null; |
| 23 | obj.ctrlMsgAllowed = true; |
| 24 | obj.attemptWebRTC = false; |
| 25 | obj.webRtcActive = false; |
| 26 | obj.webrtcconfig = null; |
| 27 | obj.webSwitchOk = false; |
| 28 | obj.webchannel = null; |
| 29 | obj.webrtc = null; |
| 30 | obj.debugmode = 0; |
| 31 | obj.serverIsRecording = false; |
| 32 | obj.urlname = 'meshrelay.ashx'; |
| 33 | obj.latency = { lastSend: null, current: -1, callback: null }; |
| 34 | if (domainUrl == null) { domainUrl = '/'; } |
| 35 | |
| 36 | // Console Message |
| 37 | obj.consoleMessage = null; |
| 38 | obj.onConsoleMessageChange = null; |
| 39 | |
| 40 | // Session Metadata |
| 41 | obj.metadata = null; |
| 42 | obj.onMetadataChange = null; |
| 43 | |
| 44 | // Private method |
| 45 | //obj.debug = function (msg) { console.log(msg); } |
| 46 | |
| 47 | // Display websocket or webrtc data to the console |
| 48 | function logData(e, name) { |
| 49 | if (typeof e.data == 'object') { |
| 50 | var view = new Uint8Array(e.data), cmd = (view[0] << 8) + view[1], cmdsize = (view[2] << 8) + view[3]; |
| 51 | console.log(name + ' binary data', cmd, cmdsize, e.data.byteLength, buf2hex(e.data).substring(0, 24)); |
| 52 | } else if (typeof e.data == 'string') { |
| 53 | console.log(name + ' string data', e.data.length, e.data); |
| 54 | } else { |
| 55 | console.log(name + ' unknown data', e.data); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | obj.Start = function (nodeid) { |
| 60 | var url2, url = window.location.protocol.replace('http', 'ws') + '//' + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/' + obj.urlname + '?browser=1&p=' + obj.protocol + (nodeid?('&nodeid=' + nodeid):'') + '&id=' + obj.tunnelid; |
| 61 | //if (serverPublicNamePort) { url2 = window.location.protocol.replace('http', 'ws') + '//' + serverPublicNamePort + '/meshrelay.ashx?id=' + obj.tunnelid; } else { url2 = url; } |
| 62 | if ((authCookie != null) && (authCookie != '')) { url += '&auth=' + authCookie; } |
| 63 | if ((urlargs != null) && (urlargs.slowrelay != null)) { url += '&slowrelay=' + urlargs.slowrelay; } |
| 64 | obj.nodeid = nodeid; |
| 65 | obj.connectstate = 0; |
| 66 | obj.socket = new WebSocket(url); |
| 67 | obj.socket.binaryType = 'arraybuffer'; |
| 68 | obj.socket.onopen = obj.xxOnSocketConnected; |
| 69 | obj.socket.onmessage = obj.xxOnMessage; |
| 70 | //obj.socket.onmessage = function (e) { logData(e, 'WebSocket'); obj.xxOnMessage(e); } |
| 71 | obj.socket.onerror = function (e) { /* console.error(e); */ } |
| 72 | obj.socket.onclose = obj.xxOnSocketClosed; |
| 73 | obj.xxStateChange(1); |
| 74 | if (obj.meshserver != null) { |
| 75 | var rurl = '*' + domainUrl + 'meshrelay.ashx?p=' + obj.protocol + '&nodeid=' + nodeid + '&id=' + obj.tunnelid; |
| 76 | if ((rauthCookie != null) && (rauthCookie != '')) { rurl += ('&rauth=' + rauthCookie); } |
| 77 | obj.meshserver.send({ action: 'msg', type: 'tunnel', nodeid: obj.nodeid, value: rurl, usage: obj.protocol }); |
| 78 | //obj.debug('Agent Redir Start: ' + url); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | obj.xxOnSocketConnected = function () { |
| 83 | if (obj.debugmode == 1) { console.log('onSocketConnected'); } |
| 84 | //obj.debug('Agent Redir Socket Connected'); |
| 85 | if (!obj.latency.lastSend){ |
| 86 | obj.latency.lastSend = setInterval(function(){ |
| 87 | if (obj.latency.current == -1) { |
| 88 | clearInterval(obj.latency.lastSend); |
| 89 | obj.latency.lastSend = null; |
| 90 | } else { |
| 91 | obj.sendCtrlMsg(JSON.stringify({ctrlChannel:102938,type:"rtt",time:(new Date().getTime())})); |
| 92 | } |
| 93 | }, 10000); |
| 94 | } |
| 95 | obj.sendCtrlMsg(JSON.stringify({ctrlChannel:102938,type:"rtt",time:(new Date().getTime())})); |
| 96 | obj.xxStateChange(2); |
| 97 | } |
| 98 | |
| 99 | // Called to pass websocket control messages |
| 100 | obj.xxOnControlCommand = function (msg) { |
| 101 | var controlMsg; |
| 102 | try { controlMsg = JSON.parse(msg); } catch (e) { return; } |
| 103 | if (controlMsg.ctrlChannel != '102938') { if (obj.m.ProcessData) { obj.m.ProcessData(msg); } else { console.log(msg); } return; } |
| 104 | if ((typeof args != 'undefined') && args.redirtrace) { console.log('RedirRecv', controlMsg); } |
| 105 | if (controlMsg.type == 'console') { |
| 106 | obj.setConsoleMessage(controlMsg.msg, controlMsg.msgid, controlMsg.msgargs, controlMsg.timeout); |
| 107 | } else if (controlMsg.type == 'metadata') { |
| 108 | obj.metadata = controlMsg; |
| 109 | if (obj.onMetadataChange) obj.onMetadataChange(obj.metadata); |
| 110 | } else if ((controlMsg.type == 'rtt') && (typeof controlMsg.time == 'number')) { |
| 111 | obj.latency.current = (new Date().getTime()) - controlMsg.time; |
| 112 | if (obj.latency.callback != null) { obj.latency.callback(obj.latency.current); } |
| 113 | } else if (obj.webrtc != null) { |
| 114 | if (controlMsg.type == 'answer') { |
| 115 | obj.webrtc.setRemoteDescription(new RTCSessionDescription(controlMsg), function () { /*console.log('WebRTC remote ok');*/ }, obj.xxCloseWebRTC); |
| 116 | } else if (controlMsg.type == 'webrtc0') { |
| 117 | obj.webSwitchOk = true; // Other side is ready for switch over |
| 118 | performWebRtcSwitch(); |
| 119 | } else if (controlMsg.type == 'webrtc1') { |
| 120 | obj.sendCtrlMsg('{"ctrlChannel":"102938","type":"webrtc2"}'); // Confirm we got end of data marker, indicates data will no longer be received on websocket. |
| 121 | } else if (controlMsg.type == 'webrtc2') { |
| 122 | // TODO: Resume/Start sending data over WebRTC |
| 123 | } |
| 124 | } else if (controlMsg.type == 'ping') { // if we get a ping, respond with a pong. |
| 125 | obj.sendCtrlMsg('{"ctrlChannel":"102938","type":"pong"}'); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // Set the console message |
| 130 | obj.setConsoleMessage = function (str, id, args, timeout) { |
| 131 | if (obj.consoleMessage == str) return; |
| 132 | obj.consoleMessage = str; |
| 133 | obj.consoleMessageId = id; |
| 134 | obj.consoleMessageArgs = args; |
| 135 | obj.consoleMessageTimeout = timeout; |
| 136 | if (obj.onConsoleMessageChange) { obj.onConsoleMessageChange(obj, obj.consoleMessage, obj.consoleMessageId); } |
| 137 | } |
| 138 | |
| 139 | obj.sendCtrlMsg = function (x) { if (obj.ctrlMsgAllowed == true) { if ((typeof args != 'undefined') && args.redirtrace) { console.log('RedirSend', typeof x, x); } try { obj.socket.send(x); } catch (ex) { } } } |
| 140 | |
| 141 | function performWebRtcSwitch() { |
| 142 | if ((obj.webSwitchOk == true) && (obj.webRtcActive == true)) { |
| 143 | obj.latency.current = -1; // RTT will no longer be calculated when WebRTC is enabled |
| 144 | obj.sendCtrlMsg('{"ctrlChannel":"102938","type":"webrtc0"}'); // Indicate to the meshagent that it can start traffic switchover |
| 145 | obj.sendCtrlMsg('{"ctrlChannel":"102938","type":"webrtc1"}'); // Indicate to the meshagent that data traffic will no longer be sent over websocket. |
| 146 | // TODO: Hold/Stop sending data over websocket |
| 147 | if (obj.onStateChanged != null) { obj.onStateChanged(obj, obj.State); } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | obj.xxOnMessage = function (e) { |
| 152 | //console.log('Recv', e.data, e.data.byteLength, obj.State); |
| 153 | if (obj.State < 3) { |
| 154 | if ((e.data == 'c') || (e.data == 'cr')) { |
| 155 | if (e.data == 'cr') { obj.serverIsRecording = true; } |
| 156 | if (obj.options != null) { delete obj.options.action; obj.options.type = 'options'; try { obj.sendCtrlMsg(JSON.stringify(obj.options)); } catch (ex) { } } |
| 157 | try { obj.socket.send(obj.protocol); } catch (ex) { } |
| 158 | obj.xxStateChange(3); |
| 159 | |
| 160 | if (obj.attemptWebRTC == true) { |
| 161 | // Try to get WebRTC setup |
| 162 | var configuration = obj.webrtcconfig; //{ "iceServers": [ { 'urls': 'stun:stun.cloudflare.com:3478' }, { 'urls': 'stun:stun.l.google.com:19302' } ] }; |
| 163 | if (typeof RTCPeerConnection !== 'undefined') { obj.webrtc = new RTCPeerConnection(configuration); } |
| 164 | else if (typeof webkitRTCPeerConnection !== 'undefined') { obj.webrtc = new webkitRTCPeerConnection(configuration); } |
| 165 | if ((obj.webrtc != null) && (obj.webrtc.createDataChannel)) { |
| 166 | obj.webchannel = obj.webrtc.createDataChannel('DataChannel', {}); // { ordered: false, maxRetransmits: 2 } |
| 167 | obj.webchannel.binaryType = 'arraybuffer'; |
| 168 | obj.webchannel.onmessage = obj.xxOnMessage; |
| 169 | //obj.webchannel.onmessage = function (e) { logData(e, 'WebRTC'); obj.xxOnMessage(e); } |
| 170 | obj.webchannel.onopen = function () { obj.webRtcActive = true; performWebRtcSwitch(); }; |
| 171 | obj.webchannel.onclose = function (event) { if (obj.webRtcActive) { obj.Stop(); } } |
| 172 | obj.webrtc.onicecandidate = function (e) { |
| 173 | if (e.candidate == null) { |
| 174 | try { obj.sendCtrlMsg(JSON.stringify(obj.webrtcoffer)); } catch (ex) { } // End of candidates, send the offer |
| 175 | } else { |
| 176 | obj.webrtcoffer.sdp += ('a=' + e.candidate.candidate + '\r\n'); // New candidate, add it to the SDP |
| 177 | } |
| 178 | } |
| 179 | obj.webrtc.oniceconnectionstatechange = function () { |
| 180 | if (obj.webrtc != null) { |
| 181 | if (obj.webrtc.iceConnectionState == 'disconnected') { if (obj.webRtcActive == true) { obj.Stop(); } else { obj.xxCloseWebRTC(); } } |
| 182 | else if (obj.webrtc.iceConnectionState == 'failed') { obj.xxCloseWebRTC(); } |
| 183 | } |
| 184 | } |
| 185 | obj.webrtc.createOffer(function (offer) { |
| 186 | // Got the offer |
| 187 | obj.webrtcoffer = offer; |
| 188 | obj.webrtc.setLocalDescription(offer, function () { /*console.log('WebRTC local ok');*/ }, obj.xxCloseWebRTC); |
| 189 | }, obj.xxCloseWebRTC, { mandatory: { OfferToReceiveAudio: false, OfferToReceiveVideo: false } }); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | return; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | // Control messages, most likely WebRTC setup |
| 198 | //console.log('New data', e.data.byteLength); |
| 199 | if (typeof e.data == 'string') { |
| 200 | if (e.data[0] == '~') { obj.m.ProcessData(e.data); } else { obj.xxOnControlCommand(e.data); } |
| 201 | } else { |
| 202 | // Send the data to the module |
| 203 | if (obj.m.ProcessBinaryCommand) { |
| 204 | // If only 1 byte |
| 205 | if ((cmdAccLen == 0) && (e.data.byteLength < 4)) return; // Ignore any commands less than 4 bytes. |
| 206 | |
| 207 | // Send as Binary Command |
| 208 | if (cmdAccLen != 0) { |
| 209 | // Accumulator is active |
| 210 | var view = new Uint8Array(e.data); |
| 211 | cmdAcc.push(view); |
| 212 | cmdAccLen += view.byteLength; |
| 213 | //console.log('Accumulating', cmdAccLen); |
| 214 | if (cmdAccCmdSize <= cmdAccLen) { |
| 215 | var tmp = new Uint8Array(cmdAccLen), tmpPtr = 0; |
| 216 | for (var i in cmdAcc) { tmp.set(cmdAcc[i], tmpPtr); tmpPtr += cmdAcc[i].byteLength; } |
| 217 | //console.log('AccumulatorCompleted'); |
| 218 | obj.m.ProcessBinaryCommand(cmdAccCmd, cmdAccCmdSize, tmp); |
| 219 | cmdAccCmd = 0, cmdAccCmdSize = 0, cmdAccLen = 0, cmdAcc = []; |
| 220 | } |
| 221 | } else { |
| 222 | // Accumulator is not active |
| 223 | var view = new Uint8Array(e.data), cmd = (view[0] << 8) + view[1], cmdsize = (view[2] << 8) + view[3]; |
| 224 | if ((cmd == 27) && (cmdsize == 8)) { cmd = (view[8] << 8) + view[9]; cmdsize = (view[5] << 16) + (view[6] << 8) + view[7]; view = view.slice(8); } |
| 225 | //console.log(cmdsize, view.byteLength); |
| 226 | if (cmdsize != view.byteLength) { |
| 227 | //console.log('AccumulatorRequired', cmd, cmdsize, view.byteLength); |
| 228 | cmdAccCmd = cmd; cmdAccCmdSize = cmdsize; cmdAccLen = view.byteLength, cmdAcc = [view]; |
| 229 | } else { |
| 230 | obj.m.ProcessBinaryCommand(cmd, cmdsize, view); |
| 231 | } |
| 232 | } |
| 233 | } else if (obj.m.ProcessBinaryData) { |
| 234 | // Send as Binary |
| 235 | obj.m.ProcessBinaryData(new Uint8Array(e.data)); |
| 236 | } else { |
| 237 | // Send as Text |
| 238 | if (e.data.byteLength < 16000) { // Process small data block |
| 239 | obj.m.ProcessData(String.fromCharCode.apply(null, new Uint8Array(e.data))); // This will stack overflow on Chrome with 100k+ blocks. |
| 240 | } else { // Process large data block |
| 241 | var bb = new Blob([new Uint8Array(e.data)]), f = new FileReader(); |
| 242 | f.onload = function (e) { obj.m.ProcessData(e.target.result); }; |
| 243 | f.readAsBinaryString(bb); |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | }; |
| 248 | |
| 249 | // Command accumulator, this is used for WebRTC fragmentation |
| 250 | var cmdAccCmd = 0, cmdAccCmdSize = 0, cmdAccLen = 0, cmdAcc = []; |
| 251 | |
| 252 | obj.sendText = function (x) { |
| 253 | if (typeof x != 'string') { x = JSON.stringify(x); } // Turn into a string if needed |
| 254 | obj.send(encode_utf8(x)); // Encode UTF8 correctly |
| 255 | } |
| 256 | |
| 257 | obj.send = function (x) { |
| 258 | //obj.debug('Agent Redir Send(' + obj.webRtcActive + ', ' + x.length + '): ' + rstr2hex(x)); |
| 259 | //console.log('Agent Redir Send(' + obj.webRtcActive + ', ' + x.length + '): ' + ((typeof x == 'string')?x:rstr2hex(x))); |
| 260 | if ((typeof args != 'undefined') && args.redirtrace) { console.log('RedirSend', typeof x, x.length, (x[0] == '{') ? x : rstr2hex(x).substring(0, 64)); } |
| 261 | try { |
| 262 | if (obj.socket != null && obj.socket.readyState == WebSocket.OPEN) { |
| 263 | if (typeof x == 'string') { |
| 264 | if (obj.debugmode == 1) { |
| 265 | var b = new Uint8Array(x.length), c = []; |
| 266 | for (var i = 0; i < x.length; ++i) { b[i] = x.charCodeAt(i); c.push(x.charCodeAt(i)); } |
| 267 | if (obj.webRtcActive == true) { obj.webchannel.send(b.buffer); } else { obj.socket.send(b.buffer); } |
| 268 | //console.log('Send', c); |
| 269 | } else { |
| 270 | var b = new Uint8Array(x.length); |
| 271 | for (var i = 0; i < x.length; ++i) { b[i] = x.charCodeAt(i); } |
| 272 | if (obj.webRtcActive == true) { obj.webchannel.send(b.buffer); } else { obj.socket.send(b.buffer); } |
| 273 | } |
| 274 | } else { |
| 275 | //if (obj.debugmode == 1) { console.log('Send', x); } |
| 276 | if (obj.webRtcActive == true) { obj.webchannel.send(x); } else { obj.socket.send(x); } |
| 277 | } |
| 278 | } |
| 279 | } catch (ex) { } |
| 280 | } |
| 281 | |
| 282 | obj.xxOnSocketClosed = function () { |
| 283 | //obj.debug('Agent Redir Socket Closed'); |
| 284 | //if (obj.debugmode == 1) { console.log('onSocketClosed'); } |
| 285 | obj.Stop(1); |
| 286 | } |
| 287 | |
| 288 | obj.xxStateChange = function(newstate) { |
| 289 | if (obj.State == newstate) return; |
| 290 | obj.State = newstate; |
| 291 | obj.m.xxStateChange(obj.State); |
| 292 | if (obj.onStateChanged != null) obj.onStateChanged(obj, obj.State); |
| 293 | } |
| 294 | |
| 295 | // Close the WebRTC connection, should be called if a problem occurs during WebRTC setup. |
| 296 | obj.xxCloseWebRTC = function () { |
| 297 | if (obj.webchannel != null) { try { obj.webchannel.close(); } catch (e) { } obj.webchannel = null; } |
| 298 | if (obj.webrtc != null) { try { obj.webrtc.close(); } catch (e) { } obj.webrtc = null; } |
| 299 | obj.webRtcActive = false; |
| 300 | } |
| 301 | |
| 302 | obj.Stop = function (x) { |
| 303 | if (obj.debugmode == 1) { console.log('stop', x); } |
| 304 | |
| 305 | // Clean up WebRTC |
| 306 | obj.xxCloseWebRTC(); |
| 307 | |
| 308 | // clear RTT timer |
| 309 | obj.latency.current = -1; |
| 310 | |
| 311 | //obj.debug('Agent Redir Socket Stopped'); |
| 312 | obj.connectstate = -1; |
| 313 | if (obj.socket != null) { |
| 314 | try { if (obj.socket.readyState == 1) { obj.sendCtrlMsg('{"ctrlChannel":"102938","type":"close"}'); } } catch (ex) { } // If connected, send the close command |
| 315 | try { if (obj.socket.readyState <= 1) { obj.socket.close(); } } catch (ex) { } // If connecting or connected, close the websocket |
| 316 | obj.socket = null; |
| 317 | } |
| 318 | obj.xxStateChange(0); |
| 319 | } |
| 320 | |
| 321 | // Buffer is an ArrayBuffer |
| 322 | function buf2hex(buffer) { return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join(''); } |
| 323 | |
| 324 | return obj; |
| 325 | } |