2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2019-05-26 19:58:31 -04:00
|
|
|
import { decode, encode } from "../strings/mod.ts";
|
2019-09-03 03:10:05 -04:00
|
|
|
import { hasOwnProperty } from "../util/has_own_property.ts";
|
2020-03-13 21:40:13 -04:00
|
|
|
import { BufReader, BufWriter } from "../io/bufio.ts";
|
2019-01-12 16:50:04 -05:00
|
|
|
import { readLong, readShort, sliceLongToBytes } from "../io/ioutil.ts";
|
2019-01-06 14:26:18 -05:00
|
|
|
import { Sha1 } from "./sha1.ts";
|
2020-02-26 10:48:35 -05:00
|
|
|
import { writeResponse } from "../http/io.ts";
|
2019-05-14 15:19:12 -04:00
|
|
|
import { TextProtoReader } from "../textproto/mod.ts";
|
2020-02-06 08:42:32 -05:00
|
|
|
import { Deferred, deferred } from "../util/async.ts";
|
2020-02-23 11:59:36 -05:00
|
|
|
import { assertNotEOF } from "../testing/asserts.ts";
|
2020-03-22 14:49:09 -04:00
|
|
|
import { concat } from "../bytes/mod.ts";
|
2020-02-23 11:59:36 -05:00
|
|
|
import Conn = Deno.Conn;
|
|
|
|
import Writer = Deno.Writer;
|
2019-01-06 14:26:18 -05:00
|
|
|
|
2019-02-02 14:57:27 -05:00
|
|
|
export enum OpCode {
|
|
|
|
Continue = 0x0,
|
|
|
|
TextFrame = 0x1,
|
|
|
|
BinaryFrame = 0x2,
|
|
|
|
Close = 0x8,
|
|
|
|
Ping = 0x9,
|
2020-03-28 13:03:49 -04:00
|
|
|
Pong = 0xa,
|
2019-02-02 14:57:27 -05:00
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
|
|
|
|
export type WebSocketEvent =
|
|
|
|
| string
|
|
|
|
| Uint8Array
|
2020-02-23 11:59:36 -05:00
|
|
|
| WebSocketCloseEvent // Received after closing connection finished.
|
|
|
|
| WebSocketPingEvent // Received after pong frame responded.
|
2019-01-06 14:26:18 -05:00
|
|
|
| WebSocketPongEvent;
|
|
|
|
|
2019-03-12 01:51:51 -04:00
|
|
|
export interface WebSocketCloseEvent {
|
2019-01-06 14:26:18 -05:00
|
|
|
code: number;
|
|
|
|
reason?: string;
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
|
2019-05-30 08:59:30 -04:00
|
|
|
export function isWebSocketCloseEvent(
|
|
|
|
a: WebSocketEvent
|
|
|
|
): a is WebSocketCloseEvent {
|
2019-09-03 03:10:05 -04:00
|
|
|
return hasOwnProperty(a, "code");
|
2019-01-06 14:26:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export type WebSocketPingEvent = ["ping", Uint8Array];
|
|
|
|
|
2019-05-30 08:59:30 -04:00
|
|
|
export function isWebSocketPingEvent(
|
|
|
|
a: WebSocketEvent
|
|
|
|
): a is WebSocketPingEvent {
|
2019-01-06 14:26:18 -05:00
|
|
|
return Array.isArray(a) && a[0] === "ping" && a[1] instanceof Uint8Array;
|
|
|
|
}
|
|
|
|
|
|
|
|
export type WebSocketPongEvent = ["pong", Uint8Array];
|
|
|
|
|
2019-05-30 08:59:30 -04:00
|
|
|
export function isWebSocketPongEvent(
|
|
|
|
a: WebSocketEvent
|
|
|
|
): a is WebSocketPongEvent {
|
2019-01-06 14:26:18 -05:00
|
|
|
return Array.isArray(a) && a[0] === "pong" && a[1] instanceof Uint8Array;
|
|
|
|
}
|
|
|
|
|
2019-03-04 18:23:04 -05:00
|
|
|
export type WebSocketMessage = string | Uint8Array;
|
|
|
|
|
2019-03-12 01:51:51 -04:00
|
|
|
export interface WebSocketFrame {
|
2019-01-06 14:26:18 -05:00
|
|
|
isLastFrame: boolean;
|
2019-03-04 18:23:04 -05:00
|
|
|
opcode: OpCode;
|
2019-01-06 14:26:18 -05:00
|
|
|
mask?: Uint8Array;
|
|
|
|
payload: Uint8Array;
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
|
2019-03-12 01:51:51 -04:00
|
|
|
export interface WebSocket {
|
2019-05-14 15:19:12 -04:00
|
|
|
readonly conn: Conn;
|
2019-01-06 14:26:18 -05:00
|
|
|
readonly isClosed: boolean;
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2019-01-06 14:26:18 -05:00
|
|
|
receive(): AsyncIterableIterator<WebSocketEvent>;
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2020-02-23 11:59:36 -05:00
|
|
|
/**
|
2020-03-13 21:40:13 -04:00
|
|
|
* @throws `Deno.errors.ConnectionReset`
|
2020-02-23 11:59:36 -05:00
|
|
|
*/
|
2019-03-04 18:23:04 -05:00
|
|
|
send(data: WebSocketMessage): Promise<void>;
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2020-02-23 11:59:36 -05:00
|
|
|
/**
|
|
|
|
* @param data
|
2020-03-13 21:40:13 -04:00
|
|
|
* @throws `Deno.errors.ConnectionReset`
|
2020-02-23 11:59:36 -05:00
|
|
|
*/
|
2019-03-04 18:23:04 -05:00
|
|
|
ping(data?: WebSocketMessage): Promise<void>;
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2020-02-23 11:59:36 -05:00
|
|
|
/** Close connection after sending close frame to peer.
|
|
|
|
* This is canonical way of disconnection but it may hang because of peer's response delay.
|
2020-02-28 11:17:00 -05:00
|
|
|
* Default close code is 1000 (Normal Closure)
|
2020-03-13 21:40:13 -04:00
|
|
|
* @throws `Deno.errors.ConnectionReset`
|
2020-02-23 11:59:36 -05:00
|
|
|
*/
|
2020-02-28 11:17:00 -05:00
|
|
|
close(): Promise<void>;
|
|
|
|
close(code: number): Promise<void>;
|
|
|
|
close(code: number, reason: string): Promise<void>;
|
2020-02-23 11:59:36 -05:00
|
|
|
|
|
|
|
/** Close connection forcely without sending close frame to peer.
|
|
|
|
* This is basically undesirable way of disconnection. Use carefully. */
|
|
|
|
closeForce(): void;
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
/** Unmask masked websocket payload */
|
2019-03-12 01:51:51 -04:00
|
|
|
export function unmask(payload: Uint8Array, mask?: Uint8Array): void {
|
|
|
|
if (mask) {
|
|
|
|
for (let i = 0, len = payload.length; i < len; i++) {
|
2020-02-07 02:23:38 -05:00
|
|
|
payload[i] ^= mask[i & 3];
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
/** Write websocket frame to given writer */
|
2019-03-12 01:51:51 -04:00
|
|
|
export async function writeFrame(
|
|
|
|
frame: WebSocketFrame,
|
|
|
|
writer: Writer
|
|
|
|
): Promise<void> {
|
|
|
|
const payloadLength = frame.payload.byteLength;
|
|
|
|
let header: Uint8Array;
|
|
|
|
const hasMask = frame.mask ? 0x80 : 0;
|
2019-05-14 15:19:12 -04:00
|
|
|
if (frame.mask && frame.mask.byteLength !== 4) {
|
|
|
|
throw new Error(
|
|
|
|
"invalid mask. mask must be 4 bytes: length=" + frame.mask.byteLength
|
|
|
|
);
|
|
|
|
}
|
2019-03-12 01:51:51 -04:00
|
|
|
if (payloadLength < 126) {
|
|
|
|
header = new Uint8Array([0x80 | frame.opcode, hasMask | payloadLength]);
|
|
|
|
} else if (payloadLength < 0xffff) {
|
|
|
|
header = new Uint8Array([
|
|
|
|
0x80 | frame.opcode,
|
|
|
|
hasMask | 0b01111110,
|
|
|
|
payloadLength >>> 8,
|
2020-03-28 13:03:49 -04:00
|
|
|
payloadLength & 0x00ff,
|
2019-03-12 01:51:51 -04:00
|
|
|
]);
|
|
|
|
} else {
|
|
|
|
header = new Uint8Array([
|
|
|
|
0x80 | frame.opcode,
|
|
|
|
hasMask | 0b01111111,
|
2020-03-28 13:03:49 -04:00
|
|
|
...sliceLongToBytes(payloadLength),
|
2019-03-12 01:51:51 -04:00
|
|
|
]);
|
|
|
|
}
|
2019-05-14 15:19:12 -04:00
|
|
|
if (frame.mask) {
|
2020-03-22 14:49:09 -04:00
|
|
|
header = concat(header, frame.mask);
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
2019-03-12 01:51:51 -04:00
|
|
|
unmask(frame.payload, frame.mask);
|
2020-03-22 14:49:09 -04:00
|
|
|
header = concat(header, frame.payload);
|
2019-05-14 15:19:12 -04:00
|
|
|
const w = BufWriter.create(writer);
|
|
|
|
await w.write(header);
|
2019-05-23 22:04:06 -04:00
|
|
|
await w.flush();
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
|
|
|
|
2020-02-23 11:59:36 -05:00
|
|
|
/** Read websocket frame from given BufReader
|
2020-03-13 21:40:13 -04:00
|
|
|
* @throws `Deno.errors.UnexpectedEof` When peer closed connection without close frame
|
|
|
|
* @throws `Error` Frame is invalid
|
2020-02-23 11:59:36 -05:00
|
|
|
*/
|
2019-03-12 01:51:51 -04:00
|
|
|
export async function readFrame(buf: BufReader): Promise<WebSocketFrame> {
|
2020-02-23 11:59:36 -05:00
|
|
|
let b = assertNotEOF(await buf.readByte());
|
2019-03-12 01:51:51 -04:00
|
|
|
let isLastFrame = false;
|
|
|
|
switch (b >>> 4) {
|
|
|
|
case 0b1000:
|
|
|
|
isLastFrame = true;
|
|
|
|
break;
|
|
|
|
case 0b0000:
|
|
|
|
isLastFrame = false;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
throw new Error("invalid signature");
|
|
|
|
}
|
|
|
|
const opcode = b & 0x0f;
|
|
|
|
// has_mask & payload
|
2020-02-23 11:59:36 -05:00
|
|
|
b = assertNotEOF(await buf.readByte());
|
2019-03-12 01:51:51 -04:00
|
|
|
const hasMask = b >>> 7;
|
|
|
|
let payloadLength = b & 0b01111111;
|
|
|
|
if (payloadLength === 126) {
|
2020-02-23 11:59:36 -05:00
|
|
|
const l = assertNotEOF(await readShort(buf));
|
2019-05-30 21:19:28 -04:00
|
|
|
payloadLength = l;
|
2019-03-12 01:51:51 -04:00
|
|
|
} else if (payloadLength === 127) {
|
2020-02-23 11:59:36 -05:00
|
|
|
const l = assertNotEOF(await readLong(buf));
|
2019-05-30 21:19:28 -04:00
|
|
|
payloadLength = Number(l);
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
|
|
|
// mask
|
2020-02-23 11:59:36 -05:00
|
|
|
let mask: Uint8Array | undefined;
|
2019-03-12 01:51:51 -04:00
|
|
|
if (hasMask) {
|
|
|
|
mask = new Uint8Array(4);
|
2020-02-23 11:59:36 -05:00
|
|
|
assertNotEOF(await buf.readFull(mask));
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
|
|
|
// payload
|
|
|
|
const payload = new Uint8Array(payloadLength);
|
2020-02-23 11:59:36 -05:00
|
|
|
assertNotEOF(await buf.readFull(payload));
|
2019-03-12 01:51:51 -04:00
|
|
|
return {
|
|
|
|
isLastFrame,
|
|
|
|
opcode,
|
|
|
|
mask,
|
2020-03-28 13:03:49 -04:00
|
|
|
payload,
|
2019-03-12 01:51:51 -04:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
// Create client-to-server mask, random 32bit number
|
|
|
|
function createMask(): Uint8Array {
|
2019-09-04 10:42:40 -04:00
|
|
|
return crypto.getRandomValues(new Uint8Array(4));
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
|
|
|
|
class WebSocketImpl implements WebSocket {
|
2020-02-06 08:42:32 -05:00
|
|
|
readonly conn: Conn;
|
2019-05-14 15:19:12 -04:00
|
|
|
private readonly mask?: Uint8Array;
|
|
|
|
private readonly bufReader: BufReader;
|
|
|
|
private readonly bufWriter: BufWriter;
|
2020-02-06 08:42:32 -05:00
|
|
|
private sendQueue: Array<{
|
|
|
|
frame: WebSocketFrame;
|
|
|
|
d: Deferred<void>;
|
|
|
|
}> = [];
|
2019-02-10 18:45:24 -05:00
|
|
|
|
2020-02-06 08:42:32 -05:00
|
|
|
constructor({
|
|
|
|
conn,
|
|
|
|
bufReader,
|
|
|
|
bufWriter,
|
2020-03-28 13:03:49 -04:00
|
|
|
mask,
|
2020-02-06 08:42:32 -05:00
|
|
|
}: {
|
|
|
|
conn: Conn;
|
|
|
|
bufReader?: BufReader;
|
|
|
|
bufWriter?: BufWriter;
|
|
|
|
mask?: Uint8Array;
|
|
|
|
}) {
|
|
|
|
this.conn = conn;
|
|
|
|
this.mask = mask;
|
|
|
|
this.bufReader = bufReader || new BufReader(conn);
|
|
|
|
this.bufWriter = bufWriter || new BufWriter(conn);
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
|
|
|
|
async *receive(): AsyncIterableIterator<WebSocketEvent> {
|
|
|
|
let frames: WebSocketFrame[] = [];
|
|
|
|
let payloadsLength = 0;
|
2020-02-23 11:59:36 -05:00
|
|
|
while (!this._isClosed) {
|
|
|
|
let frame: WebSocketFrame;
|
|
|
|
try {
|
|
|
|
frame = await readFrame(this.bufReader);
|
|
|
|
} catch (e) {
|
|
|
|
this.ensureSocketClosed();
|
|
|
|
break;
|
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
unmask(frame.payload, frame.mask);
|
|
|
|
switch (frame.opcode) {
|
2019-02-02 14:57:27 -05:00
|
|
|
case OpCode.TextFrame:
|
|
|
|
case OpCode.BinaryFrame:
|
|
|
|
case OpCode.Continue:
|
2019-01-06 14:26:18 -05:00
|
|
|
frames.push(frame);
|
|
|
|
payloadsLength += frame.payload.length;
|
|
|
|
if (frame.isLastFrame) {
|
|
|
|
const concat = new Uint8Array(payloadsLength);
|
|
|
|
let offs = 0;
|
|
|
|
for (const frame of frames) {
|
|
|
|
concat.set(frame.payload, offs);
|
|
|
|
offs += frame.payload.length;
|
|
|
|
}
|
2019-02-02 14:57:27 -05:00
|
|
|
if (frames[0].opcode === OpCode.TextFrame) {
|
2019-01-06 14:26:18 -05:00
|
|
|
// text
|
2019-05-14 15:19:12 -04:00
|
|
|
yield decode(concat);
|
2019-01-06 14:26:18 -05:00
|
|
|
} else {
|
|
|
|
// binary
|
|
|
|
yield concat;
|
|
|
|
}
|
|
|
|
frames = [];
|
|
|
|
payloadsLength = 0;
|
|
|
|
}
|
|
|
|
break;
|
2019-02-02 14:57:27 -05:00
|
|
|
case OpCode.Close:
|
2019-05-14 15:19:12 -04:00
|
|
|
// [0x12, 0x34] -> 0x1234
|
|
|
|
const code = (frame.payload[0] << 8) | frame.payload[1];
|
|
|
|
const reason = decode(
|
2019-01-06 14:26:18 -05:00
|
|
|
frame.payload.subarray(2, frame.payload.length)
|
2019-05-14 15:19:12 -04:00
|
|
|
);
|
|
|
|
await this.close(code, reason);
|
2019-01-06 14:26:18 -05:00
|
|
|
yield { code, reason };
|
|
|
|
return;
|
2019-02-02 14:57:27 -05:00
|
|
|
case OpCode.Ping:
|
2020-02-06 08:42:32 -05:00
|
|
|
await this.enqueue({
|
|
|
|
opcode: OpCode.Pong,
|
|
|
|
payload: frame.payload,
|
2020-03-28 13:03:49 -04:00
|
|
|
isLastFrame: true,
|
2020-02-06 08:42:32 -05:00
|
|
|
});
|
2019-01-06 14:26:18 -05:00
|
|
|
yield ["ping", frame.payload] as WebSocketPingEvent;
|
|
|
|
break;
|
2019-02-02 14:57:27 -05:00
|
|
|
case OpCode.Pong:
|
2019-01-06 14:26:18 -05:00
|
|
|
yield ["pong", frame.payload] as WebSocketPongEvent;
|
|
|
|
break;
|
2019-03-04 18:23:04 -05:00
|
|
|
default:
|
2019-01-06 14:26:18 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-06 08:42:32 -05:00
|
|
|
private dequeue(): void {
|
2020-02-23 11:59:36 -05:00
|
|
|
const [entry] = this.sendQueue;
|
|
|
|
if (!entry) return;
|
|
|
|
if (this._isClosed) return;
|
|
|
|
const { d, frame } = entry;
|
|
|
|
writeFrame(frame, this.bufWriter)
|
|
|
|
.then(() => d.resolve())
|
2020-03-28 13:03:49 -04:00
|
|
|
.catch((e) => d.reject(e))
|
2020-02-06 08:42:32 -05:00
|
|
|
.finally(() => {
|
|
|
|
this.sendQueue.shift();
|
|
|
|
this.dequeue();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private enqueue(frame: WebSocketFrame): Promise<void> {
|
2020-02-23 11:59:36 -05:00
|
|
|
if (this._isClosed) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.ConnectionReset("Socket has already been closed");
|
2020-02-23 11:59:36 -05:00
|
|
|
}
|
2020-02-06 08:42:32 -05:00
|
|
|
const d = deferred<void>();
|
|
|
|
this.sendQueue.push({ d, frame });
|
|
|
|
if (this.sendQueue.length === 1) {
|
|
|
|
this.dequeue();
|
|
|
|
}
|
|
|
|
return d;
|
|
|
|
}
|
|
|
|
|
2020-03-20 09:38:34 -04:00
|
|
|
send(data: WebSocketMessage): Promise<void> {
|
2019-01-06 14:26:18 -05:00
|
|
|
const opcode =
|
2019-02-02 14:57:27 -05:00
|
|
|
typeof data === "string" ? OpCode.TextFrame : OpCode.BinaryFrame;
|
2019-05-14 15:19:12 -04:00
|
|
|
const payload = typeof data === "string" ? encode(data) : data;
|
2019-01-06 14:26:18 -05:00
|
|
|
const isLastFrame = true;
|
2020-02-06 08:42:32 -05:00
|
|
|
const frame = {
|
|
|
|
isLastFrame,
|
|
|
|
opcode,
|
|
|
|
payload,
|
2020-03-28 13:03:49 -04:00
|
|
|
mask: this.mask,
|
2020-02-06 08:42:32 -05:00
|
|
|
};
|
|
|
|
return this.enqueue(frame);
|
2019-01-06 14:26:18 -05:00
|
|
|
}
|
|
|
|
|
2020-03-20 09:38:34 -04:00
|
|
|
ping(data: WebSocketMessage = ""): Promise<void> {
|
2019-05-14 15:19:12 -04:00
|
|
|
const payload = typeof data === "string" ? encode(data) : data;
|
2020-02-06 08:42:32 -05:00
|
|
|
const frame = {
|
|
|
|
isLastFrame: true,
|
|
|
|
opcode: OpCode.Ping,
|
|
|
|
mask: this.mask,
|
2020-03-28 13:03:49 -04:00
|
|
|
payload,
|
2020-02-06 08:42:32 -05:00
|
|
|
};
|
|
|
|
return this.enqueue(frame);
|
2019-01-06 14:26:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
private _isClosed = false;
|
2019-03-12 01:51:51 -04:00
|
|
|
get isClosed(): boolean {
|
2019-01-06 14:26:18 -05:00
|
|
|
return this._isClosed;
|
|
|
|
}
|
|
|
|
|
2020-02-28 11:17:00 -05:00
|
|
|
async close(code = 1000, reason?: string): Promise<void> {
|
2019-01-06 14:26:18 -05:00
|
|
|
try {
|
|
|
|
const header = [code >>> 8, code & 0x00ff];
|
|
|
|
let payload: Uint8Array;
|
|
|
|
if (reason) {
|
2019-05-14 15:19:12 -04:00
|
|
|
const reasonBytes = encode(reason);
|
2019-01-06 14:26:18 -05:00
|
|
|
payload = new Uint8Array(2 + reasonBytes.byteLength);
|
|
|
|
payload.set(header);
|
|
|
|
payload.set(reasonBytes, 2);
|
|
|
|
} else {
|
|
|
|
payload = new Uint8Array(header);
|
|
|
|
}
|
2020-02-06 08:42:32 -05:00
|
|
|
await this.enqueue({
|
|
|
|
isLastFrame: true,
|
|
|
|
opcode: OpCode.Close,
|
|
|
|
mask: this.mask,
|
2020-03-28 13:03:49 -04:00
|
|
|
payload,
|
2020-02-06 08:42:32 -05:00
|
|
|
});
|
2019-01-06 14:26:18 -05:00
|
|
|
} catch (e) {
|
|
|
|
throw e;
|
|
|
|
} finally {
|
|
|
|
this.ensureSocketClosed();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-23 11:59:36 -05:00
|
|
|
closeForce(): void {
|
|
|
|
this.ensureSocketClosed();
|
|
|
|
}
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
private ensureSocketClosed(): void {
|
2020-02-23 11:59:36 -05:00
|
|
|
if (this.isClosed) return;
|
2019-01-06 14:26:18 -05:00
|
|
|
try {
|
|
|
|
this.conn.close();
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
} finally {
|
|
|
|
this._isClosed = true;
|
2020-02-23 11:59:36 -05:00
|
|
|
const rest = this.sendQueue;
|
|
|
|
this.sendQueue = [];
|
2020-03-28 13:03:49 -04:00
|
|
|
rest.forEach((e) =>
|
2020-03-13 21:40:13 -04:00
|
|
|
e.d.reject(
|
|
|
|
new Deno.errors.ConnectionReset("Socket has already been closed")
|
|
|
|
)
|
|
|
|
);
|
2019-01-06 14:26:18 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
/** Return whether given headers is acceptable for websocket */
|
2019-02-10 18:45:24 -05:00
|
|
|
export function acceptable(req: { headers: Headers }): boolean {
|
2019-05-14 17:45:52 -04:00
|
|
|
const upgrade = req.headers.get("upgrade");
|
|
|
|
if (!upgrade || upgrade.toLowerCase() !== "websocket") {
|
|
|
|
return false;
|
|
|
|
}
|
2019-05-14 15:19:12 -04:00
|
|
|
const secKey = req.headers.get("sec-websocket-key");
|
2019-01-06 14:26:18 -05:00
|
|
|
return (
|
2019-02-10 18:45:24 -05:00
|
|
|
req.headers.has("sec-websocket-key") &&
|
2019-05-14 15:19:12 -04:00
|
|
|
typeof secKey === "string" &&
|
|
|
|
secKey.length > 0
|
2019-01-06 14:26:18 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-03-12 01:51:51 -04:00
|
|
|
const kGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
/** Create sec-websocket-accept header value with given nonce */
|
2019-03-12 01:51:51 -04:00
|
|
|
export function createSecAccept(nonce: string): string {
|
|
|
|
const sha1 = new Sha1();
|
|
|
|
sha1.update(nonce + kGUID);
|
|
|
|
const bytes = sha1.digest();
|
2019-10-05 12:02:34 -04:00
|
|
|
return btoa(String.fromCharCode(...bytes));
|
2019-03-12 01:51:51 -04:00
|
|
|
}
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
/** Upgrade given TCP connection into websocket connection */
|
2019-02-10 18:45:24 -05:00
|
|
|
export async function acceptWebSocket(req: {
|
|
|
|
conn: Conn;
|
2019-05-14 15:19:12 -04:00
|
|
|
bufWriter: BufWriter;
|
|
|
|
bufReader: BufReader;
|
2019-02-10 18:45:24 -05:00
|
|
|
headers: Headers;
|
|
|
|
}): Promise<WebSocket> {
|
2019-05-14 15:19:12 -04:00
|
|
|
const { conn, headers, bufReader, bufWriter } = req;
|
2019-01-06 14:26:18 -05:00
|
|
|
if (acceptable(req)) {
|
2020-02-06 08:42:32 -05:00
|
|
|
const sock = new WebSocketImpl({ conn, bufReader, bufWriter });
|
2019-02-10 18:45:24 -05:00
|
|
|
const secKey = headers.get("sec-websocket-key");
|
2019-05-14 15:19:12 -04:00
|
|
|
if (typeof secKey !== "string") {
|
|
|
|
throw new Error("sec-websocket-key is not provided");
|
|
|
|
}
|
2019-01-06 14:26:18 -05:00
|
|
|
const secAccept = createSecAccept(secKey);
|
2019-05-14 15:19:12 -04:00
|
|
|
await writeResponse(bufWriter, {
|
2019-01-06 14:26:18 -05:00
|
|
|
status: 101,
|
|
|
|
headers: new Headers({
|
|
|
|
Upgrade: "websocket",
|
|
|
|
Connection: "Upgrade",
|
2020-03-28 13:03:49 -04:00
|
|
|
"Sec-WebSocket-Accept": secAccept,
|
|
|
|
}),
|
2019-01-06 14:26:18 -05:00
|
|
|
});
|
|
|
|
return sock;
|
|
|
|
}
|
|
|
|
throw new Error("request is not acceptable");
|
|
|
|
}
|
2019-05-14 15:19:12 -04:00
|
|
|
|
|
|
|
const kSecChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.~_";
|
|
|
|
|
|
|
|
/** Create WebSocket-Sec-Key. Base64 encoded 16 bytes string */
|
|
|
|
export function createSecKey(): string {
|
|
|
|
let key = "";
|
|
|
|
for (let i = 0; i < 16; i++) {
|
2020-02-24 16:37:15 -05:00
|
|
|
const j = Math.floor(Math.random() * kSecChars.length);
|
2019-05-14 15:19:12 -04:00
|
|
|
key += kSecChars[j];
|
|
|
|
}
|
|
|
|
return btoa(key);
|
|
|
|
}
|
|
|
|
|
2020-01-04 04:31:12 -05:00
|
|
|
export async function handshake(
|
2019-05-23 22:04:06 -04:00
|
|
|
url: URL,
|
|
|
|
headers: Headers,
|
|
|
|
bufReader: BufReader,
|
|
|
|
bufWriter: BufWriter
|
|
|
|
): Promise<void> {
|
2020-01-04 04:31:12 -05:00
|
|
|
const { hostname, pathname, search } = url;
|
2019-05-14 15:19:12 -04:00
|
|
|
const key = createSecKey();
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
if (!headers.has("host")) {
|
|
|
|
headers.set("host", hostname);
|
|
|
|
}
|
|
|
|
headers.set("upgrade", "websocket");
|
|
|
|
headers.set("connection", "upgrade");
|
|
|
|
headers.set("sec-websocket-key", key);
|
2019-05-30 11:51:47 -04:00
|
|
|
headers.set("sec-websocket-version", "13");
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2020-01-04 04:31:12 -05:00
|
|
|
let headerStr = `GET ${pathname}${search} HTTP/1.1\r\n`;
|
2019-05-14 15:19:12 -04:00
|
|
|
for (const [key, value] of headers) {
|
|
|
|
headerStr += `${key}: ${value}\r\n`;
|
|
|
|
}
|
|
|
|
headerStr += "\r\n";
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
await bufWriter.write(encode(headerStr));
|
2019-05-23 22:04:06 -04:00
|
|
|
await bufWriter.flush();
|
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
const tpReader = new TextProtoReader(bufReader);
|
2019-05-23 22:04:06 -04:00
|
|
|
const statusLine = await tpReader.readLine();
|
2019-07-07 15:20:41 -04:00
|
|
|
if (statusLine === Deno.EOF) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
const m = statusLine.match(/^(?<version>\S+) (?<statusCode>\S+) /);
|
2019-05-14 15:19:12 -04:00
|
|
|
if (!m) {
|
2019-05-23 22:04:06 -04:00
|
|
|
throw new Error("ws: invalid status line: " + statusLine);
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
2019-05-30 08:59:30 -04:00
|
|
|
|
|
|
|
// @ts-ignore
|
2019-05-23 22:04:06 -04:00
|
|
|
const { version, statusCode } = m.groups;
|
2019-05-14 15:19:12 -04:00
|
|
|
if (version !== "HTTP/1.1" || statusCode !== "101") {
|
2019-05-23 22:04:06 -04:00
|
|
|
throw new Error(
|
|
|
|
`ws: server didn't accept handshake: ` +
|
|
|
|
`version=${version}, statusCode=${statusCode}`
|
2019-05-14 15:19:12 -04:00
|
|
|
);
|
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
|
|
|
const responseHeaders = await tpReader.readMIMEHeader();
|
2019-07-07 15:20:41 -04:00
|
|
|
if (responseHeaders === Deno.EOF) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2019-05-14 15:19:12 -04:00
|
|
|
const expectedSecAccept = createSecAccept(key);
|
|
|
|
const secAccept = responseHeaders.get("sec-websocket-accept");
|
|
|
|
if (secAccept !== expectedSecAccept) {
|
2019-05-23 22:04:06 -04:00
|
|
|
throw new Error(
|
|
|
|
`ws: unexpected sec-websocket-accept header: ` +
|
|
|
|
`expected=${expectedSecAccept}, actual=${secAccept}`
|
2019-05-14 15:19:12 -04:00
|
|
|
);
|
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
}
|
|
|
|
|
2019-06-19 00:22:01 -04:00
|
|
|
/**
|
|
|
|
* Connect to given websocket endpoint url.
|
|
|
|
* Endpoint must be acceptable for URL.
|
|
|
|
*/
|
2019-05-23 22:04:06 -04:00
|
|
|
export async function connectWebSocket(
|
|
|
|
endpoint: string,
|
|
|
|
headers: Headers = new Headers()
|
|
|
|
): Promise<WebSocket> {
|
|
|
|
const url = new URL(endpoint);
|
2019-10-05 12:02:34 -04:00
|
|
|
const { hostname } = url;
|
2019-09-28 12:46:21 -04:00
|
|
|
let conn: Conn;
|
|
|
|
if (url.protocol === "http:" || url.protocol === "ws:") {
|
|
|
|
const port = parseInt(url.port || "80");
|
2020-01-18 12:35:12 -05:00
|
|
|
conn = await Deno.connect({ hostname, port });
|
2019-09-28 12:46:21 -04:00
|
|
|
} else if (url.protocol === "https:" || url.protocol === "wss:") {
|
|
|
|
const port = parseInt(url.port || "443");
|
2020-01-18 12:35:12 -05:00
|
|
|
conn = await Deno.connectTLS({ hostname, port });
|
2019-09-28 12:46:21 -04:00
|
|
|
} else {
|
|
|
|
throw new Error("ws: unsupported protocol: " + url.protocol);
|
2019-05-23 22:04:06 -04:00
|
|
|
}
|
|
|
|
const bufWriter = new BufWriter(conn);
|
|
|
|
const bufReader = new BufReader(conn);
|
|
|
|
try {
|
|
|
|
await handshake(url, headers, bufReader, bufWriter);
|
|
|
|
} catch (err) {
|
|
|
|
conn.close();
|
|
|
|
throw err;
|
|
|
|
}
|
2020-02-06 08:42:32 -05:00
|
|
|
return new WebSocketImpl({
|
|
|
|
conn,
|
2019-05-14 15:19:12 -04:00
|
|
|
bufWriter,
|
2019-09-28 12:47:38 -04:00
|
|
|
bufReader,
|
2020-03-28 13:03:49 -04:00
|
|
|
mask: createMask(),
|
2019-05-14 15:19:12 -04:00
|
|
|
});
|
|
|
|
}
|
2020-02-06 08:42:32 -05:00
|
|
|
|
|
|
|
export function createWebSocket(params: {
|
|
|
|
conn: Conn;
|
|
|
|
bufWriter?: BufWriter;
|
|
|
|
bufReader?: BufReader;
|
|
|
|
mask?: Uint8Array;
|
|
|
|
}): WebSocket {
|
|
|
|
return new WebSocketImpl(params);
|
|
|
|
}
|