websock.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. * Websock: high-performance buffering wrapper
  3. * Copyright (C) 2019 The noVNC Authors
  4. * Licensed under MPL 2.0 (see LICENSE.txt)
  5. *
  6. * Websock is similar to the standard WebSocket / RTCDataChannel object
  7. * but with extra 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. import * as Log from './util/logging.js';
  15. // this has performance issues in some versions Chromium, and
  16. // doesn't gain a tremendous amount of performance increase in Firefox
  17. // at the moment. It may be valuable to turn it on in the future.
  18. const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
  19. // Constants pulled from RTCDataChannelState enum
  20. // https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum
  21. const DataChannel = {
  22. CONNECTING: "connecting",
  23. OPEN: "open",
  24. CLOSING: "closing",
  25. CLOSED: "closed"
  26. };
  27. const ReadyStates = {
  28. CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING],
  29. OPEN: [WebSocket.OPEN, DataChannel.OPEN],
  30. CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING],
  31. CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED],
  32. };
  33. // Properties a raw channel must have, WebSocket and RTCDataChannel are two examples
  34. const rawChannelProps = [
  35. "send",
  36. "close",
  37. "binaryType",
  38. "onerror",
  39. "onmessage",
  40. "onopen",
  41. "protocol",
  42. "readyState",
  43. ];
  44. export default class Websock {
  45. constructor() {
  46. this._websocket = null; // WebSocket or RTCDataChannel object
  47. this._rQi = 0; // Receive queue index
  48. this._rQlen = 0; // Next write position in the receive queue
  49. this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
  50. // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
  51. this._rQ = null; // Receive queue
  52. this._sQbufferSize = 1024 * 10; // 10 KiB
  53. // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
  54. this._sQlen = 0;
  55. this._sQ = null; // Send queue
  56. this._eventHandlers = {
  57. message: () => {},
  58. open: () => {},
  59. close: () => {},
  60. error: () => {}
  61. };
  62. }
  63. // Getters and Setters
  64. get readyState() {
  65. let subState;
  66. if (this._websocket === null) {
  67. return "unused";
  68. }
  69. subState = this._websocket.readyState;
  70. if (ReadyStates.CONNECTING.includes(subState)) {
  71. return "connecting";
  72. } else if (ReadyStates.OPEN.includes(subState)) {
  73. return "open";
  74. } else if (ReadyStates.CLOSING.includes(subState)) {
  75. return "closing";
  76. } else if (ReadyStates.CLOSED.includes(subState)) {
  77. return "closed";
  78. }
  79. return "unknown";
  80. }
  81. // Receive Queue
  82. rQpeek8() {
  83. return this._rQ[this._rQi];
  84. }
  85. rQskipBytes(bytes) {
  86. this._rQi += bytes;
  87. }
  88. rQshift8() {
  89. return this._rQshift(1);
  90. }
  91. rQshift16() {
  92. return this._rQshift(2);
  93. }
  94. rQshift32() {
  95. return this._rQshift(4);
  96. }
  97. // TODO(directxman12): test performance with these vs a DataView
  98. _rQshift(bytes) {
  99. let res = 0;
  100. for (let byte = bytes - 1; byte >= 0; byte--) {
  101. res += this._rQ[this._rQi++] << (byte * 8);
  102. }
  103. return res >>> 0;
  104. }
  105. rQshiftStr(len) {
  106. let str = "";
  107. // Handle large arrays in steps to avoid long strings on the stack
  108. for (let i = 0; i < len; i += 4096) {
  109. let part = this.rQshiftBytes(Math.min(4096, len - i), false);
  110. str += String.fromCharCode.apply(null, part);
  111. }
  112. return str;
  113. }
  114. rQshiftBytes(len, copy=true) {
  115. this._rQi += len;
  116. if (copy) {
  117. return this._rQ.slice(this._rQi - len, this._rQi);
  118. } else {
  119. return this._rQ.subarray(this._rQi - len, this._rQi);
  120. }
  121. }
  122. rQshiftTo(target, len) {
  123. // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
  124. target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
  125. this._rQi += len;
  126. }
  127. rQpeekBytes(len, copy=true) {
  128. if (copy) {
  129. return this._rQ.slice(this._rQi, this._rQi + len);
  130. } else {
  131. return this._rQ.subarray(this._rQi, this._rQi + len);
  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. if (this._rQlen - this._rQi < num) {
  139. if (goback) {
  140. if (this._rQi < goback) {
  141. throw new Error("rQwait cannot backup " + goback + " bytes");
  142. }
  143. this._rQi -= goback;
  144. }
  145. return true; // true means need more data
  146. }
  147. return false;
  148. }
  149. // Send Queue
  150. sQpush8(num) {
  151. this._sQensureSpace(1);
  152. this._sQ[this._sQlen++] = num;
  153. }
  154. sQpush16(num) {
  155. this._sQensureSpace(2);
  156. this._sQ[this._sQlen++] = (num >> 8) & 0xff;
  157. this._sQ[this._sQlen++] = (num >> 0) & 0xff;
  158. }
  159. sQpush32(num) {
  160. this._sQensureSpace(4);
  161. this._sQ[this._sQlen++] = (num >> 24) & 0xff;
  162. this._sQ[this._sQlen++] = (num >> 16) & 0xff;
  163. this._sQ[this._sQlen++] = (num >> 8) & 0xff;
  164. this._sQ[this._sQlen++] = (num >> 0) & 0xff;
  165. }
  166. sQpushString(str) {
  167. let bytes = str.split('').map(chr => chr.charCodeAt(0));
  168. this.sQpushBytes(new Uint8Array(bytes));
  169. }
  170. sQpushBytes(bytes) {
  171. for (let offset = 0;offset < bytes.length;) {
  172. this._sQensureSpace(1);
  173. let chunkSize = this._sQbufferSize - this._sQlen;
  174. if (chunkSize > bytes.length - offset) {
  175. chunkSize = bytes.length - offset;
  176. }
  177. this._sQ.set(bytes.subarray(offset, offset + chunkSize), this._sQlen);
  178. this._sQlen += chunkSize;
  179. offset += chunkSize;
  180. }
  181. }
  182. flush() {
  183. if (this._sQlen > 0 && this.readyState === 'open') {
  184. this._websocket.send(new Uint8Array(this._sQ.buffer, 0, this._sQlen));
  185. this._sQlen = 0;
  186. }
  187. }
  188. _sQensureSpace(bytes) {
  189. if (this._sQbufferSize - this._sQlen < bytes) {
  190. this.flush();
  191. }
  192. }
  193. // Event Handlers
  194. off(evt) {
  195. this._eventHandlers[evt] = () => {};
  196. }
  197. on(evt, handler) {
  198. this._eventHandlers[evt] = handler;
  199. }
  200. _allocateBuffers() {
  201. this._rQ = new Uint8Array(this._rQbufferSize);
  202. this._sQ = new Uint8Array(this._sQbufferSize);
  203. }
  204. init() {
  205. this._allocateBuffers();
  206. this._rQi = 0;
  207. this._websocket = null;
  208. }
  209. open(uri, protocols) {
  210. this.attach(new WebSocket(uri, protocols));
  211. }
  212. attach(rawChannel) {
  213. this.init();
  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. }
  222. this._websocket = rawChannel;
  223. this._websocket.binaryType = "arraybuffer";
  224. this._websocket.onmessage = this._recvMessage.bind(this);
  225. this._websocket.onopen = () => {
  226. Log.Debug('>> WebSock.onopen');
  227. if (this._websocket.protocol) {
  228. Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
  229. }
  230. this._eventHandlers.open();
  231. Log.Debug("<< WebSock.onopen");
  232. };
  233. this._websocket.onclose = (e) => {
  234. Log.Debug(">> WebSock.onclose");
  235. this._eventHandlers.close(e);
  236. Log.Debug("<< WebSock.onclose");
  237. };
  238. this._websocket.onerror = (e) => {
  239. Log.Debug(">> WebSock.onerror: " + e);
  240. this._eventHandlers.error(e);
  241. Log.Debug("<< WebSock.onerror: " + e);
  242. };
  243. }
  244. close() {
  245. if (this._websocket) {
  246. if (this.readyState === 'connecting' ||
  247. this.readyState === 'open') {
  248. Log.Info("Closing WebSocket connection");
  249. this._websocket.close();
  250. }
  251. this._websocket.onmessage = () => {};
  252. }
  253. }
  254. // private methods
  255. // We want to move all the unread data to the start of the queue,
  256. // e.g. compacting.
  257. // The function also expands the receive que if needed, and for
  258. // performance reasons we combine these two actions to avoid
  259. // unnecessary copying.
  260. _expandCompactRQ(minFit) {
  261. // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place
  262. // instead of resizing
  263. const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8;
  264. const resizeNeeded = this._rQbufferSize < requiredBufferSize;
  265. if (resizeNeeded) {
  266. // Make sure we always *at least* double the buffer size, and have at least space for 8x
  267. // the current amount of data
  268. this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize);
  269. }
  270. // we don't want to grow unboundedly
  271. if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
  272. this._rQbufferSize = MAX_RQ_GROW_SIZE;
  273. if (this._rQbufferSize - (this._rQlen - this._rQi) < minFit) {
  274. throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
  275. }
  276. }
  277. if (resizeNeeded) {
  278. const oldRQbuffer = this._rQ.buffer;
  279. this._rQ = new Uint8Array(this._rQbufferSize);
  280. this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi));
  281. } else {
  282. this._rQ.copyWithin(0, this._rQi, this._rQlen);
  283. }
  284. this._rQlen = this._rQlen - this._rQi;
  285. this._rQi = 0;
  286. }
  287. // push arraybuffer values onto the end of the receive que
  288. _recvMessage(e) {
  289. if (this._rQlen == this._rQi) {
  290. // All data has now been processed, this means we
  291. // can reset the receive queue.
  292. this._rQlen = 0;
  293. this._rQi = 0;
  294. }
  295. const u8 = new Uint8Array(e.data);
  296. if (u8.length > this._rQbufferSize - this._rQlen) {
  297. this._expandCompactRQ(u8.length);
  298. }
  299. this._rQ.set(u8, this._rQlen);
  300. this._rQlen += u8.length;
  301. if (this._rQlen - this._rQi > 0) {
  302. this._eventHandlers.message();
  303. } else {
  304. Log.Debug("Ignoring empty message");
  305. }
  306. }
  307. }