websock.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 Websock
  7. * enables communication with raw TCP sockets (i.e. the binary stream)
  8. * via websockify. This is accomplished by base64 encoding the data
  9. * stream between Websock and websockify.
  10. *
  11. * Websock has built-in receive queue buffering; the message event
  12. * does not contain actual data but is simply a notification that
  13. * there is new data available. Several rQ* methods are available to
  14. * read binary data off of the receive queue.
  15. */
  16. /*jslint browser: true, bitwise: false, plusplus: false */
  17. /*global Util, Base64 */
  18. // Load Flash WebSocket emulator if needed
  19. // To force WebSocket emulator even when native WebSocket available
  20. //window.WEB_SOCKET_FORCE_FLASH = true;
  21. // To enable WebSocket emulator debug:
  22. //window.WEB_SOCKET_DEBUG=1;
  23. if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) {
  24. Websock_native = true;
  25. } else if (window.MozWebSocket && !window.WEB_SOCKET_FORCE_FLASH) {
  26. Websock_native = true;
  27. window.WebSocket = window.MozWebSocket;
  28. } else {
  29. /* no builtin WebSocket so load web_socket.js */
  30. Websock_native = false;
  31. (function () {
  32. window.WEB_SOCKET_SWF_LOCATION = Util.get_include_uri() +
  33. "web-socket-js/WebSocketMain.swf";
  34. if (Util.Engine.trident) {
  35. Util.Debug("Forcing uncached load of WebSocketMain.swf");
  36. window.WEB_SOCKET_SWF_LOCATION += "?" + Math.random();
  37. }
  38. Util.load_scripts(["web-socket-js/swfobject.js",
  39. "web-socket-js/web_socket.js"]);
  40. }());
  41. }
  42. function Websock() {
  43. "use strict";
  44. var api = {}, // Public API
  45. websocket = null, // WebSocket object
  46. mode = 'base64', // Current WebSocket mode: 'binary', 'base64'
  47. rQ = [], // Receive queue
  48. rQi = 0, // Receive queue index
  49. rQmax = 10000, // Max receive queue size before compacting
  50. sQ = [], // Send queue
  51. eventHandlers = {
  52. 'message' : function() {},
  53. 'open' : function() {},
  54. 'close' : function() {},
  55. 'error' : function() {}
  56. },
  57. test_mode = false;
  58. //
  59. // Queue public functions
  60. //
  61. function get_sQ() {
  62. return sQ;
  63. }
  64. function get_rQ() {
  65. return rQ;
  66. }
  67. function get_rQi() {
  68. return rQi;
  69. }
  70. function set_rQi(val) {
  71. rQi = val;
  72. }
  73. function rQlen() {
  74. return rQ.length - rQi;
  75. }
  76. function rQpeek8() {
  77. return (rQ[rQi] );
  78. }
  79. function rQshift8() {
  80. return (rQ[rQi++] );
  81. }
  82. function rQunshift8(num) {
  83. if (rQi === 0) {
  84. rQ.unshift(num);
  85. } else {
  86. rQi -= 1;
  87. rQ[rQi] = num;
  88. }
  89. }
  90. function rQshift16() {
  91. return (rQ[rQi++] << 8) +
  92. (rQ[rQi++] );
  93. }
  94. function rQshift32() {
  95. return (rQ[rQi++] << 24) +
  96. (rQ[rQi++] << 16) +
  97. (rQ[rQi++] << 8) +
  98. (rQ[rQi++] );
  99. }
  100. function rQshiftStr(len) {
  101. if (typeof(len) === 'undefined') { len = rQlen(); }
  102. var arr = rQ.slice(rQi, rQi + len);
  103. rQi += len;
  104. return String.fromCharCode.apply(null, arr);
  105. }
  106. function rQshiftBytes(len) {
  107. if (typeof(len) === 'undefined') { len = rQlen(); }
  108. rQi += len;
  109. return rQ.slice(rQi-len, rQi);
  110. }
  111. function rQslice(start, end) {
  112. if (end) {
  113. return rQ.slice(rQi + start, rQi + end);
  114. } else {
  115. return rQ.slice(rQi + start);
  116. }
  117. }
  118. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  119. // to be available in the receive queue. Return true if we need to
  120. // wait (and possibly print a debug message), otherwise false.
  121. function rQwait(msg, num, goback) {
  122. var rQlen = rQ.length - rQi; // Skip rQlen() function call
  123. if (rQlen < num) {
  124. if (goback) {
  125. if (rQi < goback) {
  126. throw("rQwait cannot backup " + goback + " bytes");
  127. }
  128. rQi -= goback;
  129. }
  130. //Util.Debug(" waiting for " + (num-rQlen) +
  131. // " " + msg + " byte(s)");
  132. return true; // true means need more data
  133. }
  134. return false;
  135. }
  136. //
  137. // Private utility routines
  138. //
  139. function encode_message() {
  140. if (mode === 'binary') {
  141. // Put in a binary arraybuffer
  142. return (new Uint8Array(sQ)).buffer;
  143. } else {
  144. // base64 encode
  145. return Base64.encode(sQ);
  146. }
  147. }
  148. function decode_message(data) {
  149. //Util.Debug(">> decode_message: " + data);
  150. if (mode === 'binary') {
  151. // push arraybuffer values onto the end
  152. rQ.push.apply(rQ, (new Uint8Array(data)));
  153. } else {
  154. // base64 decode and concat to the end
  155. rQ = rQ.concat(Base64.decode(data, 0));
  156. }
  157. //Util.Debug(">> decode_message, rQ: " + rQ);
  158. }
  159. //
  160. // Public Send functions
  161. //
  162. function flush() {
  163. if (websocket.bufferedAmount !== 0) {
  164. Util.Debug("bufferedAmount: " + websocket.bufferedAmount);
  165. }
  166. if (websocket.bufferedAmount < api.maxBufferedAmount) {
  167. //Util.Debug("arr: " + arr);
  168. //Util.Debug("sQ: " + sQ);
  169. if (sQ.length > 0) {
  170. websocket.send(encode_message(sQ));
  171. sQ = [];
  172. }
  173. return true;
  174. } else {
  175. Util.Info("Delaying send, bufferedAmount: " +
  176. websocket.bufferedAmount);
  177. return false;
  178. }
  179. }
  180. // overridable for testing
  181. function send(arr) {
  182. //Util.Debug(">> send_array: " + arr);
  183. sQ = sQ.concat(arr);
  184. return flush();
  185. }
  186. function send_string(str) {
  187. //Util.Debug(">> send_string: " + str);
  188. api.send(str.split('').map(
  189. function (chr) { return chr.charCodeAt(0); } ) );
  190. }
  191. //
  192. // Other public functions
  193. function recv_message(e) {
  194. //Util.Debug(">> recv_message: " + e.data.length);
  195. try {
  196. decode_message(e.data);
  197. if (rQlen() > 0) {
  198. eventHandlers.message();
  199. // Compact the receive queue
  200. if (rQ.length > rQmax) {
  201. //Util.Debug("Compacting receive queue");
  202. rQ = rQ.slice(rQi);
  203. rQi = 0;
  204. }
  205. } else {
  206. Util.Debug("Ignoring empty message");
  207. }
  208. } catch (exc) {
  209. if (typeof exc.stack !== 'undefined') {
  210. Util.Warn("recv_message, caught exception: " + exc.stack);
  211. } else if (typeof exc.description !== 'undefined') {
  212. Util.Warn("recv_message, caught exception: " + exc.description);
  213. } else {
  214. Util.Warn("recv_message, caught exception:" + exc);
  215. }
  216. if (typeof exc.name !== 'undefined') {
  217. eventHandlers.error(exc.name + ": " + exc.message);
  218. } else {
  219. eventHandlers.error(exc);
  220. }
  221. }
  222. //Util.Debug("<< recv_message");
  223. }
  224. // Set event handlers
  225. function on(evt, handler) {
  226. eventHandlers[evt] = handler;
  227. }
  228. function init(protocols) {
  229. rQ = [];
  230. rQi = 0;
  231. sQ = [];
  232. websocket = null;
  233. var bt = false,
  234. wsbt = false,
  235. try_binary = false;
  236. // Check for full typed array support
  237. if (('Uint8Array' in window) &&
  238. ('set' in Uint8Array.prototype)) {
  239. bt = true;
  240. }
  241. // Check for full binary type support in WebSockets
  242. // TODO: this sucks, the property should exist on the prototype
  243. // but it does not.
  244. try {
  245. if (bt && ('binaryType' in (new WebSocket("ws://localhost:17523")))) {
  246. Util.Info("Detected binaryType support in WebSockets");
  247. wsbt = true;
  248. }
  249. } catch (exc) {
  250. // Just ignore failed test localhost connections
  251. }
  252. // Default protocols if not specified
  253. if (typeof(protocols) === "undefined") {
  254. if (wsbt) {
  255. protocols = ['binary', 'base64'];
  256. } else {
  257. protocols = 'base64';
  258. }
  259. }
  260. // If no binary support, make sure it was not requested
  261. if (!wsbt) {
  262. if (protocols === 'binary') {
  263. throw("WebSocket binary sub-protocol requested but not supported");
  264. }
  265. if (typeof(protocols) === "object") {
  266. var new_protocols = [];
  267. for (var i = 0; i < protocols.length; i++) {
  268. if (protocols[i] === 'binary') {
  269. Util.Error("Skipping unsupported WebSocket binary sub-protocol");
  270. } else {
  271. new_protocols.push(protocols[i]);
  272. }
  273. }
  274. if (new_protocols.length > 0) {
  275. protocols = new_protocols;
  276. } else {
  277. throw("Only WebSocket binary sub-protocol was requested and not supported.");
  278. }
  279. }
  280. }
  281. return protocols;
  282. }
  283. function open(uri, protocols) {
  284. protocols = init(protocols);
  285. if (test_mode) {
  286. websocket = {};
  287. } else {
  288. websocket = new WebSocket(uri, protocols);
  289. }
  290. websocket.onmessage = recv_message;
  291. websocket.onopen = function() {
  292. Util.Debug(">> WebSock.onopen");
  293. if (websocket.protocol) {
  294. mode = websocket.protocol;
  295. Util.Info("Server chose sub-protocol: " + websocket.protocol);
  296. } else {
  297. mode = 'base64';
  298. Util.Error("Server select no sub-protocol!: " + websocket.protocol);
  299. }
  300. if (mode === 'binary') {
  301. websocket.binaryType = 'arraybuffer';
  302. }
  303. eventHandlers.open();
  304. Util.Debug("<< WebSock.onopen");
  305. };
  306. websocket.onclose = function(e) {
  307. Util.Debug(">> WebSock.onclose");
  308. eventHandlers.close(e);
  309. Util.Debug("<< WebSock.onclose");
  310. };
  311. websocket.onerror = function(e) {
  312. Util.Debug(">> WebSock.onerror: " + e);
  313. eventHandlers.error(e);
  314. Util.Debug("<< WebSock.onerror");
  315. };
  316. }
  317. function close() {
  318. if (websocket) {
  319. if ((websocket.readyState === WebSocket.OPEN) ||
  320. (websocket.readyState === WebSocket.CONNECTING)) {
  321. Util.Info("Closing WebSocket connection");
  322. websocket.close();
  323. }
  324. websocket.onmessage = function (e) { return; };
  325. }
  326. }
  327. // Override internal functions for testing
  328. // Takes a send function, returns reference to recv function
  329. function testMode(override_send) {
  330. test_mode = true;
  331. api.send = override_send;
  332. api.close = function () {};
  333. return recv_message;
  334. }
  335. function constructor() {
  336. // Configuration settings
  337. api.maxBufferedAmount = 200;
  338. // Direct access to send and receive queues
  339. api.get_sQ = get_sQ;
  340. api.get_rQ = get_rQ;
  341. api.get_rQi = get_rQi;
  342. api.set_rQi = set_rQi;
  343. // Routines to read from the receive queue
  344. api.rQlen = rQlen;
  345. api.rQpeek8 = rQpeek8;
  346. api.rQshift8 = rQshift8;
  347. api.rQunshift8 = rQunshift8;
  348. api.rQshift16 = rQshift16;
  349. api.rQshift32 = rQshift32;
  350. api.rQshiftStr = rQshiftStr;
  351. api.rQshiftBytes = rQshiftBytes;
  352. api.rQslice = rQslice;
  353. api.rQwait = rQwait;
  354. api.flush = flush;
  355. api.send = send;
  356. api.send_string = send_string;
  357. api.on = on;
  358. api.init = init;
  359. api.open = open;
  360. api.close = close;
  361. api.testMode = testMode;
  362. return api;
  363. }
  364. return constructor();
  365. }