2021-01-10 21:59:07 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-03-13 21:40:13 -04:00
|
|
|
import { BufReader, BufWriter } from "../io/bufio.ts";
|
2020-02-24 22:49:39 -05:00
|
|
|
import { TextProtoReader } from "../textproto/mod.ts";
|
2020-06-07 09:20:33 -04:00
|
|
|
import { assert } from "../_util/assert.ts";
|
2020-04-01 15:23:39 -04:00
|
|
|
import { encoder } from "../encoding/utf8.ts";
|
2020-09-27 06:22:32 -04:00
|
|
|
import { Response, ServerRequest } from "./server.ts";
|
2020-02-26 10:48:35 -05:00
|
|
|
import { STATUS_TEXT } from "./http_status.ts";
|
2020-02-24 22:49:39 -05:00
|
|
|
|
|
|
|
export function emptyReader(): Deno.Reader {
|
|
|
|
return {
|
2020-04-28 12:40:43 -04:00
|
|
|
read(_: Uint8Array): Promise<number | null> {
|
|
|
|
return Promise.resolve(null);
|
2020-03-28 13:03:49 -04:00
|
|
|
},
|
2020-02-24 22:49:39 -05:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function bodyReader(contentLength: number, r: BufReader): Deno.Reader {
|
|
|
|
let totalRead = 0;
|
|
|
|
let finished = false;
|
2020-04-28 12:40:43 -04:00
|
|
|
async function read(buf: Uint8Array): Promise<number | null> {
|
|
|
|
if (finished) return null;
|
|
|
|
let result: number | null;
|
2020-02-24 22:49:39 -05:00
|
|
|
const remaining = contentLength - totalRead;
|
|
|
|
if (remaining >= buf.byteLength) {
|
|
|
|
result = await r.read(buf);
|
|
|
|
} else {
|
|
|
|
const readBuf = buf.subarray(0, remaining);
|
|
|
|
result = await r.read(readBuf);
|
|
|
|
}
|
2020-04-28 12:40:43 -04:00
|
|
|
if (result !== null) {
|
2020-02-24 22:49:39 -05:00
|
|
|
totalRead += result;
|
|
|
|
}
|
|
|
|
finished = totalRead === contentLength;
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
return { read };
|
|
|
|
}
|
|
|
|
|
|
|
|
export function chunkedBodyReader(h: Headers, r: BufReader): Deno.Reader {
|
|
|
|
// Based on https://tools.ietf.org/html/rfc2616#section-19.4.6
|
|
|
|
const tp = new TextProtoReader(r);
|
|
|
|
let finished = false;
|
|
|
|
const chunks: Array<{
|
|
|
|
offset: number;
|
|
|
|
data: Uint8Array;
|
|
|
|
}> = [];
|
2020-04-28 12:40:43 -04:00
|
|
|
async function read(buf: Uint8Array): Promise<number | null> {
|
|
|
|
if (finished) return null;
|
2020-02-24 22:49:39 -05:00
|
|
|
const [chunk] = chunks;
|
|
|
|
if (chunk) {
|
|
|
|
const chunkRemaining = chunk.data.byteLength - chunk.offset;
|
|
|
|
const readLength = Math.min(chunkRemaining, buf.byteLength);
|
|
|
|
for (let i = 0; i < readLength; i++) {
|
|
|
|
buf[i] = chunk.data[chunk.offset + i];
|
|
|
|
}
|
|
|
|
chunk.offset += readLength;
|
|
|
|
if (chunk.offset === chunk.data.byteLength) {
|
|
|
|
chunks.shift();
|
|
|
|
// Consume \r\n;
|
2020-04-28 12:40:43 -04:00
|
|
|
if ((await tp.readLine()) === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return readLength;
|
|
|
|
}
|
|
|
|
const line = await tp.readLine();
|
2020-04-28 12:40:43 -04:00
|
|
|
if (line === null) throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
// TODO: handle chunk extension
|
|
|
|
const [chunkSizeString] = line.split(";");
|
|
|
|
const chunkSize = parseInt(chunkSizeString, 16);
|
|
|
|
if (Number.isNaN(chunkSize) || chunkSize < 0) {
|
2020-11-18 11:47:47 -05:00
|
|
|
throw new Deno.errors.InvalidData("Invalid chunk size");
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
if (chunkSize > 0) {
|
|
|
|
if (chunkSize > buf.byteLength) {
|
|
|
|
let eof = await r.readFull(buf);
|
2020-04-28 12:40:43 -04:00
|
|
|
if (eof === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
const restChunk = new Uint8Array(chunkSize - buf.byteLength);
|
|
|
|
eof = await r.readFull(restChunk);
|
2020-04-28 12:40:43 -04:00
|
|
|
if (eof === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
} else {
|
|
|
|
chunks.push({
|
|
|
|
offset: 0,
|
2020-03-28 13:03:49 -04:00
|
|
|
data: restChunk,
|
2020-02-24 22:49:39 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
return buf.byteLength;
|
|
|
|
} else {
|
|
|
|
const bufToFill = buf.subarray(0, chunkSize);
|
|
|
|
const eof = await r.readFull(bufToFill);
|
2020-04-28 12:40:43 -04:00
|
|
|
if (eof === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
// Consume \r\n
|
2020-04-28 12:40:43 -04:00
|
|
|
if ((await tp.readLine()) === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
return chunkSize;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
assert(chunkSize === 0);
|
|
|
|
// Consume \r\n
|
2020-04-28 12:40:43 -04:00
|
|
|
if ((await r.readLine()) === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
await readTrailers(h, r);
|
|
|
|
finished = true;
|
2020-04-28 12:40:43 -04:00
|
|
|
return null;
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return { read };
|
|
|
|
}
|
|
|
|
|
2020-05-29 08:40:54 -04:00
|
|
|
function isProhibidedForTrailer(key: string): boolean {
|
|
|
|
const s = new Set(["transfer-encoding", "content-length", "trailer"]);
|
|
|
|
return s.has(key.toLowerCase());
|
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
|
2020-06-03 22:32:27 -04:00
|
|
|
/** Read trailer headers from reader and append values to headers. "trailer"
|
|
|
|
* field will be deleted. */
|
2020-02-24 22:49:39 -05:00
|
|
|
export async function readTrailers(
|
|
|
|
headers: Headers,
|
2020-07-14 15:24:17 -04:00
|
|
|
r: BufReader,
|
2020-02-24 22:49:39 -05:00
|
|
|
): Promise<void> {
|
2020-06-03 22:32:27 -04:00
|
|
|
const trailers = parseTrailer(headers.get("trailer"));
|
|
|
|
if (trailers == null) return;
|
|
|
|
const trailerNames = [...trailers.keys()];
|
2020-02-24 22:49:39 -05:00
|
|
|
const tp = new TextProtoReader(r);
|
|
|
|
const result = await tp.readMIMEHeader();
|
2020-06-03 22:32:27 -04:00
|
|
|
if (result == null) {
|
|
|
|
throw new Deno.errors.InvalidData("Missing trailer header.");
|
|
|
|
}
|
|
|
|
const undeclared = [...result.keys()].filter(
|
2020-07-14 15:24:17 -04:00
|
|
|
(k) => !trailerNames.includes(k),
|
2020-06-03 22:32:27 -04:00
|
|
|
);
|
|
|
|
if (undeclared.length > 0) {
|
|
|
|
throw new Deno.errors.InvalidData(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Undeclared trailers: ${Deno.inspect(undeclared)}.`,
|
2020-06-03 22:32:27 -04:00
|
|
|
);
|
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
for (const [k, v] of result) {
|
|
|
|
headers.append(k, v);
|
|
|
|
}
|
2020-06-03 22:32:27 -04:00
|
|
|
const missingTrailers = trailerNames.filter((k) => !result.has(k));
|
|
|
|
if (missingTrailers.length > 0) {
|
|
|
|
throw new Deno.errors.InvalidData(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Missing trailers: ${Deno.inspect(missingTrailers)}.`,
|
2020-06-03 22:32:27 -04:00
|
|
|
);
|
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
headers.delete("trailer");
|
|
|
|
}
|
|
|
|
|
2020-05-29 08:40:54 -04:00
|
|
|
function parseTrailer(field: string | null): Headers | undefined {
|
2020-02-24 22:49:39 -05:00
|
|
|
if (field == null) {
|
|
|
|
return undefined;
|
|
|
|
}
|
2020-06-03 22:32:27 -04:00
|
|
|
const trailerNames = field.split(",").map((v) => v.trim().toLowerCase());
|
|
|
|
if (trailerNames.length === 0) {
|
|
|
|
throw new Deno.errors.InvalidData("Empty trailer header.");
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
2020-06-03 22:32:27 -04:00
|
|
|
const prohibited = trailerNames.filter((k) => isProhibidedForTrailer(k));
|
|
|
|
if (prohibited.length > 0) {
|
|
|
|
throw new Deno.errors.InvalidData(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Prohibited trailer names: ${Deno.inspect(prohibited)}.`,
|
2020-06-03 22:32:27 -04:00
|
|
|
);
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
2020-06-03 22:32:27 -04:00
|
|
|
return new Headers(trailerNames.map((key) => [key, ""]));
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function writeChunkedBody(
|
2020-11-12 17:11:09 -05:00
|
|
|
w: BufWriter,
|
2020-07-14 15:24:17 -04:00
|
|
|
r: Deno.Reader,
|
2020-02-24 22:49:39 -05:00
|
|
|
): Promise<void> {
|
2020-04-22 15:30:45 -04:00
|
|
|
for await (const chunk of Deno.iter(r)) {
|
2020-02-24 22:49:39 -05:00
|
|
|
if (chunk.byteLength <= 0) continue;
|
|
|
|
const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`);
|
|
|
|
const end = encoder.encode("\r\n");
|
2020-11-12 17:11:09 -05:00
|
|
|
await w.write(start);
|
|
|
|
await w.write(chunk);
|
|
|
|
await w.write(end);
|
|
|
|
await w.flush();
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
const endChunk = encoder.encode("0\r\n\r\n");
|
2020-11-12 17:11:09 -05:00
|
|
|
await w.write(endChunk);
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
|
2020-06-03 22:32:27 -04:00
|
|
|
/** Write trailer headers to writer. It should mostly should be called after
|
|
|
|
* `writeResponse()`. */
|
2020-02-24 22:49:39 -05:00
|
|
|
export async function writeTrailers(
|
|
|
|
w: Deno.Writer,
|
|
|
|
headers: Headers,
|
2020-07-14 15:24:17 -04:00
|
|
|
trailers: Headers,
|
2020-02-24 22:49:39 -05:00
|
|
|
): Promise<void> {
|
|
|
|
const trailer = headers.get("trailer");
|
|
|
|
if (trailer === null) {
|
2020-06-03 22:32:27 -04:00
|
|
|
throw new TypeError("Missing trailer header.");
|
2020-02-24 22:49:39 -05:00
|
|
|
}
|
|
|
|
const transferEncoding = headers.get("transfer-encoding");
|
|
|
|
if (transferEncoding === null || !transferEncoding.match(/^chunked/)) {
|
2020-06-03 22:32:27 -04:00
|
|
|
throw new TypeError(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Trailers are only allowed for "transfer-encoding: chunked", got "transfer-encoding: ${transferEncoding}".`,
|
2020-02-24 22:49:39 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
const writer = BufWriter.create(w);
|
2020-06-03 22:32:27 -04:00
|
|
|
const trailerNames = trailer.split(",").map((s) => s.trim().toLowerCase());
|
|
|
|
const prohibitedTrailers = trailerNames.filter((k) =>
|
|
|
|
isProhibidedForTrailer(k)
|
|
|
|
);
|
|
|
|
if (prohibitedTrailers.length > 0) {
|
|
|
|
throw new TypeError(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Prohibited trailer names: ${Deno.inspect(prohibitedTrailers)}.`,
|
2020-02-24 22:49:39 -05:00
|
|
|
);
|
|
|
|
}
|
2020-06-03 22:32:27 -04:00
|
|
|
const undeclared = [...trailers.keys()].filter(
|
2020-07-14 15:24:17 -04:00
|
|
|
(k) => !trailerNames.includes(k),
|
2020-06-03 22:32:27 -04:00
|
|
|
);
|
|
|
|
if (undeclared.length > 0) {
|
|
|
|
throw new TypeError(`Undeclared trailers: ${Deno.inspect(undeclared)}.`);
|
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
for (const [key, value] of trailers) {
|
|
|
|
await writer.write(encoder.encode(`${key}: ${value}\r\n`));
|
|
|
|
}
|
|
|
|
await writer.write(encoder.encode("\r\n"));
|
|
|
|
await writer.flush();
|
|
|
|
}
|
2020-02-26 10:48:35 -05:00
|
|
|
|
|
|
|
export async function writeResponse(
|
|
|
|
w: Deno.Writer,
|
2020-07-14 15:24:17 -04:00
|
|
|
r: Response,
|
2020-02-26 10:48:35 -05:00
|
|
|
): Promise<void> {
|
|
|
|
const protoMajor = 1;
|
|
|
|
const protoMinor = 1;
|
|
|
|
const statusCode = r.status || 200;
|
|
|
|
const statusText = STATUS_TEXT.get(statusCode);
|
|
|
|
const writer = BufWriter.create(w);
|
|
|
|
if (!statusText) {
|
2020-03-19 19:15:21 -04:00
|
|
|
throw new Deno.errors.InvalidData("Bad status code");
|
2020-02-26 10:48:35 -05:00
|
|
|
}
|
|
|
|
if (!r.body) {
|
|
|
|
r.body = new Uint8Array();
|
|
|
|
}
|
|
|
|
if (typeof r.body === "string") {
|
|
|
|
r.body = encoder.encode(r.body);
|
|
|
|
}
|
|
|
|
|
|
|
|
let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`;
|
|
|
|
|
2020-05-01 10:35:18 -04:00
|
|
|
const headers = r.headers ?? new Headers();
|
|
|
|
|
|
|
|
if (r.body && !headers.get("content-length")) {
|
|
|
|
if (r.body instanceof Uint8Array) {
|
|
|
|
out += `content-length: ${r.body.byteLength}\r\n`;
|
|
|
|
} else if (!headers.get("transfer-encoding")) {
|
|
|
|
out += "transfer-encoding: chunked\r\n";
|
|
|
|
}
|
|
|
|
}
|
2020-02-26 10:48:35 -05:00
|
|
|
|
|
|
|
for (const [key, value] of headers) {
|
|
|
|
out += `${key}: ${value}\r\n`;
|
|
|
|
}
|
2020-05-01 10:35:18 -04:00
|
|
|
|
|
|
|
out += `\r\n`;
|
2020-02-26 10:48:35 -05:00
|
|
|
|
|
|
|
const header = encoder.encode(out);
|
|
|
|
const n = await writer.write(header);
|
|
|
|
assert(n === header.byteLength);
|
|
|
|
|
|
|
|
if (r.body instanceof Uint8Array) {
|
|
|
|
const n = await writer.write(r.body);
|
|
|
|
assert(n === r.body.byteLength);
|
|
|
|
} else if (headers.has("content-length")) {
|
|
|
|
const contentLength = headers.get("content-length");
|
|
|
|
assert(contentLength != null);
|
|
|
|
const bodyLength = parseInt(contentLength);
|
2020-04-24 18:09:14 -04:00
|
|
|
const n = await Deno.copy(r.body, writer);
|
2020-02-26 10:48:35 -05:00
|
|
|
assert(n === bodyLength);
|
|
|
|
} else {
|
|
|
|
await writeChunkedBody(writer, r.body);
|
|
|
|
}
|
|
|
|
if (r.trailers) {
|
|
|
|
const t = await r.trailers();
|
|
|
|
await writeTrailers(writer, headers, t);
|
|
|
|
}
|
|
|
|
await writer.flush();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ParseHTTPVersion parses a HTTP version string.
|
2020-04-27 14:08:20 -04:00
|
|
|
* "HTTP/1.0" returns (1, 0).
|
2020-02-26 10:48:35 -05:00
|
|
|
* Ported from https://github.com/golang/go/blob/f5c43b9/src/net/http/request.go#L766-L792
|
|
|
|
*/
|
|
|
|
export function parseHTTPVersion(vers: string): [number, number] {
|
|
|
|
switch (vers) {
|
|
|
|
case "HTTP/1.1":
|
|
|
|
return [1, 1];
|
|
|
|
|
|
|
|
case "HTTP/1.0":
|
|
|
|
return [1, 0];
|
|
|
|
|
|
|
|
default: {
|
|
|
|
const Big = 1000000; // arbitrary upper bound
|
|
|
|
|
|
|
|
if (!vers.startsWith("HTTP/")) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
const dot = vers.indexOf(".");
|
|
|
|
if (dot < 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
const majorStr = vers.substring(vers.indexOf("/") + 1, dot);
|
2020-04-27 14:08:20 -04:00
|
|
|
const major = Number(majorStr);
|
|
|
|
if (!Number.isInteger(major) || major < 0 || major > Big) {
|
2020-02-26 10:48:35 -05:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
const minorStr = vers.substring(dot + 1);
|
2020-04-27 14:08:20 -04:00
|
|
|
const minor = Number(minorStr);
|
|
|
|
if (!Number.isInteger(minor) || minor < 0 || minor > Big) {
|
2020-02-26 10:48:35 -05:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
return [major, minor];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`malformed HTTP version ${vers}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function readRequest(
|
|
|
|
conn: Deno.Conn,
|
2020-07-14 15:24:17 -04:00
|
|
|
bufr: BufReader,
|
2020-04-28 12:40:43 -04:00
|
|
|
): Promise<ServerRequest | null> {
|
2020-04-02 15:20:17 -04:00
|
|
|
const tp = new TextProtoReader(bufr);
|
|
|
|
const firstLine = await tp.readLine(); // e.g. GET /index.html HTTP/1.0
|
2020-04-28 12:40:43 -04:00
|
|
|
if (firstLine === null) return null;
|
2020-04-02 15:20:17 -04:00
|
|
|
const headers = await tp.readMIMEHeader();
|
2020-04-28 12:40:43 -04:00
|
|
|
if (headers === null) throw new Deno.errors.UnexpectedEof();
|
2020-02-26 10:48:35 -05:00
|
|
|
|
|
|
|
const req = new ServerRequest();
|
|
|
|
req.conn = conn;
|
2020-04-02 15:20:17 -04:00
|
|
|
req.r = bufr;
|
2020-02-26 10:48:35 -05:00
|
|
|
[req.method, req.url, req.proto] = firstLine.split(" ", 3);
|
2020-12-30 18:17:41 -05:00
|
|
|
[req.protoMajor, req.protoMinor] = parseHTTPVersion(req.proto);
|
2020-02-26 10:48:35 -05:00
|
|
|
req.headers = headers;
|
|
|
|
fixLength(req);
|
|
|
|
return req;
|
|
|
|
}
|
|
|
|
|
|
|
|
function fixLength(req: ServerRequest): void {
|
|
|
|
const contentLength = req.headers.get("Content-Length");
|
|
|
|
if (contentLength) {
|
|
|
|
const arrClen = contentLength.split(",");
|
|
|
|
if (arrClen.length > 1) {
|
|
|
|
const distinct = [...new Set(arrClen.map((e): string => e.trim()))];
|
|
|
|
if (distinct.length > 1) {
|
|
|
|
throw Error("cannot contain multiple Content-Length headers");
|
|
|
|
} else {
|
|
|
|
req.headers.set("Content-Length", distinct[0]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const c = req.headers.get("Content-Length");
|
|
|
|
if (req.method === "HEAD" && c && c !== "0") {
|
|
|
|
throw Error("http: method cannot contain a Content-Length");
|
|
|
|
}
|
|
|
|
if (c && req.headers.has("transfer-encoding")) {
|
|
|
|
// A sender MUST NOT send a Content-Length header field in any message
|
|
|
|
// that contains a Transfer-Encoding header field.
|
|
|
|
// rfc: https://tools.ietf.org/html/rfc7230#section-3.3.2
|
|
|
|
throw new Error(
|
2020-07-14 15:24:17 -04:00
|
|
|
"http: Transfer-Encoding and Content-Length cannot be send together",
|
2020-02-26 10:48:35 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|