]> git.proxmox.com Git - mirror_novnc.git/blame - core/websock.js
Added support for RTCDataChannel
[mirror_novnc.git] / core / websock.js
CommitLineData
72f1348b 1/*
44d384b9 2 * Websock: high-performance buffering wrapper
412d9306 3 * Copyright (C) 2019 The noVNC Authors
1d728ace 4 * Licensed under MPL 2.0 (see LICENSE.txt)
72f1348b 5 *
44d384b9
TS
6 * Websock is similar to the standard WebSocket / RTCDataChannel object
7 * but with extra buffer handling.
72f1348b
JM
8 *
9 * Websock has built-in receive queue buffering; the message event
10 * does not contain actual data but is simply a notification that
11 * there is new data available. Several rQ* methods are available to
12 * read binary data off of the receive queue.
13 */
14
6d6f0db0 15import * as Log from './util/logging.js';
ae510306 16
6d6f0db0
SR
17// this has performance issues in some versions Chromium, and
18// doesn't gain a tremendous amount of performance increase in Firefox
19// at the moment. It may be valuable to turn it on in the future.
2b5f94fa 20const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
6d6f0db0 21
44d384b9
TS
22// Constants pulled from RTCDataChannelState enum
23// https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum
24const DataChannel = {
25 CONNECTING: "connecting",
26 OPEN: "open",
27 CLOSING: "closing",
28 CLOSED: "closed"
29};
30
31const ReadyStates = {
32 CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING],
33 OPEN: [WebSocket.OPEN, DataChannel.OPEN],
34 CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING],
35 CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED],
36};
37
38// Properties a raw channel must have, WebSocket and RTCDataChannel are two examples
39const rawChannelProps = [
40 "send",
41 "close",
42 "binaryType",
43 "onerror",
44 "onmessage",
45 "onopen",
46 "protocol",
47 "readyState",
48];
49
0e4808bf
JD
50export default class Websock {
51 constructor() {
44d384b9 52 this._websocket = null; // WebSocket or RTCDataChannel object
0e4808bf
JD
53
54 this._rQi = 0; // Receive queue index
55 this._rQlen = 0; // Next write position in the receive queue
56 this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
0e4808bf
JD
57 // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
58 this._rQ = null; // Receive queue
59
60 this._sQbufferSize = 1024 * 10; // 10 KiB
61 // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
62 this._sQlen = 0;
63 this._sQ = null; // Send queue
64
65 this._eventHandlers = {
66 message: () => {},
67 open: () => {},
68 close: () => {},
69 error: () => {}
70 };
71 }
72
6d6f0db0 73 // Getters and Setters
8a189a62 74 get sQ() {
6d6f0db0 75 return this._sQ;
0e4808bf 76 }
6d6f0db0 77
8a189a62 78 get rQ() {
6d6f0db0 79 return this._rQ;
0e4808bf 80 }
6d6f0db0 81
8a189a62 82 get rQi() {
6d6f0db0 83 return this._rQi;
0e4808bf 84 }
6d6f0db0 85
8a189a62 86 set rQi(val) {
6d6f0db0 87 this._rQi = val;
0e4808bf 88 }
6d6f0db0
SR
89
90 // Receive Queue
8a189a62 91 get rQlen() {
6d6f0db0 92 return this._rQlen - this._rQi;
0e4808bf 93 }
6d6f0db0 94
0e4808bf 95 rQpeek8() {
6d6f0db0 96 return this._rQ[this._rQi];
0e4808bf 97 }
6d6f0db0 98
8a189a62
JD
99 rQskipBytes(bytes) {
100 this._rQi += bytes;
101 }
102
0e4808bf 103 rQshift8() {
879e33ab 104 return this._rQshift(1);
0e4808bf 105 }
6d6f0db0 106
0e4808bf 107 rQshift16() {
879e33ab 108 return this._rQshift(2);
0e4808bf 109 }
6d6f0db0 110
0e4808bf 111 rQshift32() {
879e33ab
JD
112 return this._rQshift(4);
113 }
114
115 // TODO(directxman12): test performance with these vs a DataView
116 _rQshift(bytes) {
117 let res = 0;
118 for (let byte = bytes - 1; byte >= 0; byte--) {
119 res += this._rQ[this._rQi++] << (byte * 8);
120 }
121 return res;
0e4808bf 122 }
6d6f0db0 123
0e4808bf 124 rQshiftStr(len) {
8a189a62 125 if (typeof(len) === 'undefined') { len = this.rQlen; }
db9daa98
SM
126 let str = "";
127 // Handle large arrays in steps to avoid long strings on the stack
128 for (let i = 0; i < len; i += 4096) {
f90c2a6d 129 let part = this.rQshiftBytes(Math.min(4096, len - i));
d9814c06 130 str += String.fromCharCode.apply(null, part);
db9daa98
SM
131 }
132 return str;
0e4808bf 133 }
6d6f0db0 134
0e4808bf 135 rQshiftBytes(len) {
8a189a62 136 if (typeof(len) === 'undefined') { len = this.rQlen; }
6d6f0db0
SR
137 this._rQi += len;
138 return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
0e4808bf 139 }
6d6f0db0 140
0e4808bf 141 rQshiftTo(target, len) {
8a189a62 142 if (len === undefined) { len = this.rQlen; }
6d6f0db0
SR
143 // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
144 target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
145 this._rQi += len;
0e4808bf 146 }
6d6f0db0 147
8a189a62
JD
148 rQslice(start, end = this.rQlen) {
149 return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
0e4808bf 150 }
6d6f0db0
SR
151
152 // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
153 // to be available in the receive queue. Return true if we need to
154 // wait (and possibly print a debug message), otherwise false.
0e4808bf 155 rQwait(msg, num, goback) {
8a189a62 156 if (this.rQlen < num) {
6d6f0db0
SR
157 if (goback) {
158 if (this._rQi < goback) {
159 throw new Error("rQwait cannot backup " + goback + " bytes");
2cccf753 160 }
6d6f0db0 161 this._rQi -= goback;
2cccf753 162 }
6d6f0db0
SR
163 return true; // true means need more data
164 }
165 return false;
0e4808bf 166 }
72f1348b 167
6d6f0db0 168 // Send Queue
72f1348b 169
0e4808bf 170 flush() {
44d384b9 171 if (this._sQlen > 0 && ReadyStates.OPEN.indexOf(this._websocket.readyState) >= 0) {
ea858bfa 172 this._websocket.send(this._encodeMessage());
6d6f0db0
SR
173 this._sQlen = 0;
174 }
0e4808bf 175 }
6d6f0db0 176
0e4808bf 177 send(arr) {
6d6f0db0
SR
178 this._sQ.set(arr, this._sQlen);
179 this._sQlen += arr.length;
180 this.flush();
0e4808bf 181 }
6d6f0db0 182
ea858bfa 183 sendString(str) {
651c23ec 184 this.send(str.split('').map(chr => chr.charCodeAt(0)));
0e4808bf 185 }
6d6f0db0
SR
186
187 // Event Handlers
0e4808bf 188 off(evt) {
651c23ec 189 this._eventHandlers[evt] = () => {};
0e4808bf 190 }
6d6f0db0 191
0e4808bf 192 on(evt, handler) {
6d6f0db0 193 this._eventHandlers[evt] = handler;
0e4808bf 194 }
6d6f0db0 195
ea858bfa 196 _allocateBuffers() {
6d6f0db0
SR
197 this._rQ = new Uint8Array(this._rQbufferSize);
198 this._sQ = new Uint8Array(this._sQbufferSize);
0e4808bf 199 }
6d6f0db0 200
0e4808bf 201 init() {
ea858bfa 202 this._allocateBuffers();
6d6f0db0
SR
203 this._rQi = 0;
204 this._websocket = null;
0e4808bf 205 }
6d6f0db0 206
0e4808bf 207 open(uri, protocols) {
44d384b9
TS
208 this.attach(new WebSocket(uri, protocols));
209 }
210
211 attach(rawChannel) {
6d6f0db0
SR
212 this.init();
213
44d384b9
TS
214 // Must get object and class methods to be compatible with the tests.
215 const channelProps = [...Object.keys(rawChannel), ...Object.getOwnPropertyNames(Object.getPrototypeOf(rawChannel))];
216 for (let i = 0; i < rawChannelProps.length; i++) {
217 const prop = rawChannelProps[i];
218 if (channelProps.indexOf(prop) < 0) {
219 throw new Error('Raw channel missing property: ' + prop);
220 }
221 }
6d6f0db0 222
44d384b9
TS
223 this._websocket = rawChannel;
224 this._websocket.binaryType = "arraybuffer";
ea858bfa 225 this._websocket.onmessage = this._recvMessage.bind(this);
44d384b9
TS
226
227 const onOpen = () => {
6d6f0db0
SR
228 Log.Debug('>> WebSock.onopen');
229 if (this._websocket.protocol) {
230 Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
2cccf753 231 }
2cccf753 232
6d6f0db0
SR
233 this._eventHandlers.open();
234 Log.Debug("<< WebSock.onopen");
651c23ec 235 };
44d384b9
TS
236
237 // If the readyState cannot be found this defaults to assuming it's not open.
238 const isOpen = ReadyStates.OPEN.indexOf(this._websocket.readyState) >= 0;
239 if (isOpen) {
240 onOpen();
241 } else {
242 this._websocket.onopen = onOpen;
243 }
244
651c23ec 245 this._websocket.onclose = (e) => {
6d6f0db0
SR
246 Log.Debug(">> WebSock.onclose");
247 this._eventHandlers.close(e);
248 Log.Debug("<< WebSock.onclose");
651c23ec 249 };
44d384b9 250
651c23ec 251 this._websocket.onerror = (e) => {
6d6f0db0
SR
252 Log.Debug(">> WebSock.onerror: " + e);
253 this._eventHandlers.error(e);
254 Log.Debug("<< WebSock.onerror: " + e);
651c23ec 255 };
0e4808bf 256 }
6d6f0db0 257
0e4808bf 258 close() {
6d6f0db0 259 if (this._websocket) {
44d384b9
TS
260 if (ReadyStates.CONNECTING.indexOf(this._websocket.readyState) >= 0 ||
261 ReadyStates.OPEN.indexOf(this._websocket.readyState) >= 0) {
6d6f0db0
SR
262 Log.Info("Closing WebSocket connection");
263 this._websocket.close();
fcff386b 264 }
6d6f0db0 265
651c23ec 266 this._websocket.onmessage = () => {};
6d6f0db0 267 }
0e4808bf 268 }
6d6f0db0
SR
269
270 // private methods
ea858bfa 271 _encodeMessage() {
6d6f0db0
SR
272 // Put in a binary arraybuffer
273 // according to the spec, you can send ArrayBufferViews with the send method
274 return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
0e4808bf 275 }
6d6f0db0 276
e8614e20
SM
277 // We want to move all the unread data to the start of the queue,
278 // e.g. compacting.
279 // The function also expands the receive que if needed, and for
280 // performance reasons we combine these two actions to avoid
281 // unneccessary copying.
ea858bfa 282 _expandCompactRQ(minFit) {
7d755d10
JAD
283 // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place
284 // instead of resizing
ea858bfa
SM
285 const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8;
286 const resizeNeeded = this._rQbufferSize < requiredBufferSize;
7d755d10 287
6d6f0db0 288 if (resizeNeeded) {
7d755d10
JAD
289 // Make sure we always *at least* double the buffer size, and have at least space for 8x
290 // the current amount of data
ea858bfa 291 this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize);
6d6f0db0 292 }
40037b6a 293
6d6f0db0
SR
294 // we don't want to grow unboundedly
295 if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
296 this._rQbufferSize = MAX_RQ_GROW_SIZE;
ea858bfa 297 if (this._rQbufferSize - this.rQlen < minFit) {
8727f598 298 throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
40037b6a 299 }
6d6f0db0 300 }
40037b6a 301
6d6f0db0 302 if (resizeNeeded) {
ea858bfa 303 const oldRQbuffer = this._rQ.buffer;
6d6f0db0 304 this._rQ = new Uint8Array(this._rQbufferSize);
ea858bfa 305 this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi));
6d6f0db0 306 } else {
5b5b7474 307 this._rQ.copyWithin(0, this._rQi, this._rQlen);
6d6f0db0 308 }
40037b6a 309
6d6f0db0
SR
310 this._rQlen = this._rQlen - this._rQi;
311 this._rQi = 0;
0e4808bf 312 }
40037b6a 313
e8614e20 314 // push arraybuffer values onto the end of the receive que
ea858bfa 315 _DecodeMessage(data) {
2b5f94fa 316 const u8 = new Uint8Array(data);
6d6f0db0 317 if (u8.length > this._rQbufferSize - this._rQlen) {
ea858bfa 318 this._expandCompactRQ(u8.length);
6d6f0db0
SR
319 }
320 this._rQ.set(u8, this._rQlen);
321 this._rQlen += u8.length;
0e4808bf 322 }
fcff386b 323
ea858bfa
SM
324 _recvMessage(e) {
325 this._DecodeMessage(e.data);
8a189a62 326 if (this.rQlen > 0) {
1678bf86 327 this._eventHandlers.message();
1678bf86 328 if (this._rQlen == this._rQi) {
e8614e20
SM
329 // All data has now been processed, this means we
330 // can reset the receive queue.
1678bf86
PO
331 this._rQlen = 0;
332 this._rQi = 0;
2cccf753 333 }
1678bf86
PO
334 } else {
335 Log.Debug("Ignoring empty message");
72f1348b 336 }
6d6f0db0 337 }
0e4808bf 338}