You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

386 lines
12 KiB

4 years ago
  1. 'use strict';
  2. require('./shims');
  3. var URL = require('url-parse')
  4. , inherits = require('inherits')
  5. , JSON3 = require('json3')
  6. , random = require('./utils/random')
  7. , escape = require('./utils/escape')
  8. , urlUtils = require('./utils/url')
  9. , eventUtils = require('./utils/event')
  10. , transport = require('./utils/transport')
  11. , objectUtils = require('./utils/object')
  12. , browser = require('./utils/browser')
  13. , log = require('./utils/log')
  14. , Event = require('./event/event')
  15. , EventTarget = require('./event/eventtarget')
  16. , loc = require('./location')
  17. , CloseEvent = require('./event/close')
  18. , TransportMessageEvent = require('./event/trans-message')
  19. , InfoReceiver = require('./info-receiver')
  20. ;
  21. var debug = function() {};
  22. if (process.env.NODE_ENV !== 'production') {
  23. debug = require('debug')('sockjs-client:main');
  24. }
  25. var transports;
  26. // follow constructor steps defined at http://dev.w3.org/html5/websockets/#the-websocket-interface
  27. function SockJS(url, protocols, options) {
  28. if (!(this instanceof SockJS)) {
  29. return new SockJS(url, protocols, options);
  30. }
  31. if (arguments.length < 1) {
  32. throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  33. }
  34. EventTarget.call(this);
  35. this.readyState = SockJS.CONNECTING;
  36. this.extensions = '';
  37. this.protocol = '';
  38. // non-standard extension
  39. options = options || {};
  40. if (options.protocols_whitelist) {
  41. log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  42. }
  43. this._transportsWhitelist = options.transports;
  44. this._transportOptions = options.transportOptions || {};
  45. this._timeout = options.timeout || 0;
  46. var sessionId = options.sessionId || 8;
  47. if (typeof sessionId === 'function') {
  48. this._generateSessionId = sessionId;
  49. } else if (typeof sessionId === 'number') {
  50. this._generateSessionId = function() {
  51. return random.string(sessionId);
  52. };
  53. } else {
  54. throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  55. }
  56. this._server = options.server || random.numberString(1000);
  57. // Step 1 of WS spec - parse and validate the url. Issue #8
  58. var parsedUrl = new URL(url);
  59. if (!parsedUrl.host || !parsedUrl.protocol) {
  60. throw new SyntaxError("The URL '" + url + "' is invalid");
  61. } else if (parsedUrl.hash) {
  62. throw new SyntaxError('The URL must not contain a fragment');
  63. } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
  64. throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  65. }
  66. var secure = parsedUrl.protocol === 'https:';
  67. // Step 2 - don't allow secure origin with an insecure protocol
  68. if (loc.protocol === 'https:' && !secure) {
  69. throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  70. }
  71. // Step 3 - check port access - no need here
  72. // Step 4 - parse protocols argument
  73. if (!protocols) {
  74. protocols = [];
  75. } else if (!Array.isArray(protocols)) {
  76. protocols = [protocols];
  77. }
  78. // Step 5 - check protocols argument
  79. var sortedProtocols = protocols.sort();
  80. sortedProtocols.forEach(function(proto, i) {
  81. if (!proto) {
  82. throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
  83. }
  84. if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
  85. throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
  86. }
  87. });
  88. // Step 6 - convert origin
  89. var o = urlUtils.getOrigin(loc.href);
  90. this._origin = o ? o.toLowerCase() : null;
  91. // remove the trailing slash
  92. parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));
  93. // store the sanitized url
  94. this.url = parsedUrl.href;
  95. debug('using url', this.url);
  96. // Step 7 - start connection in background
  97. // obtain server info
  98. // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  99. this._urlInfo = {
  100. nullOrigin: !browser.hasDomain()
  101. , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  102. , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  103. };
  104. this._ir = new InfoReceiver(this.url, this._urlInfo);
  105. this._ir.once('finish', this._receiveInfo.bind(this));
  106. }
  107. inherits(SockJS, EventTarget);
  108. function userSetCode(code) {
  109. return code === 1000 || (code >= 3000 && code <= 4999);
  110. }
  111. SockJS.prototype.close = function(code, reason) {
  112. // Step 1
  113. if (code && !userSetCode(code)) {
  114. throw new Error('InvalidAccessError: Invalid code');
  115. }
  116. // Step 2.4 states the max is 123 bytes, but we are just checking length
  117. if (reason && reason.length > 123) {
  118. throw new SyntaxError('reason argument has an invalid length');
  119. }
  120. // Step 3.1
  121. if (this.readyState === SockJS.CLOSING || this.readyState === SockJS.CLOSED) {
  122. return;
  123. }
  124. // TODO look at docs to determine how to set this
  125. var wasClean = true;
  126. this._close(code || 1000, reason || 'Normal closure', wasClean);
  127. };
  128. SockJS.prototype.send = function(data) {
  129. // #13 - convert anything non-string to string
  130. // TODO this currently turns objects into [object Object]
  131. if (typeof data !== 'string') {
  132. data = '' + data;
  133. }
  134. if (this.readyState === SockJS.CONNECTING) {
  135. throw new Error('InvalidStateError: The connection has not been established yet');
  136. }
  137. if (this.readyState !== SockJS.OPEN) {
  138. return;
  139. }
  140. this._transport.send(escape.quote(data));
  141. };
  142. SockJS.version = require('./version');
  143. SockJS.CONNECTING = 0;
  144. SockJS.OPEN = 1;
  145. SockJS.CLOSING = 2;
  146. SockJS.CLOSED = 3;
  147. SockJS.prototype._receiveInfo = function(info, rtt) {
  148. debug('_receiveInfo', rtt);
  149. this._ir = null;
  150. if (!info) {
  151. this._close(1002, 'Cannot connect to server');
  152. return;
  153. }
  154. // establish a round-trip timeout (RTO) based on the
  155. // round-trip time (RTT)
  156. this._rto = this.countRTO(rtt);
  157. // allow server to override url used for the actual transport
  158. this._transUrl = info.base_url ? info.base_url : this.url;
  159. info = objectUtils.extend(info, this._urlInfo);
  160. debug('info', info);
  161. // determine list of desired and supported transports
  162. var enabledTransports = transports.filterToEnabled(this._transportsWhitelist, info);
  163. this._transports = enabledTransports.main;
  164. debug(this._transports.length + ' enabled transports');
  165. this._connect();
  166. };
  167. SockJS.prototype._connect = function() {
  168. for (var Transport = this._transports.shift(); Transport; Transport = this._transports.shift()) {
  169. debug('attempt', Transport.transportName);
  170. if (Transport.needBody) {
  171. if (!global.document.body ||
  172. (typeof global.document.readyState !== 'undefined' &&
  173. global.document.readyState !== 'complete' &&
  174. global.document.readyState !== 'interactive')) {
  175. debug('waiting for body');
  176. this._transports.unshift(Transport);
  177. eventUtils.attachEvent('load', this._connect.bind(this));
  178. return;
  179. }
  180. }
  181. // calculate timeout based on RTO and round trips. Default to 5s
  182. var timeoutMs = Math.max(this._timeout, (this._rto * Transport.roundTrips) || 5000);
  183. this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);
  184. debug('using timeout', timeoutMs);
  185. var transportUrl = urlUtils.addPath(this._transUrl, '/' + this._server + '/' + this._generateSessionId());
  186. var options = this._transportOptions[Transport.transportName];
  187. debug('transport url', transportUrl);
  188. var transportObj = new Transport(transportUrl, this._transUrl, options);
  189. transportObj.on('message', this._transportMessage.bind(this));
  190. transportObj.once('close', this._transportClose.bind(this));
  191. transportObj.transportName = Transport.transportName;
  192. this._transport = transportObj;
  193. return;
  194. }
  195. this._close(2000, 'All transports failed', false);
  196. };
  197. SockJS.prototype._transportTimeout = function() {
  198. debug('_transportTimeout');
  199. if (this.readyState === SockJS.CONNECTING) {
  200. if (this._transport) {
  201. this._transport.close();
  202. }
  203. this._transportClose(2007, 'Transport timed out');
  204. }
  205. };
  206. SockJS.prototype._transportMessage = function(msg) {
  207. debug('_transportMessage', msg);
  208. var self = this
  209. , type = msg.slice(0, 1)
  210. , content = msg.slice(1)
  211. , payload
  212. ;
  213. // first check for messages that don't need a payload
  214. switch (type) {
  215. case 'o':
  216. this._open();
  217. return;
  218. case 'h':
  219. this.dispatchEvent(new Event('heartbeat'));
  220. debug('heartbeat', this.transport);
  221. return;
  222. }
  223. if (content) {
  224. try {
  225. payload = JSON3.parse(content);
  226. } catch (e) {
  227. debug('bad json', content);
  228. }
  229. }
  230. if (typeof payload === 'undefined') {
  231. debug('empty payload', content);
  232. return;
  233. }
  234. switch (type) {
  235. case 'a':
  236. if (Array.isArray(payload)) {
  237. payload.forEach(function(p) {
  238. debug('message', self.transport, p);
  239. self.dispatchEvent(new TransportMessageEvent(p));
  240. });
  241. }
  242. break;
  243. case 'm':
  244. debug('message', this.transport, payload);
  245. this.dispatchEvent(new TransportMessageEvent(payload));
  246. break;
  247. case 'c':
  248. if (Array.isArray(payload) && payload.length === 2) {
  249. this._close(payload[0], payload[1], true);
  250. }
  251. break;
  252. }
  253. };
  254. SockJS.prototype._transportClose = function(code, reason) {
  255. debug('_transportClose', this.transport, code, reason);
  256. if (this._transport) {
  257. this._transport.removeAllListeners();
  258. this._transport = null;
  259. this.transport = null;
  260. }
  261. if (!userSetCode(code) && code !== 2000 && this.readyState === SockJS.CONNECTING) {
  262. this._connect();
  263. return;
  264. }
  265. this._close(code, reason);
  266. };
  267. SockJS.prototype._open = function() {
  268. debug('_open', this._transport && this._transport.transportName, this.readyState);
  269. if (this.readyState === SockJS.CONNECTING) {
  270. if (this._transportTimeoutId) {
  271. clearTimeout(this._transportTimeoutId);
  272. this._transportTimeoutId = null;
  273. }
  274. this.readyState = SockJS.OPEN;
  275. this.transport = this._transport.transportName;
  276. this.dispatchEvent(new Event('open'));
  277. debug('connected', this.transport);
  278. } else {
  279. // The server might have been restarted, and lost track of our
  280. // connection.
  281. this._close(1006, 'Server lost session');
  282. }
  283. };
  284. SockJS.prototype._close = function(code, reason, wasClean) {
  285. debug('_close', this.transport, code, reason, wasClean, this.readyState);
  286. var forceFail = false;
  287. if (this._ir) {
  288. forceFail = true;
  289. this._ir.close();
  290. this._ir = null;
  291. }
  292. if (this._transport) {
  293. this._transport.close();
  294. this._transport = null;
  295. this.transport = null;
  296. }
  297. if (this.readyState === SockJS.CLOSED) {
  298. throw new Error('InvalidStateError: SockJS has already been closed');
  299. }
  300. this.readyState = SockJS.CLOSING;
  301. setTimeout(function() {
  302. this.readyState = SockJS.CLOSED;
  303. if (forceFail) {
  304. this.dispatchEvent(new Event('error'));
  305. }
  306. var e = new CloseEvent('close');
  307. e.wasClean = wasClean || false;
  308. e.code = code || 1000;
  309. e.reason = reason;
  310. this.dispatchEvent(e);
  311. this.onmessage = this.onclose = this.onerror = null;
  312. debug('disconnected');
  313. }.bind(this), 0);
  314. };
  315. // See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
  316. // and RFC 2988.
  317. SockJS.prototype.countRTO = function(rtt) {
  318. // In a local environment, when using IE8/9 and the `jsonp-polling`
  319. // transport the time needed to establish a connection (the time that pass
  320. // from the opening of the transport to the call of `_dispatchOpen`) is
  321. // around 200msec (the lower bound used in the article above) and this
  322. // causes spurious timeouts. For this reason we calculate a value slightly
  323. // larger than that used in the article.
  324. if (rtt > 100) {
  325. return 4 * rtt; // rto > 400msec
  326. }
  327. return 300 + rtt; // 300msec < rto <= 400msec
  328. };
  329. module.exports = function(availableTransports) {
  330. transports = transport(availableTransports);
  331. require('./iframe-bootstrap')(SockJS, availableTransports);
  332. return SockJS;
  333. };