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