main.js 12 KB

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