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