Projekt

Obecné

Profil

Stáhnout (11.8 KB) Statistiky
| Větev: | Revize:
1
'use strict';
2

    
3
require('./shims');
4

    
5
var URL = require('url-parse')
6
  , inherits = require('inherits')
7
  , JSON3 = require('json3')
8
  , random = require('./utils/random')
9
  , escape = require('./utils/escape')
10
  , urlUtils = require('./utils/url')
11
  , eventUtils = require('./utils/event')
12
  , transport = require('./utils/transport')
13
  , objectUtils = require('./utils/object')
14
  , browser = require('./utils/browser')
15
  , log = require('./utils/log')
16
  , Event = require('./event/event')
17
  , EventTarget = require('./event/eventtarget')
18
  , loc = require('./location')
19
  , CloseEvent = require('./event/close')
20
  , TransportMessageEvent = require('./event/trans-message')
21
  , InfoReceiver = require('./info-receiver')
22
  ;
23

    
24
var debug = function() {};
25
if (process.env.NODE_ENV !== 'production') {
26
  debug = require('debug')('sockjs-client:main');
27
}
28

    
29
var transports;
30

    
31
// follow constructor steps defined at http://dev.w3.org/html5/websockets/#the-websocket-interface
32
function SockJS(url, protocols, options) {
33
  if (!(this instanceof SockJS)) {
34
    return new SockJS(url, protocols, options);
35
  }
36
  if (arguments.length < 1) {
37
    throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
38
  }
39
  EventTarget.call(this);
40

    
41
  this.readyState = SockJS.CONNECTING;
42
  this.extensions = '';
43
  this.protocol = '';
44

    
45
  // non-standard extension
46
  options = options || {};
47
  if (options.protocols_whitelist) {
48
    log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
49
  }
50
  this._transportsWhitelist = options.transports;
51
  this._transportOptions = options.transportOptions || {};
52
  this._timeout = options.timeout || 0;
53

    
54
  var sessionId = options.sessionId || 8;
55
  if (typeof sessionId === 'function') {
56
    this._generateSessionId = sessionId;
57
  } else if (typeof sessionId === 'number') {
58
    this._generateSessionId = function() {
59
      return random.string(sessionId);
60
    };
61
  } else {
62
    throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
63
  }
64

    
65
  this._server = options.server || random.numberString(1000);
66

    
67
  // Step 1 of WS spec - parse and validate the url. Issue #8
68
  var parsedUrl = new URL(url);
69
  if (!parsedUrl.host || !parsedUrl.protocol) {
70
    throw new SyntaxError("The URL '" + url + "' is invalid");
71
  } else if (parsedUrl.hash) {
72
    throw new SyntaxError('The URL must not contain a fragment');
73
  } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
74
    throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
75
  }
76

    
77
  var secure = parsedUrl.protocol === 'https:';
78
  // Step 2 - don't allow secure origin with an insecure protocol
79
  if (loc.protocol === 'https:' && !secure) {
80
    throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
81
  }
82

    
83
  // Step 3 - check port access - no need here
84
  // Step 4 - parse protocols argument
85
  if (!protocols) {
86
    protocols = [];
87
  } else if (!Array.isArray(protocols)) {
88
    protocols = [protocols];
89
  }
90

    
91
  // Step 5 - check protocols argument
92
  var sortedProtocols = protocols.sort();
93
  sortedProtocols.forEach(function(proto, i) {
94
    if (!proto) {
95
      throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
96
    }
97
    if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
98
      throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
99
    }
100
  });
101

    
102
  // Step 6 - convert origin
103
  var o = urlUtils.getOrigin(loc.href);
104
  this._origin = o ? o.toLowerCase() : null;
105

    
106
  // remove the trailing slash
107
  parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));
108

    
109
  // store the sanitized url
110
  this.url = parsedUrl.href;
111
  debug('using url', this.url);
112

    
113
  // Step 7 - start connection in background
114
  // obtain server info
115
  // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
116
  this._urlInfo = {
117
    nullOrigin: !browser.hasDomain()
118
  , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
119
  , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
120
  };
121

    
122
  this._ir = new InfoReceiver(this.url, this._urlInfo);
123
  this._ir.once('finish', this._receiveInfo.bind(this));
124
}
125

    
126
inherits(SockJS, EventTarget);
127

    
128
function userSetCode(code) {
129
  return code === 1000 || (code >= 3000 && code <= 4999);
130
}
131

    
132
SockJS.prototype.close = function(code, reason) {
133
  // Step 1
134
  if (code && !userSetCode(code)) {
135
    throw new Error('InvalidAccessError: Invalid code');
136
  }
137
  // Step 2.4 states the max is 123 bytes, but we are just checking length
138
  if (reason && reason.length > 123) {
139
    throw new SyntaxError('reason argument has an invalid length');
140
  }
141

    
142
  // Step 3.1
143
  if (this.readyState === SockJS.CLOSING || this.readyState === SockJS.CLOSED) {
144
    return;
145
  }
146

    
147
  // TODO look at docs to determine how to set this
148
  var wasClean = true;
149
  this._close(code || 1000, reason || 'Normal closure', wasClean);
150
};
151

    
152
SockJS.prototype.send = function(data) {
153
  // #13 - convert anything non-string to string
154
  // TODO this currently turns objects into [object Object]
155
  if (typeof data !== 'string') {
156
    data = '' + data;
157
  }
158
  if (this.readyState === SockJS.CONNECTING) {
159
    throw new Error('InvalidStateError: The connection has not been established yet');
160
  }
161
  if (this.readyState !== SockJS.OPEN) {
162
    return;
163
  }
164
  this._transport.send(escape.quote(data));
165
};
166

    
167
SockJS.version = require('./version');
168

    
169
SockJS.CONNECTING = 0;
170
SockJS.OPEN = 1;
171
SockJS.CLOSING = 2;
172
SockJS.CLOSED = 3;
173

    
174
SockJS.prototype._receiveInfo = function(info, rtt) {
175
  debug('_receiveInfo', rtt);
176
  this._ir = null;
177
  if (!info) {
178
    this._close(1002, 'Cannot connect to server');
179
    return;
180
  }
181

    
182
  // establish a round-trip timeout (RTO) based on the
183
  // round-trip time (RTT)
184
  this._rto = this.countRTO(rtt);
185
  // allow server to override url used for the actual transport
186
  this._transUrl = info.base_url ? info.base_url : this.url;
187
  info = objectUtils.extend(info, this._urlInfo);
188
  debug('info', info);
189
  // determine list of desired and supported transports
190
  var enabledTransports = transports.filterToEnabled(this._transportsWhitelist, info);
191
  this._transports = enabledTransports.main;
192
  debug(this._transports.length + ' enabled transports');
193

    
194
  this._connect();
195
};
196

    
197
SockJS.prototype._connect = function() {
198
  for (var Transport = this._transports.shift(); Transport; Transport = this._transports.shift()) {
199
    debug('attempt', Transport.transportName);
200
    if (Transport.needBody) {
201
      if (!global.document.body ||
202
          (typeof global.document.readyState !== 'undefined' &&
203
            global.document.readyState !== 'complete' &&
204
            global.document.readyState !== 'interactive')) {
205
        debug('waiting for body');
206
        this._transports.unshift(Transport);
207
        eventUtils.attachEvent('load', this._connect.bind(this));
208
        return;
209
      }
210
    }
211

    
212
    // calculate timeout based on RTO and round trips. Default to 5s
213
    var timeoutMs = Math.max(this._timeout, (this._rto * Transport.roundTrips) || 5000);
214
    this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);
215
    debug('using timeout', timeoutMs);
216

    
217
    var transportUrl = urlUtils.addPath(this._transUrl, '/' + this._server + '/' + this._generateSessionId());
218
    var options = this._transportOptions[Transport.transportName];
219
    debug('transport url', transportUrl);
220
    var transportObj = new Transport(transportUrl, this._transUrl, options);
221
    transportObj.on('message', this._transportMessage.bind(this));
222
    transportObj.once('close', this._transportClose.bind(this));
223
    transportObj.transportName = Transport.transportName;
224
    this._transport = transportObj;
225

    
226
    return;
227
  }
228
  this._close(2000, 'All transports failed', false);
229
};
230

    
231
SockJS.prototype._transportTimeout = function() {
232
  debug('_transportTimeout');
233
  if (this.readyState === SockJS.CONNECTING) {
234
    if (this._transport) {
235
      this._transport.close();
236
    }
237

    
238
    this._transportClose(2007, 'Transport timed out');
239
  }
240
};
241

    
242
SockJS.prototype._transportMessage = function(msg) {
243
  debug('_transportMessage', msg);
244
  var self = this
245
    , type = msg.slice(0, 1)
246
    , content = msg.slice(1)
247
    , payload
248
    ;
249

    
250
  // first check for messages that don't need a payload
251
  switch (type) {
252
    case 'o':
253
      this._open();
254
      return;
255
    case 'h':
256
      this.dispatchEvent(new Event('heartbeat'));
257
      debug('heartbeat', this.transport);
258
      return;
259
  }
260

    
261
  if (content) {
262
    try {
263
      payload = JSON3.parse(content);
264
    } catch (e) {
265
      debug('bad json', content);
266
    }
267
  }
268

    
269
  if (typeof payload === 'undefined') {
270
    debug('empty payload', content);
271
    return;
272
  }
273

    
274
  switch (type) {
275
    case 'a':
276
      if (Array.isArray(payload)) {
277
        payload.forEach(function(p) {
278
          debug('message', self.transport, p);
279
          self.dispatchEvent(new TransportMessageEvent(p));
280
        });
281
      }
282
      break;
283
    case 'm':
284
      debug('message', this.transport, payload);
285
      this.dispatchEvent(new TransportMessageEvent(payload));
286
      break;
287
    case 'c':
288
      if (Array.isArray(payload) && payload.length === 2) {
289
        this._close(payload[0], payload[1], true);
290
      }
291
      break;
292
  }
293
};
294

    
295
SockJS.prototype._transportClose = function(code, reason) {
296
  debug('_transportClose', this.transport, code, reason);
297
  if (this._transport) {
298
    this._transport.removeAllListeners();
299
    this._transport = null;
300
    this.transport = null;
301
  }
302

    
303
  if (!userSetCode(code) && code !== 2000 && this.readyState === SockJS.CONNECTING) {
304
    this._connect();
305
    return;
306
  }
307

    
308
  this._close(code, reason);
309
};
310

    
311
SockJS.prototype._open = function() {
312
  debug('_open', this._transport && this._transport.transportName, this.readyState);
313
  if (this.readyState === SockJS.CONNECTING) {
314
    if (this._transportTimeoutId) {
315
      clearTimeout(this._transportTimeoutId);
316
      this._transportTimeoutId = null;
317
    }
318
    this.readyState = SockJS.OPEN;
319
    this.transport = this._transport.transportName;
320
    this.dispatchEvent(new Event('open'));
321
    debug('connected', this.transport);
322
  } else {
323
    // The server might have been restarted, and lost track of our
324
    // connection.
325
    this._close(1006, 'Server lost session');
326
  }
327
};
328

    
329
SockJS.prototype._close = function(code, reason, wasClean) {
330
  debug('_close', this.transport, code, reason, wasClean, this.readyState);
331
  var forceFail = false;
332

    
333
  if (this._ir) {
334
    forceFail = true;
335
    this._ir.close();
336
    this._ir = null;
337
  }
338
  if (this._transport) {
339
    this._transport.close();
340
    this._transport = null;
341
    this.transport = null;
342
  }
343

    
344
  if (this.readyState === SockJS.CLOSED) {
345
    throw new Error('InvalidStateError: SockJS has already been closed');
346
  }
347

    
348
  this.readyState = SockJS.CLOSING;
349
  setTimeout(function() {
350
    this.readyState = SockJS.CLOSED;
351

    
352
    if (forceFail) {
353
      this.dispatchEvent(new Event('error'));
354
    }
355

    
356
    var e = new CloseEvent('close');
357
    e.wasClean = wasClean || false;
358
    e.code = code || 1000;
359
    e.reason = reason;
360

    
361
    this.dispatchEvent(e);
362
    this.onmessage = this.onclose = this.onerror = null;
363
    debug('disconnected');
364
  }.bind(this), 0);
365
};
366

    
367
// See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
368
// and RFC 2988.
369
SockJS.prototype.countRTO = function(rtt) {
370
  // In a local environment, when using IE8/9 and the `jsonp-polling`
371
  // transport the time needed to establish a connection (the time that pass
372
  // from the opening of the transport to the call of `_dispatchOpen`) is
373
  // around 200msec (the lower bound used in the article above) and this
374
  // causes spurious timeouts. For this reason we calculate a value slightly
375
  // larger than that used in the article.
376
  if (rtt > 100) {
377
    return 4 * rtt; // rto > 400msec
378
  }
379
  return 300 + rtt; // 300msec < rto <= 400msec
380
};
381

    
382
module.exports = function(availableTransports) {
383
  transports = transport(availableTransports);
384
  require('./iframe-bootstrap')(SockJS, availableTransports);
385
  return SockJS;
386
};
(9-9/12)