3 var crypto = require('crypto'),
5 util = require('util'),
6 HttpParser = require('../http_parser'),
7 Base = require('./base'),
8 Hybi = require('./hybi'),
9 Proxy = require('./proxy');
11 var Client = function(_url, options) {
12 this.version = 'hybi-13';
13 Hybi.call(this, null, _url, options);
16 this._key = Client.generateKey();
17 this._accept = Hybi.generateAccept(this._key);
18 this._http = new HttpParser('response');
20 var uri = url.parse(this.url),
21 auth = uri.auth && new Buffer(uri.auth, 'utf8').toString('base64');
23 if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0)
24 throw new Error(this.url + ' is not a valid WebSocket URL');
26 this._pathname = (uri.pathname || '/') + (uri.search || '');
28 this._headers.set('Host', uri.host);
29 this._headers.set('Upgrade', 'websocket');
30 this._headers.set('Connection', 'Upgrade');
31 this._headers.set('Sec-WebSocket-Key', this._key);
32 this._headers.set('Sec-WebSocket-Version', '13');
34 if (this._protocols.length > 0)
35 this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', '));
38 this._headers.set('Authorization', 'Basic ' + auth);
40 util.inherits(Client, Hybi);
42 Client.generateKey = function() {
43 return crypto.randomBytes(16).toString('base64');
47 VALID_PROTOCOLS: ['ws:', 'wss:'],
49 proxy: function(origin, options) {
50 return new Proxy(this, origin, options);
54 if (this.readyState !== -1) return false;
55 this._write(this._handshakeRequest());
60 parse: function(chunk) {
61 if (this.readyState === 3) return;
62 if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk);
64 this._http.parse(chunk);
65 if (!this._http.isComplete()) return;
67 this._validateHandshake();
68 if (this.readyState === 3) return;
71 this.parse(this._http.body);
74 _handshakeRequest: function() {
75 var extensions = this._extensions.generateOffer();
77 this._headers.set('Sec-WebSocket-Extensions', extensions);
79 var start = 'GET ' + this._pathname + ' HTTP/1.1',
80 headers = [start, this._headers.toString(), ''];
82 return new Buffer(headers.join('\r\n'), 'utf8');
85 _failHandshake: function(message) {
86 message = 'Error during WebSocket handshake: ' + message;
88 this.emit('error', new Error(message));
89 this.emit('close', new Base.CloseEvent(this.ERRORS.protocol_error, message));
92 _validateHandshake: function() {
93 this.statusCode = this._http.statusCode;
94 this.headers = this._http.headers;
96 if (this._http.statusCode !== 101)
97 return this._failHandshake('Unexpected response code: ' + this._http.statusCode);
99 var headers = this._http.headers,
100 upgrade = headers['upgrade'] || '',
101 connection = headers['connection'] || '',
102 accept = headers['sec-websocket-accept'] || '',
103 protocol = headers['sec-websocket-protocol'] || '';
106 return this._failHandshake("'Upgrade' header is missing");
107 if (upgrade.toLowerCase() !== 'websocket')
108 return this._failHandshake("'Upgrade' header value is not 'WebSocket'");
110 if (connection === '')
111 return this._failHandshake("'Connection' header is missing");
112 if (connection.toLowerCase() !== 'upgrade')
113 return this._failHandshake("'Connection' header value is not 'Upgrade'");
115 if (accept !== this._accept)
116 return this._failHandshake('Sec-WebSocket-Accept mismatch');
118 this.protocol = null;
120 if (protocol !== '') {
121 if (this._protocols.indexOf(protocol) < 0)
122 return this._failHandshake('Sec-WebSocket-Protocol mismatch');
124 this.protocol = protocol;
128 this._extensions.activate(this.headers['sec-websocket-extensions']);
130 return this._failHandshake(e.message);
135 for (var key in instance)
136 Client.prototype[key] = instance[key];
138 module.exports = Client;