Front end of the Slack clone application.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*!
  2. * ws: a node.js websocket client
  3. * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
  4. * MIT Licensed
  5. */
  6. 'use strict';
  7. const safeBuffer = require('safe-buffer');
  8. const EventEmitter = require('events');
  9. const crypto = require('crypto');
  10. const Ultron = require('ultron');
  11. const http = require('http');
  12. const url = require('url');
  13. const PerMessageDeflate = require('./PerMessageDeflate');
  14. const Extensions = require('./Extensions');
  15. const constants = require('./Constants');
  16. const WebSocket = require('./WebSocket');
  17. const Buffer = safeBuffer.Buffer;
  18. /**
  19. * Class representing a WebSocket server.
  20. *
  21. * @extends EventEmitter
  22. */
  23. class WebSocketServer extends EventEmitter {
  24. /**
  25. * Create a `WebSocketServer` instance.
  26. *
  27. * @param {Object} options Configuration options
  28. * @param {String} options.host The hostname where to bind the server
  29. * @param {Number} options.port The port where to bind the server
  30. * @param {http.Server} options.server A pre-created HTTP/S server to use
  31. * @param {Function} options.verifyClient An hook to reject connections
  32. * @param {Function} options.handleProtocols An hook to handle protocols
  33. * @param {String} options.path Accept only connections matching this path
  34. * @param {Boolean} options.noServer Enable no server mode
  35. * @param {Boolean} options.clientTracking Specifies whether or not to track clients
  36. * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
  37. * @param {Number} options.maxPayload The maximum allowed message size
  38. * @param {Function} callback A listener for the `listening` event
  39. */
  40. constructor (options, callback) {
  41. super();
  42. options = Object.assign({
  43. maxPayload: 100 * 1024 * 1024,
  44. perMessageDeflate: false,
  45. handleProtocols: null,
  46. clientTracking: true,
  47. verifyClient: null,
  48. noServer: false,
  49. backlog: null, // use default (511 as implemented in net.js)
  50. server: null,
  51. host: null,
  52. path: null,
  53. port: null
  54. }, options);
  55. if (options.port == null && !options.server && !options.noServer) {
  56. throw new TypeError('missing or invalid options');
  57. }
  58. if (options.port != null) {
  59. this._server = http.createServer((req, res) => {
  60. const body = http.STATUS_CODES[426];
  61. res.writeHead(426, {
  62. 'Content-Length': body.length,
  63. 'Content-Type': 'text/plain'
  64. });
  65. res.end(body);
  66. });
  67. this._server.allowHalfOpen = false;
  68. this._server.listen(options.port, options.host, options.backlog, callback);
  69. } else if (options.server) {
  70. this._server = options.server;
  71. }
  72. if (this._server) {
  73. this._ultron = new Ultron(this._server);
  74. this._ultron.on('listening', () => this.emit('listening'));
  75. this._ultron.on('error', (err) => this.emit('error', err));
  76. this._ultron.on('upgrade', (req, socket, head) => {
  77. this.handleUpgrade(req, socket, head, (client) => {
  78. this.emit('connection', client, req);
  79. });
  80. });
  81. }
  82. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  83. if (options.clientTracking) this.clients = new Set();
  84. this.options = options;
  85. }
  86. /**
  87. * Close the server.
  88. *
  89. * @param {Function} cb Callback
  90. * @public
  91. */
  92. close (cb) {
  93. //
  94. // Terminate all associated clients.
  95. //
  96. if (this.clients) {
  97. for (const client of this.clients) client.terminate();
  98. }
  99. const server = this._server;
  100. if (server) {
  101. this._ultron.destroy();
  102. this._ultron = this._server = null;
  103. //
  104. // Close the http server if it was internally created.
  105. //
  106. if (this.options.port != null) return server.close(cb);
  107. }
  108. if (cb) cb();
  109. }
  110. /**
  111. * See if a given request should be handled by this server instance.
  112. *
  113. * @param {http.IncomingMessage} req Request object to inspect
  114. * @return {Boolean} `true` if the request is valid, else `false`
  115. * @public
  116. */
  117. shouldHandle (req) {
  118. if (this.options.path && url.parse(req.url).pathname !== this.options.path) {
  119. return false;
  120. }
  121. return true;
  122. }
  123. /**
  124. * Handle a HTTP Upgrade request.
  125. *
  126. * @param {http.IncomingMessage} req The request object
  127. * @param {net.Socket} socket The network socket between the server and client
  128. * @param {Buffer} head The first packet of the upgraded stream
  129. * @param {Function} cb Callback
  130. * @public
  131. */
  132. handleUpgrade (req, socket, head, cb) {
  133. socket.on('error', socketError);
  134. const version = +req.headers['sec-websocket-version'];
  135. const extensions = {};
  136. if (
  137. req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' ||
  138. !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) ||
  139. !this.shouldHandle(req)
  140. ) {
  141. return abortConnection(socket, 400);
  142. }
  143. if (this.options.perMessageDeflate) {
  144. const perMessageDeflate = new PerMessageDeflate(
  145. this.options.perMessageDeflate,
  146. true,
  147. this.options.maxPayload
  148. );
  149. try {
  150. const offers = Extensions.parse(
  151. req.headers['sec-websocket-extensions']
  152. );
  153. if (offers[PerMessageDeflate.extensionName]) {
  154. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  155. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  156. }
  157. } catch (err) {
  158. return abortConnection(socket, 400);
  159. }
  160. }
  161. var protocol = (req.headers['sec-websocket-protocol'] || '').split(/, */);
  162. //
  163. // Optionally call external protocol selection handler.
  164. //
  165. if (this.options.handleProtocols) {
  166. protocol = this.options.handleProtocols(protocol, req);
  167. if (protocol === false) return abortConnection(socket, 401);
  168. } else {
  169. protocol = protocol[0];
  170. }
  171. //
  172. // Optionally call external client verification handler.
  173. //
  174. if (this.options.verifyClient) {
  175. const info = {
  176. origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  177. secure: !!(req.connection.authorized || req.connection.encrypted),
  178. req
  179. };
  180. if (this.options.verifyClient.length === 2) {
  181. this.options.verifyClient(info, (verified, code, message) => {
  182. if (!verified) return abortConnection(socket, code || 401, message);
  183. this.completeUpgrade(
  184. protocol,
  185. extensions,
  186. version,
  187. req,
  188. socket,
  189. head,
  190. cb
  191. );
  192. });
  193. return;
  194. }
  195. if (!this.options.verifyClient(info)) return abortConnection(socket, 401);
  196. }
  197. this.completeUpgrade(protocol, extensions, version, req, socket, head, cb);
  198. }
  199. /**
  200. * Upgrade the connection to WebSocket.
  201. *
  202. * @param {String} protocol The chosen subprotocol
  203. * @param {Object} extensions The accepted extensions
  204. * @param {Number} version The WebSocket protocol version
  205. * @param {http.IncomingMessage} req The request object
  206. * @param {net.Socket} socket The network socket between the server and client
  207. * @param {Buffer} head The first packet of the upgraded stream
  208. * @param {Function} cb Callback
  209. * @private
  210. */
  211. completeUpgrade (protocol, extensions, version, req, socket, head, cb) {
  212. //
  213. // Destroy the socket if the client has already sent a FIN packet.
  214. //
  215. if (!socket.readable || !socket.writable) return socket.destroy();
  216. const key = crypto.createHash('sha1')
  217. .update(req.headers['sec-websocket-key'] + constants.GUID, 'binary')
  218. .digest('base64');
  219. const headers = [
  220. 'HTTP/1.1 101 Switching Protocols',
  221. 'Upgrade: websocket',
  222. 'Connection: Upgrade',
  223. `Sec-WebSocket-Accept: ${key}`
  224. ];
  225. if (protocol) headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  226. if (extensions[PerMessageDeflate.extensionName]) {
  227. const params = extensions[PerMessageDeflate.extensionName].params;
  228. const value = Extensions.format({
  229. [PerMessageDeflate.extensionName]: [params]
  230. });
  231. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  232. }
  233. //
  234. // Allow external modification/inspection of handshake headers.
  235. //
  236. this.emit('headers', headers, req);
  237. socket.write(headers.concat('\r\n').join('\r\n'));
  238. const client = new WebSocket([socket, head], null, {
  239. maxPayload: this.options.maxPayload,
  240. protocolVersion: version,
  241. extensions,
  242. protocol
  243. });
  244. if (this.clients) {
  245. this.clients.add(client);
  246. client.on('close', () => this.clients.delete(client));
  247. }
  248. socket.removeListener('error', socketError);
  249. cb(client);
  250. }
  251. }
  252. module.exports = WebSocketServer;
  253. /**
  254. * Handle premature socket errors.
  255. *
  256. * @private
  257. */
  258. function socketError () {
  259. this.destroy();
  260. }
  261. /**
  262. * Close the connection when preconditions are not fulfilled.
  263. *
  264. * @param {net.Socket} socket The socket of the upgrade request
  265. * @param {Number} code The HTTP response status code
  266. * @param {String} [message] The HTTP response body
  267. * @private
  268. */
  269. function abortConnection (socket, code, message) {
  270. if (socket.writable) {
  271. message = message || http.STATUS_CODES[code];
  272. socket.write(
  273. `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
  274. 'Connection: close\r\n' +
  275. 'Content-type: text/html\r\n' +
  276. `Content-Length: ${Buffer.byteLength(message)}\r\n` +
  277. '\r\n' +
  278. message
  279. );
  280. }
  281. socket.removeListener('error', socketError);
  282. socket.destroy();
  283. }