]> git.proxmox.com Git - mirror_novnc.git/blob - core/websock.js
Use fat arrow functions `const foo = () => { ... };` for callbacks
[mirror_novnc.git] / core / websock.js
1 /*
2 * Websock: high-performance binary WebSockets
3 * Copyright (C) 2012 Joel Martin
4 * Licensed under MPL 2.0 (see LICENSE.txt)
5 *
6 * Websock is similar to the standard WebSocket object but with extra
7 * buffer handling.
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
15 import * as Log from './util/logging.js';
16
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.
20 const ENABLE_COPYWITHIN = false;
21 const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
22
23 export default class Websock {
24 constructor() {
25 this._websocket = null; // WebSocket object
26
27 this._rQi = 0; // Receive queue index
28 this._rQlen = 0; // Next write position in the receive queue
29 this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
30 this._rQmax = this._rQbufferSize / 8;
31 // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
32 this._rQ = null; // Receive queue
33
34 this._sQbufferSize = 1024 * 10; // 10 KiB
35 // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
36 this._sQlen = 0;
37 this._sQ = null; // Send queue
38
39 this._eventHandlers = {
40 message: () => {},
41 open: () => {},
42 close: () => {},
43 error: () => {}
44 };
45 }
46
47 // Getters and Setters
48 get_sQ() {
49 return this._sQ;
50 }
51
52 get_rQ() {
53 return this._rQ;
54 }
55
56 get_rQi() {
57 return this._rQi;
58 }
59
60 set_rQi(val) {
61 this._rQi = val;
62 }
63
64 // Receive Queue
65 rQlen() {
66 return this._rQlen - this._rQi;
67 }
68
69 rQpeek8() {
70 return this._rQ[this._rQi];
71 }
72
73 rQshift8() {
74 return this._rQ[this._rQi++];
75 }
76
77 rQskip8() {
78 this._rQi++;
79 }
80
81 rQskipBytes(num) {
82 this._rQi += num;
83 }
84
85 // TODO(directxman12): test performance with these vs a DataView
86 rQshift16() {
87 return (this._rQ[this._rQi++] << 8) +
88 this._rQ[this._rQi++];
89 }
90
91 rQshift32() {
92 return (this._rQ[this._rQi++] << 24) +
93 (this._rQ[this._rQi++] << 16) +
94 (this._rQ[this._rQi++] << 8) +
95 this._rQ[this._rQi++];
96 }
97
98 rQshiftStr(len) {
99 if (typeof(len) === 'undefined') { len = this.rQlen(); }
100 let str = "";
101 // Handle large arrays in steps to avoid long strings on the stack
102 for (let i = 0; i < len; i += 4096) {
103 let part = this.rQshiftBytes(Math.min(4096, len - i));
104 str += String.fromCharCode.apply(null, part);
105 }
106 return str;
107 }
108
109 rQshiftBytes(len) {
110 if (typeof(len) === 'undefined') { len = this.rQlen(); }
111 this._rQi += len;
112 return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
113 }
114
115 rQshiftTo(target, len) {
116 if (len === undefined) { len = this.rQlen(); }
117 // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
118 target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
119 this._rQi += len;
120 }
121
122 rQwhole() {
123 return new Uint8Array(this._rQ.buffer, 0, this._rQlen);
124 }
125
126 rQslice(start, end) {
127 if (end) {
128 return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
129 } else {
130 return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start);
131 }
132 }
133
134 // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
135 // to be available in the receive queue. Return true if we need to
136 // wait (and possibly print a debug message), otherwise false.
137 rQwait(msg, num, goback) {
138 const rQlen = this._rQlen - this._rQi; // Skip rQlen() function call
139 if (rQlen < num) {
140 if (goback) {
141 if (this._rQi < goback) {
142 throw new Error("rQwait cannot backup " + goback + " bytes");
143 }
144 this._rQi -= goback;
145 }
146 return true; // true means need more data
147 }
148 return false;
149 }
150
151 // Send Queue
152
153 flush() {
154 if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) {
155 this._websocket.send(this._encode_message());
156 this._sQlen = 0;
157 }
158 }
159
160 send(arr) {
161 this._sQ.set(arr, this._sQlen);
162 this._sQlen += arr.length;
163 this.flush();
164 }
165
166 send_string(str) {
167 this.send(str.split('').map(chr => chr.charCodeAt(0)));
168 }
169
170 // Event Handlers
171 off(evt) {
172 this._eventHandlers[evt] = () => {};
173 }
174
175 on(evt, handler) {
176 this._eventHandlers[evt] = handler;
177 }
178
179 _allocate_buffers() {
180 this._rQ = new Uint8Array(this._rQbufferSize);
181 this._sQ = new Uint8Array(this._sQbufferSize);
182 }
183
184 init() {
185 this._allocate_buffers();
186 this._rQi = 0;
187 this._websocket = null;
188 }
189
190 open(uri, protocols) {
191 this.init();
192
193 this._websocket = new WebSocket(uri, protocols);
194 this._websocket.binaryType = 'arraybuffer';
195
196 this._websocket.onmessage = this._recv_message.bind(this);
197 this._websocket.onopen = () => {
198 Log.Debug('>> WebSock.onopen');
199 if (this._websocket.protocol) {
200 Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
201 }
202
203 this._eventHandlers.open();
204 Log.Debug("<< WebSock.onopen");
205 };
206 this._websocket.onclose = (e) => {
207 Log.Debug(">> WebSock.onclose");
208 this._eventHandlers.close(e);
209 Log.Debug("<< WebSock.onclose");
210 };
211 this._websocket.onerror = (e) => {
212 Log.Debug(">> WebSock.onerror: " + e);
213 this._eventHandlers.error(e);
214 Log.Debug("<< WebSock.onerror: " + e);
215 };
216 }
217
218 close() {
219 if (this._websocket) {
220 if ((this._websocket.readyState === WebSocket.OPEN) ||
221 (this._websocket.readyState === WebSocket.CONNECTING)) {
222 Log.Info("Closing WebSocket connection");
223 this._websocket.close();
224 }
225
226 this._websocket.onmessage = () => {};
227 }
228 }
229
230 // private methods
231 _encode_message() {
232 // Put in a binary arraybuffer
233 // according to the spec, you can send ArrayBufferViews with the send method
234 return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
235 }
236
237 _expand_compact_rQ(min_fit) {
238 const resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2;
239 if (resizeNeeded) {
240 if (!min_fit) {
241 // just double the size if we need to do compaction
242 this._rQbufferSize *= 2;
243 } else {
244 // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8
245 this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8;
246 }
247 }
248
249 // we don't want to grow unboundedly
250 if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
251 this._rQbufferSize = MAX_RQ_GROW_SIZE;
252 if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) {
253 throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
254 }
255 }
256
257 if (resizeNeeded) {
258 const old_rQbuffer = this._rQ.buffer;
259 this._rQmax = this._rQbufferSize / 8;
260 this._rQ = new Uint8Array(this._rQbufferSize);
261 this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
262 } else {
263 if (ENABLE_COPYWITHIN) {
264 this._rQ.copyWithin(0, this._rQi);
265 } else {
266 this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
267 }
268 }
269
270 this._rQlen = this._rQlen - this._rQi;
271 this._rQi = 0;
272 }
273
274 _decode_message(data) {
275 // push arraybuffer values onto the end
276 const u8 = new Uint8Array(data);
277 if (u8.length > this._rQbufferSize - this._rQlen) {
278 this._expand_compact_rQ(u8.length);
279 }
280 this._rQ.set(u8, this._rQlen);
281 this._rQlen += u8.length;
282 }
283
284 _recv_message(e) {
285 this._decode_message(e.data);
286 if (this.rQlen() > 0) {
287 this._eventHandlers.message();
288 // Compact the receive queue
289 if (this._rQlen == this._rQi) {
290 this._rQlen = 0;
291 this._rQi = 0;
292 } else if (this._rQlen > this._rQmax) {
293 this._expand_compact_rQ();
294 }
295 } else {
296 Log.Debug("Ignoring empty message");
297 }
298 }
299 }