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.

587 lines
15 KiB

4 years ago
  1. /**
  2. * Module dependencies.
  3. */
  4. var qs = require('querystring');
  5. var parse = require('url').parse;
  6. var base64id = require('base64id');
  7. var transports = require('./transports');
  8. var EventEmitter = require('events').EventEmitter;
  9. var Socket = require('./socket');
  10. var util = require('util');
  11. var debug = require('debug')('engine');
  12. var cookieMod = require('cookie');
  13. /**
  14. * Module exports.
  15. */
  16. module.exports = Server;
  17. /**
  18. * Server constructor.
  19. *
  20. * @param {Object} options
  21. * @api public
  22. */
  23. function Server (opts) {
  24. if (!(this instanceof Server)) {
  25. return new Server(opts);
  26. }
  27. this.clients = {};
  28. this.clientsCount = 0;
  29. opts = opts || {};
  30. this.wsEngine = opts.wsEngine || process.env.EIO_WS_ENGINE || 'ws';
  31. this.pingTimeout = opts.pingTimeout || 5000;
  32. this.pingInterval = opts.pingInterval || 25000;
  33. this.upgradeTimeout = opts.upgradeTimeout || 10000;
  34. this.maxHttpBufferSize = opts.maxHttpBufferSize || 10E7;
  35. this.transports = opts.transports || Object.keys(transports);
  36. this.allowUpgrades = false !== opts.allowUpgrades;
  37. this.allowRequest = opts.allowRequest;
  38. this.cookie = false !== opts.cookie ? (opts.cookie || 'io') : false;
  39. this.cookiePath = false !== opts.cookiePath ? (opts.cookiePath || '/') : false;
  40. this.cookieHttpOnly = false !== opts.cookieHttpOnly;
  41. this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || true) : false;
  42. this.httpCompression = false !== opts.httpCompression ? (opts.httpCompression || {}) : false;
  43. this.initialPacket = opts.initialPacket;
  44. var self = this;
  45. // initialize compression options
  46. ['perMessageDeflate', 'httpCompression'].forEach(function (type) {
  47. var compression = self[type];
  48. if (true === compression) self[type] = compression = {};
  49. if (compression && null == compression.threshold) {
  50. compression.threshold = 1024;
  51. }
  52. });
  53. this.init();
  54. }
  55. /**
  56. * Protocol errors mappings.
  57. */
  58. Server.errors = {
  59. UNKNOWN_TRANSPORT: 0,
  60. UNKNOWN_SID: 1,
  61. BAD_HANDSHAKE_METHOD: 2,
  62. BAD_REQUEST: 3,
  63. FORBIDDEN: 4
  64. };
  65. Server.errorMessages = {
  66. 0: 'Transport unknown',
  67. 1: 'Session ID unknown',
  68. 2: 'Bad handshake method',
  69. 3: 'Bad request',
  70. 4: 'Forbidden'
  71. };
  72. /**
  73. * Inherits from EventEmitter.
  74. */
  75. util.inherits(Server, EventEmitter);
  76. /**
  77. * Initialize websocket server
  78. *
  79. * @api private
  80. */
  81. Server.prototype.init = function () {
  82. if (!~this.transports.indexOf('websocket')) return;
  83. if (this.ws) this.ws.close();
  84. // add explicit require for bundlers like webpack
  85. var wsModule = this.wsEngine === 'ws' ? require('ws') : require(this.wsEngine);
  86. this.ws = new wsModule.Server({
  87. noServer: true,
  88. clientTracking: false,
  89. perMessageDeflate: this.perMessageDeflate,
  90. maxPayload: this.maxHttpBufferSize
  91. });
  92. };
  93. /**
  94. * Returns a list of available transports for upgrade given a certain transport.
  95. *
  96. * @return {Array}
  97. * @api public
  98. */
  99. Server.prototype.upgrades = function (transport) {
  100. if (!this.allowUpgrades) return [];
  101. return transports[transport].upgradesTo || [];
  102. };
  103. /**
  104. * Verifies a request.
  105. *
  106. * @param {http.IncomingMessage}
  107. * @return {Boolean} whether the request is valid
  108. * @api private
  109. */
  110. Server.prototype.verify = function (req, upgrade, fn) {
  111. // transport check
  112. var transport = req._query.transport;
  113. if (!~this.transports.indexOf(transport)) {
  114. debug('unknown transport "%s"', transport);
  115. return fn(Server.errors.UNKNOWN_TRANSPORT, false);
  116. }
  117. // 'Origin' header check
  118. var isOriginInvalid = checkInvalidHeaderChar(req.headers.origin);
  119. if (isOriginInvalid) {
  120. req.headers.origin = null;
  121. debug('origin header invalid');
  122. return fn(Server.errors.BAD_REQUEST, false);
  123. }
  124. // sid check
  125. var sid = req._query.sid;
  126. if (sid) {
  127. if (!this.clients.hasOwnProperty(sid)) {
  128. debug('unknown sid "%s"', sid);
  129. return fn(Server.errors.UNKNOWN_SID, false);
  130. }
  131. if (!upgrade && this.clients[sid].transport.name !== transport) {
  132. debug('bad request: unexpected transport without upgrade');
  133. return fn(Server.errors.BAD_REQUEST, false);
  134. }
  135. } else {
  136. // handshake is GET only
  137. if ('GET' !== req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false);
  138. if (!this.allowRequest) return fn(null, true);
  139. return this.allowRequest(req, fn);
  140. }
  141. fn(null, true);
  142. };
  143. /**
  144. * Prepares a request by processing the query string.
  145. *
  146. * @api private
  147. */
  148. Server.prototype.prepare = function (req) {
  149. // try to leverage pre-existing `req._query` (e.g: from connect)
  150. if (!req._query) {
  151. req._query = ~req.url.indexOf('?') ? qs.parse(parse(req.url).query) : {};
  152. }
  153. };
  154. /**
  155. * Closes all clients.
  156. *
  157. * @api public
  158. */
  159. Server.prototype.close = function () {
  160. debug('closing all open clients');
  161. for (var i in this.clients) {
  162. if (this.clients.hasOwnProperty(i)) {
  163. this.clients[i].close(true);
  164. }
  165. }
  166. if (this.ws) {
  167. debug('closing webSocketServer');
  168. this.ws.close();
  169. // don't delete this.ws because it can be used again if the http server starts listening again
  170. }
  171. return this;
  172. };
  173. /**
  174. * Handles an Engine.IO HTTP request.
  175. *
  176. * @param {http.IncomingMessage} request
  177. * @param {http.ServerResponse|http.OutgoingMessage} response
  178. * @api public
  179. */
  180. Server.prototype.handleRequest = function (req, res) {
  181. debug('handling "%s" http request "%s"', req.method, req.url);
  182. this.prepare(req);
  183. req.res = res;
  184. var self = this;
  185. this.verify(req, false, function (err, success) {
  186. if (!success) {
  187. sendErrorMessage(req, res, err);
  188. return;
  189. }
  190. if (req._query.sid) {
  191. debug('setting new request for existing client');
  192. self.clients[req._query.sid].transport.onRequest(req);
  193. } else {
  194. self.handshake(req._query.transport, req);
  195. }
  196. });
  197. };
  198. /**
  199. * Sends an Engine.IO Error Message
  200. *
  201. * @param {http.ServerResponse} response
  202. * @param {code} error code
  203. * @api private
  204. */
  205. function sendErrorMessage (req, res, code) {
  206. var headers = { 'Content-Type': 'application/json' };
  207. var isForbidden = !Server.errorMessages.hasOwnProperty(code);
  208. if (isForbidden) {
  209. res.writeHead(403, headers);
  210. res.end(JSON.stringify({
  211. code: Server.errors.FORBIDDEN,
  212. message: code || Server.errorMessages[Server.errors.FORBIDDEN]
  213. }));
  214. return;
  215. }
  216. if (req.headers.origin) {
  217. headers['Access-Control-Allow-Credentials'] = 'true';
  218. headers['Access-Control-Allow-Origin'] = req.headers.origin;
  219. } else {
  220. headers['Access-Control-Allow-Origin'] = '*';
  221. }
  222. if (res !== undefined) {
  223. res.writeHead(400, headers);
  224. res.end(JSON.stringify({
  225. code: code,
  226. message: Server.errorMessages[code]
  227. }));
  228. }
  229. }
  230. /**
  231. * generate a socket id.
  232. * Overwrite this method to generate your custom socket id
  233. *
  234. * @param {Object} request object
  235. * @api public
  236. */
  237. Server.prototype.generateId = function (req) {
  238. return base64id.generateId();
  239. };
  240. /**
  241. * Handshakes a new client.
  242. *
  243. * @param {String} transport name
  244. * @param {Object} request object
  245. * @api private
  246. */
  247. Server.prototype.handshake = function (transportName, req) {
  248. var id = this.generateId(req);
  249. debug('handshaking client "%s"', id);
  250. try {
  251. var transport = new transports[transportName](req);
  252. if ('polling' === transportName) {
  253. transport.maxHttpBufferSize = this.maxHttpBufferSize;
  254. transport.httpCompression = this.httpCompression;
  255. } else if ('websocket' === transportName) {
  256. transport.perMessageDeflate = this.perMessageDeflate;
  257. }
  258. if (req._query && req._query.b64) {
  259. transport.supportsBinary = false;
  260. } else {
  261. transport.supportsBinary = true;
  262. }
  263. } catch (e) {
  264. debug('error handshaking to transport "%s"', transportName);
  265. sendErrorMessage(req, req.res, Server.errors.BAD_REQUEST);
  266. return;
  267. }
  268. var socket = new Socket(id, this, transport, req);
  269. var self = this;
  270. if (false !== this.cookie) {
  271. transport.on('headers', function (headers) {
  272. headers['Set-Cookie'] = cookieMod.serialize(self.cookie, id,
  273. {
  274. path: self.cookiePath,
  275. httpOnly: self.cookiePath ? self.cookieHttpOnly : false,
  276. sameSite: true
  277. });
  278. });
  279. }
  280. transport.onRequest(req);
  281. this.clients[id] = socket;
  282. this.clientsCount++;
  283. socket.once('close', function () {
  284. delete self.clients[id];
  285. self.clientsCount--;
  286. });
  287. this.emit('connection', socket);
  288. };
  289. /**
  290. * Handles an Engine.IO HTTP Upgrade.
  291. *
  292. * @api public
  293. */
  294. Server.prototype.handleUpgrade = function (req, socket, upgradeHead) {
  295. this.prepare(req);
  296. var self = this;
  297. this.verify(req, true, function (err, success) {
  298. if (!success) {
  299. abortConnection(socket, err);
  300. return;
  301. }
  302. var head = Buffer.from(upgradeHead); // eslint-disable-line node/no-deprecated-api
  303. upgradeHead = null;
  304. // delegate to ws
  305. self.ws.handleUpgrade(req, socket, head, function (conn) {
  306. self.onWebSocket(req, conn);
  307. });
  308. });
  309. };
  310. /**
  311. * Called upon a ws.io connection.
  312. *
  313. * @param {ws.Socket} websocket
  314. * @api private
  315. */
  316. Server.prototype.onWebSocket = function (req, socket) {
  317. socket.on('error', onUpgradeError);
  318. if (transports[req._query.transport] !== undefined && !transports[req._query.transport].prototype.handlesUpgrades) {
  319. debug('transport doesnt handle upgraded requests');
  320. socket.close();
  321. return;
  322. }
  323. // get client id
  324. var id = req._query.sid;
  325. // keep a reference to the ws.Socket
  326. req.websocket = socket;
  327. if (id) {
  328. var client = this.clients[id];
  329. if (!client) {
  330. debug('upgrade attempt for closed client');
  331. socket.close();
  332. } else if (client.upgrading) {
  333. debug('transport has already been trying to upgrade');
  334. socket.close();
  335. } else if (client.upgraded) {
  336. debug('transport had already been upgraded');
  337. socket.close();
  338. } else {
  339. debug('upgrading existing transport');
  340. // transport error handling takes over
  341. socket.removeListener('error', onUpgradeError);
  342. var transport = new transports[req._query.transport](req);
  343. if (req._query && req._query.b64) {
  344. transport.supportsBinary = false;
  345. } else {
  346. transport.supportsBinary = true;
  347. }
  348. transport.perMessageDeflate = this.perMessageDeflate;
  349. client.maybeUpgrade(transport);
  350. }
  351. } else {
  352. // transport error handling takes over
  353. socket.removeListener('error', onUpgradeError);
  354. this.handshake(req._query.transport, req);
  355. }
  356. function onUpgradeError () {
  357. debug('websocket error before upgrade');
  358. // socket.close() not needed
  359. }
  360. };
  361. /**
  362. * Captures upgrade requests for a http.Server.
  363. *
  364. * @param {http.Server} server
  365. * @param {Object} options
  366. * @api public
  367. */
  368. Server.prototype.attach = function (server, options) {
  369. var self = this;
  370. options = options || {};
  371. var path = (options.path || '/engine.io').replace(/\/$/, '');
  372. var destroyUpgradeTimeout = options.destroyUpgradeTimeout || 1000;
  373. // normalize path
  374. path += '/';
  375. function check (req) {
  376. if ('OPTIONS' === req.method && false === options.handlePreflightRequest) {
  377. return false;
  378. }
  379. return path === req.url.substr(0, path.length);
  380. }
  381. // cache and clean up listeners
  382. var listeners = server.listeners('request').slice(0);
  383. server.removeAllListeners('request');
  384. server.on('close', self.close.bind(self));
  385. server.on('listening', self.init.bind(self));
  386. // add request handler
  387. server.on('request', function (req, res) {
  388. if (check(req)) {
  389. debug('intercepting request for path "%s"', path);
  390. if ('OPTIONS' === req.method && 'function' === typeof options.handlePreflightRequest) {
  391. options.handlePreflightRequest.call(server, req, res);
  392. } else {
  393. self.handleRequest(req, res);
  394. }
  395. } else {
  396. for (var i = 0, l = listeners.length; i < l; i++) {
  397. listeners[i].call(server, req, res);
  398. }
  399. }
  400. });
  401. if (~self.transports.indexOf('websocket')) {
  402. server.on('upgrade', function (req, socket, head) {
  403. if (check(req)) {
  404. self.handleUpgrade(req, socket, head);
  405. } else if (false !== options.destroyUpgrade) {
  406. // default node behavior is to disconnect when no handlers
  407. // but by adding a handler, we prevent that
  408. // and if no eio thing handles the upgrade
  409. // then the socket needs to die!
  410. setTimeout(function () {
  411. if (socket.writable && socket.bytesWritten <= 0) {
  412. return socket.end();
  413. }
  414. }, destroyUpgradeTimeout);
  415. }
  416. });
  417. }
  418. };
  419. /**
  420. * Closes the connection
  421. *
  422. * @param {net.Socket} socket
  423. * @param {code} error code
  424. * @api private
  425. */
  426. function abortConnection (socket, code) {
  427. socket.on('error', () => {
  428. debug('ignoring error from closed connection');
  429. });
  430. if (socket.writable) {
  431. var message = Server.errorMessages.hasOwnProperty(code) ? Server.errorMessages[code] : String(code || '');
  432. var length = Buffer.byteLength(message);
  433. socket.write(
  434. 'HTTP/1.1 400 Bad Request\r\n' +
  435. 'Connection: close\r\n' +
  436. 'Content-type: text/html\r\n' +
  437. 'Content-Length: ' + length + '\r\n' +
  438. '\r\n' +
  439. message
  440. );
  441. }
  442. socket.destroy();
  443. }
  444. /* eslint-disable */
  445. /**
  446. * From https://github.com/nodejs/node/blob/v8.4.0/lib/_http_common.js#L303-L354
  447. *
  448. * True if val contains an invalid field-vchar
  449. * field-value = *( field-content / obs-fold )
  450. * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
  451. * field-vchar = VCHAR / obs-text
  452. *
  453. * checkInvalidHeaderChar() is currently designed to be inlinable by v8,
  454. * so take care when making changes to the implementation so that the source
  455. * code size does not exceed v8's default max_inlined_source_size setting.
  456. **/
  457. var validHdrChars = [
  458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, // 0 - 15
  459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
  460. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 32 - 47
  461. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 63
  462. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
  463. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 95
  464. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
  465. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 112 - 127
  466. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 128 ...
  467. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  468. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  469. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  470. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  471. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  472. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  473. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // ... 255
  474. ];
  475. function checkInvalidHeaderChar(val) {
  476. val += '';
  477. if (val.length < 1)
  478. return false;
  479. if (!validHdrChars[val.charCodeAt(0)]) {
  480. debug('invalid header, index 0, char "%s"', val.charCodeAt(0));
  481. return true;
  482. }
  483. if (val.length < 2)
  484. return false;
  485. if (!validHdrChars[val.charCodeAt(1)]) {
  486. debug('invalid header, index 1, char "%s"', val.charCodeAt(1));
  487. return true;
  488. }
  489. if (val.length < 3)
  490. return false;
  491. if (!validHdrChars[val.charCodeAt(2)]) {
  492. debug('invalid header, index 2, char "%s"', val.charCodeAt(2));
  493. return true;
  494. }
  495. if (val.length < 4)
  496. return false;
  497. if (!validHdrChars[val.charCodeAt(3)]) {
  498. debug('invalid header, index 3, char "%s"', val.charCodeAt(3));
  499. return true;
  500. }
  501. for (var i = 4; i < val.length; ++i) {
  502. if (!validHdrChars[val.charCodeAt(i)]) {
  503. debug('invalid header, index "%i", char "%s"', i, val.charCodeAt(i));
  504. return true;
  505. }
  506. }
  507. return false;
  508. }