Initial commit
[yaffs-website] / node_modules / faye-websocket / lib / faye / websocket / client.js
1 var util   = require('util'),
2     net    = require('net'),
3     tls    = require('tls'),
4     url    = require('url'),
5     driver = require('websocket-driver'),
6     API    = require('./api'),
7     Event  = require('./api/event');
8
9 var DEFAULT_PORTS    = {'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443},
10     SECURE_PROTOCOLS = ['https:', 'wss:'];
11
12 var Client = function(_url, protocols, options) {
13   options = options || {};
14
15   this.url     = _url;
16   this._driver = driver.client(this.url, {maxLength: options.maxLength, protocols: protocols});
17
18   ['open', 'error'].forEach(function(event) {
19     this._driver.on(event, function() {
20       self.headers    = self._driver.headers;
21       self.statusCode = self._driver.statusCode;
22     });
23   }, this);
24
25   var proxy     = options.proxy || {},
26       endpoint  = url.parse(proxy.origin || this.url),
27       port      = endpoint.port || DEFAULT_PORTS[endpoint.protocol],
28       secure    = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0,
29       onConnect = function() { self._onConnect() },
30       originTLS = options.tls || {},
31       socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS,
32       self      = this;
33
34   originTLS.ca = originTLS.ca || options.ca;
35
36   this._stream = secure
37                ? tls.connect(port, endpoint.hostname, socketTLS, onConnect)
38                : net.connect(port, endpoint.hostname, onConnect);
39
40   if (proxy.origin) this._configureProxy(proxy, originTLS);
41
42   API.call(this, options);
43 };
44 util.inherits(Client, API);
45
46 Client.prototype._onConnect = function() {
47   var worker = this._proxy || this._driver;
48   worker.start();
49 };
50
51 Client.prototype._configureProxy = function(proxy, originTLS) {
52   var uri    = url.parse(this.url),
53       secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0,
54       self   = this,
55       name;
56
57   this._proxy = this._driver.proxy(proxy.origin);
58
59   if (proxy.headers) {
60     for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]);
61   }
62
63   this._proxy.pipe(this._stream, {end: false});
64   this._stream.pipe(this._proxy);
65
66   this._proxy.on('connect', function() {
67     if (secure) {
68       var options = {socket: self._stream, servername: uri.hostname};
69       for (name in originTLS) options[name] = originTLS[name];
70       self._stream = tls.connect(options);
71       self._configureStream();
72     }
73     self._driver.io.pipe(self._stream);
74     self._stream.pipe(self._driver.io);
75     self._driver.start();
76   });
77
78   this._proxy.on('error', function(error) {
79     self._driver.emit('error', error);
80   });
81 };
82
83 module.exports = Client;