Initial commit
[yaffs-website] / node_modules / websocket-driver / lib / websocket / driver / client.js
1 'use strict';
2
3 var crypto     = require('crypto'),
4     url        = require('url'),
5     util       = require('util'),
6     HttpParser = require('../http_parser'),
7     Base       = require('./base'),
8     Hybi       = require('./hybi'),
9     Proxy      = require('./proxy');
10
11 var Client = function(_url, options) {
12   this.version = 'hybi-13';
13   Hybi.call(this, null, _url, options);
14
15   this.readyState = -1;
16   this._key       = Client.generateKey();
17   this._accept    = Hybi.generateAccept(this._key);
18   this._http      = new HttpParser('response');
19
20   var uri  = url.parse(this.url),
21       auth = uri.auth && new Buffer(uri.auth, 'utf8').toString('base64');
22
23   if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0)
24     throw new Error(this.url + ' is not a valid WebSocket URL');
25
26   this._pathname = (uri.pathname || '/') + (uri.search || '');
27
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');
33
34   if (this._protocols.length > 0)
35     this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', '));
36
37   if (auth)
38     this._headers.set('Authorization', 'Basic ' + auth);
39 };
40 util.inherits(Client, Hybi);
41
42 Client.generateKey = function() {
43   return crypto.randomBytes(16).toString('base64');
44 };
45
46 var instance = {
47   VALID_PROTOCOLS: ['ws:', 'wss:'],
48
49   proxy: function(origin, options) {
50     return new Proxy(this, origin, options);
51   },
52
53   start: function() {
54     if (this.readyState !== -1) return false;
55     this._write(this._handshakeRequest());
56     this.readyState = 0;
57     return true;
58   },
59
60   parse: function(chunk) {
61     if (this.readyState === 3) return;
62     if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk);
63
64     this._http.parse(chunk);
65     if (!this._http.isComplete()) return;
66
67     this._validateHandshake();
68     if (this.readyState === 3) return;
69
70     this._open();
71     this.parse(this._http.body);
72   },
73
74   _handshakeRequest: function() {
75     var extensions = this._extensions.generateOffer();
76     if (extensions)
77       this._headers.set('Sec-WebSocket-Extensions', extensions);
78
79     var start   = 'GET ' + this._pathname + ' HTTP/1.1',
80         headers = [start, this._headers.toString(), ''];
81
82     return new Buffer(headers.join('\r\n'), 'utf8');
83   },
84
85   _failHandshake: function(message) {
86     message = 'Error during WebSocket handshake: ' + message;
87     this.readyState = 3;
88     this.emit('error', new Error(message));
89     this.emit('close', new Base.CloseEvent(this.ERRORS.protocol_error, message));
90   },
91
92   _validateHandshake: function() {
93     this.statusCode = this._http.statusCode;
94     this.headers    = this._http.headers;
95
96     if (this._http.statusCode !== 101)
97       return this._failHandshake('Unexpected response code: ' + this._http.statusCode);
98
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'] || '';
104
105     if (upgrade === '')
106       return this._failHandshake("'Upgrade' header is missing");
107     if (upgrade.toLowerCase() !== 'websocket')
108       return this._failHandshake("'Upgrade' header value is not 'WebSocket'");
109
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'");
114
115     if (accept !== this._accept)
116       return this._failHandshake('Sec-WebSocket-Accept mismatch');
117
118     this.protocol = null;
119
120     if (protocol !== '') {
121       if (this._protocols.indexOf(protocol) < 0)
122         return this._failHandshake('Sec-WebSocket-Protocol mismatch');
123       else
124         this.protocol = protocol;
125     }
126
127     try {
128       this._extensions.activate(this.headers['sec-websocket-extensions']);
129     } catch (e) {
130       return this._failHandshake(e.message);
131     }
132   }
133 };
134
135 for (var key in instance)
136   Client.prototype[key] = instance[key];
137
138 module.exports = Client;