client.js 4.2 KB

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