1 |
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const EventEmitter = require('events');
|
6 | const http = require('http');
|
7 | const { Duplex } = require('stream');
|
8 | const { createHash } = require('crypto');
|
9 |
|
10 | const extension = require('./extension');
|
11 | const PerMessageDeflate = require('./permessage-deflate');
|
12 | const subprotocol = require('./subprotocol');
|
13 | const WebSocket = require('./websocket');
|
14 | const { GUID, kWebSocket } = require('./constants');
|
15 |
|
16 | const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
17 |
|
18 | const RUNNING = 0;
|
19 | const CLOSING = 1;
|
20 | const CLOSED = 2;
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | class WebSocketServer extends EventEmitter {
|
28 | |
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | constructor(options, callback) {
|
60 | super();
|
61 |
|
62 | options = {
|
63 | allowSynchronousEvents: true,
|
64 | autoPong: true,
|
65 | maxPayload: 100 * 1024 * 1024,
|
66 | skipUTF8Validation: false,
|
67 | perMessageDeflate: false,
|
68 | handleProtocols: null,
|
69 | clientTracking: true,
|
70 | verifyClient: null,
|
71 | noServer: false,
|
72 | backlog: null,
|
73 | server: null,
|
74 | host: null,
|
75 | path: null,
|
76 | port: null,
|
77 | WebSocket,
|
78 | ...options
|
79 | };
|
80 |
|
81 | if (
|
82 | (options.port == null && !options.server && !options.noServer) ||
|
83 | (options.port != null && (options.server || options.noServer)) ||
|
84 | (options.server && options.noServer)
|
85 | ) {
|
86 | throw new TypeError(
|
87 | 'One and only one of the "port", "server", or "noServer" options ' +
|
88 | 'must be specified'
|
89 | );
|
90 | }
|
91 |
|
92 | if (options.port != null) {
|
93 | this._server = http.createServer((req, res) => {
|
94 | const body = http.STATUS_CODES[426];
|
95 |
|
96 | res.writeHead(426, {
|
97 | 'Content-Length': body.length,
|
98 | 'Content-Type': 'text/plain'
|
99 | });
|
100 | res.end(body);
|
101 | });
|
102 | this._server.listen(
|
103 | options.port,
|
104 | options.host,
|
105 | options.backlog,
|
106 | callback
|
107 | );
|
108 | } else if (options.server) {
|
109 | this._server = options.server;
|
110 | }
|
111 |
|
112 | if (this._server) {
|
113 | const emitConnection = this.emit.bind(this, 'connection');
|
114 |
|
115 | this._removeListeners = addListeners(this._server, {
|
116 | listening: this.emit.bind(this, 'listening'),
|
117 | error: this.emit.bind(this, 'error'),
|
118 | upgrade: (req, socket, head) => {
|
119 | this.handleUpgrade(req, socket, head, emitConnection);
|
120 | }
|
121 | });
|
122 | }
|
123 |
|
124 | if (options.perMessageDeflate === true) options.perMessageDeflate = {};
|
125 | if (options.clientTracking) {
|
126 | this.clients = new Set();
|
127 | this._shouldEmitClose = false;
|
128 | }
|
129 |
|
130 | this.options = options;
|
131 | this._state = RUNNING;
|
132 | }
|
133 |
|
134 | |
135 |
|
136 |
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 |
|
143 | address() {
|
144 | if (this.options.noServer) {
|
145 | throw new Error('The server is operating in "noServer" mode');
|
146 | }
|
147 |
|
148 | if (!this._server) return null;
|
149 | return this._server.address();
|
150 | }
|
151 |
|
152 | |
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 | close(cb) {
|
160 | if (this._state === CLOSED) {
|
161 | if (cb) {
|
162 | this.once('close', () => {
|
163 | cb(new Error('The server is not running'));
|
164 | });
|
165 | }
|
166 |
|
167 | process.nextTick(emitClose, this);
|
168 | return;
|
169 | }
|
170 |
|
171 | if (cb) this.once('close', cb);
|
172 |
|
173 | if (this._state === CLOSING) return;
|
174 | this._state = CLOSING;
|
175 |
|
176 | if (this.options.noServer || this.options.server) {
|
177 | if (this._server) {
|
178 | this._removeListeners();
|
179 | this._removeListeners = this._server = null;
|
180 | }
|
181 |
|
182 | if (this.clients) {
|
183 | if (!this.clients.size) {
|
184 | process.nextTick(emitClose, this);
|
185 | } else {
|
186 | this._shouldEmitClose = true;
|
187 | }
|
188 | } else {
|
189 | process.nextTick(emitClose, this);
|
190 | }
|
191 | } else {
|
192 | const server = this._server;
|
193 |
|
194 | this._removeListeners();
|
195 | this._removeListeners = this._server = null;
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 | server.close(() => {
|
202 | emitClose(this);
|
203 | });
|
204 | }
|
205 | }
|
206 |
|
207 | |
208 |
|
209 |
|
210 |
|
211 |
|
212 |
|
213 |
|
214 | shouldHandle(req) {
|
215 | if (this.options.path) {
|
216 | const index = req.url.indexOf('?');
|
217 | const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
218 |
|
219 | if (pathname !== this.options.path) return false;
|
220 | }
|
221 |
|
222 | return true;
|
223 | }
|
224 |
|
225 | |
226 |
|
227 |
|
228 |
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 | handleUpgrade(req, socket, head, cb) {
|
235 | socket.on('error', socketOnError);
|
236 |
|
237 | const key = req.headers['sec-websocket-key'];
|
238 | const upgrade = req.headers.upgrade;
|
239 | const version = +req.headers['sec-websocket-version'];
|
240 |
|
241 | if (req.method !== 'GET') {
|
242 | const message = 'Invalid HTTP method';
|
243 | abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
244 | return;
|
245 | }
|
246 |
|
247 | if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
|
248 | const message = 'Invalid Upgrade header';
|
249 | abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
250 | return;
|
251 | }
|
252 |
|
253 | if (key === undefined || !keyRegex.test(key)) {
|
254 | const message = 'Missing or invalid Sec-WebSocket-Key header';
|
255 | abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
256 | return;
|
257 | }
|
258 |
|
259 | if (version !== 8 && version !== 13) {
|
260 | const message = 'Missing or invalid Sec-WebSocket-Version header';
|
261 | abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
262 | return;
|
263 | }
|
264 |
|
265 | if (!this.shouldHandle(req)) {
|
266 | abortHandshake(socket, 400);
|
267 | return;
|
268 | }
|
269 |
|
270 | const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
|
271 | let protocols = new Set();
|
272 |
|
273 | if (secWebSocketProtocol !== undefined) {
|
274 | try {
|
275 | protocols = subprotocol.parse(secWebSocketProtocol);
|
276 | } catch (err) {
|
277 | const message = 'Invalid Sec-WebSocket-Protocol header';
|
278 | abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
279 | return;
|
280 | }
|
281 | }
|
282 |
|
283 | const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
|
284 | const extensions = {};
|
285 |
|
286 | if (
|
287 | this.options.perMessageDeflate &&
|
288 | secWebSocketExtensions !== undefined
|
289 | ) {
|
290 | const perMessageDeflate = new PerMessageDeflate(
|
291 | this.options.perMessageDeflate,
|
292 | true,
|
293 | this.options.maxPayload
|
294 | );
|
295 |
|
296 | try {
|
297 | const offers = extension.parse(secWebSocketExtensions);
|
298 |
|
299 | if (offers[PerMessageDeflate.extensionName]) {
|
300 | perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
|
301 | extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
302 | }
|
303 | } catch (err) {
|
304 | const message =
|
305 | 'Invalid or unacceptable Sec-WebSocket-Extensions header';
|
306 | abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
307 | return;
|
308 | }
|
309 | }
|
310 |
|
311 |
|
312 |
|
313 |
|
314 | if (this.options.verifyClient) {
|
315 | const info = {
|
316 | origin:
|
317 | req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
|
318 | secure: !!(req.socket.authorized || req.socket.encrypted),
|
319 | req
|
320 | };
|
321 |
|
322 | if (this.options.verifyClient.length === 2) {
|
323 | this.options.verifyClient(info, (verified, code, message, headers) => {
|
324 | if (!verified) {
|
325 | return abortHandshake(socket, code || 401, message, headers);
|
326 | }
|
327 |
|
328 | this.completeUpgrade(
|
329 | extensions,
|
330 | key,
|
331 | protocols,
|
332 | req,
|
333 | socket,
|
334 | head,
|
335 | cb
|
336 | );
|
337 | });
|
338 | return;
|
339 | }
|
340 |
|
341 | if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
|
342 | }
|
343 |
|
344 | this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
345 | }
|
346 |
|
347 | |
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 | completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
361 |
|
362 |
|
363 |
|
364 | if (!socket.readable || !socket.writable) return socket.destroy();
|
365 |
|
366 | if (socket[kWebSocket]) {
|
367 | throw new Error(
|
368 | 'server.handleUpgrade() was called more than once with the same ' +
|
369 | 'socket, possibly due to a misconfiguration'
|
370 | );
|
371 | }
|
372 |
|
373 | if (this._state > RUNNING) return abortHandshake(socket, 503);
|
374 |
|
375 | const digest = createHash('sha1')
|
376 | .update(key + GUID)
|
377 | .digest('base64');
|
378 |
|
379 | const headers = [
|
380 | 'HTTP/1.1 101 Switching Protocols',
|
381 | 'Upgrade: websocket',
|
382 | 'Connection: Upgrade',
|
383 | `Sec-WebSocket-Accept: ${digest}`
|
384 | ];
|
385 |
|
386 | const ws = new this.options.WebSocket(null, undefined, this.options);
|
387 |
|
388 | if (protocols.size) {
|
389 |
|
390 |
|
391 |
|
392 | const protocol = this.options.handleProtocols
|
393 | ? this.options.handleProtocols(protocols, req)
|
394 | : protocols.values().next().value;
|
395 |
|
396 | if (protocol) {
|
397 | headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
398 | ws._protocol = protocol;
|
399 | }
|
400 | }
|
401 |
|
402 | if (extensions[PerMessageDeflate.extensionName]) {
|
403 | const params = extensions[PerMessageDeflate.extensionName].params;
|
404 | const value = extension.format({
|
405 | [PerMessageDeflate.extensionName]: [params]
|
406 | });
|
407 | headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
408 | ws._extensions = extensions;
|
409 | }
|
410 |
|
411 |
|
412 |
|
413 |
|
414 | this.emit('headers', headers, req);
|
415 |
|
416 | socket.write(headers.concat('\r\n').join('\r\n'));
|
417 | socket.removeListener('error', socketOnError);
|
418 |
|
419 | ws.setSocket(socket, head, {
|
420 | allowSynchronousEvents: this.options.allowSynchronousEvents,
|
421 | maxPayload: this.options.maxPayload,
|
422 | skipUTF8Validation: this.options.skipUTF8Validation
|
423 | });
|
424 |
|
425 | if (this.clients) {
|
426 | this.clients.add(ws);
|
427 | ws.on('close', () => {
|
428 | this.clients.delete(ws);
|
429 |
|
430 | if (this._shouldEmitClose && !this.clients.size) {
|
431 | process.nextTick(emitClose, this);
|
432 | }
|
433 | });
|
434 | }
|
435 |
|
436 | cb(ws, req);
|
437 | }
|
438 | }
|
439 |
|
440 | module.exports = WebSocketServer;
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 |
|
447 |
|
448 |
|
449 |
|
450 |
|
451 |
|
452 | function addListeners(server, map) {
|
453 | for (const event of Object.keys(map)) server.on(event, map[event]);
|
454 |
|
455 | return function removeListeners() {
|
456 | for (const event of Object.keys(map)) {
|
457 | server.removeListener(event, map[event]);
|
458 | }
|
459 | };
|
460 | }
|
461 |
|
462 |
|
463 |
|
464 |
|
465 |
|
466 |
|
467 |
|
468 | function emitClose(server) {
|
469 | server._state = CLOSED;
|
470 | server.emit('close');
|
471 | }
|
472 |
|
473 |
|
474 |
|
475 |
|
476 |
|
477 |
|
478 | function socketOnError() {
|
479 | this.destroy();
|
480 | }
|
481 |
|
482 |
|
483 |
|
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 |
|
491 | function abortHandshake(socket, code, message, headers) {
|
492 |
|
493 |
|
494 |
|
495 |
|
496 |
|
497 |
|
498 |
|
499 |
|
500 | message = message || http.STATUS_CODES[code];
|
501 | headers = {
|
502 | Connection: 'close',
|
503 | 'Content-Type': 'text/html',
|
504 | 'Content-Length': Buffer.byteLength(message),
|
505 | ...headers
|
506 | };
|
507 |
|
508 | socket.once('finish', socket.destroy);
|
509 |
|
510 | socket.end(
|
511 | `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
|
512 | Object.keys(headers)
|
513 | .map((h) => `${h}: ${headers[h]}`)
|
514 | .join('\r\n') +
|
515 | '\r\n\r\n' +
|
516 | message
|
517 | );
|
518 | }
|
519 |
|
520 |
|
521 |
|
522 |
|
523 |
|
524 |
|
525 |
|
526 |
|
527 |
|
528 |
|
529 |
|
530 |
|
531 | function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
|
532 | if (server.listenerCount('wsClientError')) {
|
533 | const err = new Error(message);
|
534 | Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
535 |
|
536 | server.emit('wsClientError', err, socket, req);
|
537 | } else {
|
538 | abortHandshake(socket, code, message);
|
539 | }
|
540 | }
|