You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

142 lines
4.2 KiB

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