main.js 12 KB

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