main.js 12 KB

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