2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-11-04 13:45:29 -05:00
|
|
|
const { listen, listenTLS, copy, toAsyncIterator } = Deno;
|
2019-05-20 09:17:26 -04:00
|
|
|
type Listener = Deno.Listener;
|
2019-03-07 19:25:16 -05:00
|
|
|
type Conn = Deno.Conn;
|
|
|
|
type Reader = Deno.Reader;
|
|
|
|
type Writer = Deno.Writer;
|
2019-07-07 15:20:41 -04:00
|
|
|
import { BufReader, BufWriter, UnexpectedEOFError } from "../io/bufio.ts";
|
2019-01-12 16:50:04 -05:00
|
|
|
import { TextProtoReader } from "../textproto/mod.ts";
|
2018-12-23 18:49:46 -05:00
|
|
|
import { STATUS_TEXT } from "./http_status.ts";
|
2019-05-23 22:04:06 -04:00
|
|
|
import { assert } from "../testing/asserts.ts";
|
2020-01-02 12:34:33 -05:00
|
|
|
import { deferred, Deferred, MuxAsyncIterator } from "../util/async.ts";
|
2019-04-13 15:23:56 -04:00
|
|
|
|
2020-01-17 18:44:35 -05:00
|
|
|
const encoder = new TextEncoder();
|
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
function bufWriter(w: Writer): BufWriter {
|
|
|
|
if (w instanceof BufWriter) {
|
|
|
|
return w;
|
|
|
|
} else {
|
|
|
|
return new BufWriter(w);
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
2018-11-08 15:03:45 -05:00
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
export function setContentLength(r: Response): void {
|
|
|
|
if (!r.headers) {
|
|
|
|
r.headers = new Headers();
|
|
|
|
}
|
2018-11-07 13:16:07 -05:00
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
if (r.body) {
|
|
|
|
if (!r.headers.has("content-length")) {
|
2020-01-17 18:44:35 -05:00
|
|
|
// typeof r.body === "string" handled in writeResponse.
|
2019-03-09 11:46:53 -05:00
|
|
|
if (r.body instanceof Uint8Array) {
|
|
|
|
const bodyLength = r.body.byteLength;
|
|
|
|
r.headers.append("Content-Length", bodyLength.toString());
|
|
|
|
} else {
|
|
|
|
r.headers.append("Transfer-Encoding", "chunked");
|
|
|
|
}
|
2018-11-08 15:03:45 -05:00
|
|
|
}
|
2018-11-07 13:16:07 -05:00
|
|
|
}
|
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
|
2019-03-12 01:51:51 -04:00
|
|
|
async function writeChunkedBody(w: Writer, r: Reader): Promise<void> {
|
2019-03-09 11:46:53 -05:00
|
|
|
const writer = bufWriter(w);
|
2018-11-07 13:16:07 -05:00
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
for await (const chunk of toAsyncIterator(r)) {
|
2019-05-10 12:55:18 -04:00
|
|
|
if (chunk.byteLength <= 0) continue;
|
2019-03-09 11:46:53 -05:00
|
|
|
const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`);
|
|
|
|
const end = encoder.encode("\r\n");
|
|
|
|
await writer.write(start);
|
|
|
|
await writer.write(chunk);
|
|
|
|
await writer.write(end);
|
2019-02-18 18:32:31 -05:00
|
|
|
}
|
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
const endChunk = encoder.encode("0\r\n\r\n");
|
|
|
|
await writer.write(endChunk);
|
2019-02-15 11:03:57 -05:00
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
export async function writeResponse(w: Writer, r: Response): Promise<void> {
|
|
|
|
const protoMajor = 1;
|
|
|
|
const protoMinor = 1;
|
|
|
|
const statusCode = r.status || 200;
|
|
|
|
const statusText = STATUS_TEXT.get(statusCode);
|
|
|
|
const writer = bufWriter(w);
|
|
|
|
if (!statusText) {
|
|
|
|
throw Error("bad status code");
|
|
|
|
}
|
2019-05-22 22:33:17 -04:00
|
|
|
if (!r.body) {
|
|
|
|
r.body = new Uint8Array();
|
|
|
|
}
|
2020-01-17 18:44:35 -05:00
|
|
|
if (typeof r.body === "string") {
|
|
|
|
r.body = encoder.encode(r.body);
|
|
|
|
}
|
2019-02-15 11:03:57 -05:00
|
|
|
|
2019-03-09 11:46:53 -05:00
|
|
|
let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`;
|
|
|
|
|
|
|
|
setContentLength(r);
|
2020-02-07 02:23:38 -05:00
|
|
|
assert(r.headers != null);
|
|
|
|
const headers = r.headers;
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2020-02-07 02:23:38 -05:00
|
|
|
for (const [key, value] of headers) {
|
2019-05-30 08:59:30 -04:00
|
|
|
out += `${key}: ${value}\r\n`;
|
2019-02-15 11:03:57 -05:00
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
out += "\r\n";
|
|
|
|
|
2020-01-17 18:44:35 -05:00
|
|
|
const header = encoder.encode(out);
|
2019-05-22 22:33:17 -04:00
|
|
|
const n = await writer.write(header);
|
|
|
|
assert(n === header.byteLength);
|
2019-02-15 11:03:57 -05:00
|
|
|
|
2019-05-22 22:33:17 -04:00
|
|
|
if (r.body instanceof Uint8Array) {
|
|
|
|
const n = await writer.write(r.body);
|
|
|
|
assert(n === r.body.byteLength);
|
2019-05-30 08:59:30 -04:00
|
|
|
} else if (headers.has("content-length")) {
|
2020-02-07 02:23:38 -05:00
|
|
|
const contentLength = headers.get("content-length");
|
|
|
|
assert(contentLength != null);
|
|
|
|
const bodyLength = parseInt(contentLength);
|
2019-05-22 22:33:17 -04:00
|
|
|
const n = await copy(writer, r.body);
|
|
|
|
assert(n === bodyLength);
|
|
|
|
} else {
|
|
|
|
await writeChunkedBody(writer, r.body);
|
2018-12-17 11:49:10 -05:00
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
await writer.flush();
|
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
|
2020-01-02 12:34:33 -05:00
|
|
|
export class ServerRequestBody implements Reader {
|
|
|
|
constructor(private it: AsyncIterator<number, undefined, Uint8Array>) {}
|
|
|
|
async read(p: Uint8Array): Promise<number | Deno.EOF> {
|
|
|
|
const res = await this.it.next(p);
|
|
|
|
if (res.done) {
|
|
|
|
return Deno.EOF;
|
|
|
|
}
|
|
|
|
return res.value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-19 12:38:19 -05:00
|
|
|
export class ServerRequest {
|
2019-05-30 08:59:30 -04:00
|
|
|
url!: string;
|
|
|
|
method!: string;
|
|
|
|
proto!: string;
|
|
|
|
protoMinor!: number;
|
|
|
|
protoMajor!: number;
|
|
|
|
headers!: Headers;
|
2019-08-05 18:03:55 -04:00
|
|
|
conn!: Conn;
|
2019-05-30 08:59:30 -04:00
|
|
|
r!: BufReader;
|
|
|
|
w!: BufWriter;
|
2019-12-11 19:46:03 -05:00
|
|
|
done: Deferred<Error | undefined> = deferred();
|
2019-02-19 12:38:19 -05:00
|
|
|
|
2020-01-02 12:34:33 -05:00
|
|
|
private _contentLength: number | undefined | null = undefined;
|
|
|
|
/**
|
|
|
|
* Value of Content-Length header.
|
|
|
|
* If null, then content length is invalid or not given (e.g. chunked encoding).
|
|
|
|
*/
|
|
|
|
get contentLength(): number | null {
|
|
|
|
// undefined means not cached.
|
|
|
|
// null means invalid or not provided.
|
|
|
|
if (this._contentLength === undefined) {
|
2020-02-07 02:23:38 -05:00
|
|
|
const cl = this.headers.get("content-length");
|
|
|
|
if (cl) {
|
|
|
|
this._contentLength = parseInt(cl);
|
2020-01-02 12:34:33 -05:00
|
|
|
// Convert NaN to null (as NaN harder to test)
|
|
|
|
if (Number.isNaN(this._contentLength)) {
|
|
|
|
this._contentLength = null;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
this._contentLength = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return this._contentLength;
|
|
|
|
}
|
|
|
|
|
|
|
|
private _body: ServerRequestBody | null = null;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Body of the request.
|
|
|
|
*
|
|
|
|
* const buf = new Uint8Array(req.contentLength);
|
|
|
|
* let bufSlice = buf;
|
|
|
|
* let totRead = 0;
|
|
|
|
* while (true) {
|
|
|
|
* const nread = await req.body.read(bufSlice);
|
|
|
|
* if (nread === Deno.EOF) break;
|
|
|
|
* totRead += nread;
|
|
|
|
* if (totRead >= req.contentLength) break;
|
|
|
|
* bufSlice = bufSlice.subarray(nread);
|
|
|
|
* }
|
|
|
|
*/
|
|
|
|
get body(): ServerRequestBody {
|
|
|
|
if (!this._body) {
|
|
|
|
const stream = this._bodyStream();
|
|
|
|
stream.next(); // drop dummy such that first read is not empty.
|
|
|
|
this._body = new ServerRequestBody(stream);
|
|
|
|
}
|
|
|
|
return this._body;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal: actually reading body. Each step, buf to use is passed
|
|
|
|
* in through yield result.
|
|
|
|
* Returns on no more data to read or error.
|
|
|
|
*/
|
|
|
|
private async *_bodyStream(): AsyncIterator<number, undefined, Uint8Array> {
|
|
|
|
let buf = yield 0; // dummy yield to retrieve user provided buf.
|
2019-02-19 12:38:19 -05:00
|
|
|
if (this.headers.has("content-length")) {
|
2020-01-02 12:34:33 -05:00
|
|
|
const len = this.contentLength;
|
|
|
|
if (len === null) {
|
|
|
|
return;
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
|
|
|
let rr = await this.r.read(buf);
|
2019-07-07 15:20:41 -04:00
|
|
|
let nread = rr === Deno.EOF ? 0 : rr;
|
|
|
|
let nreadTotal = nread;
|
|
|
|
while (rr !== Deno.EOF && nreadTotal < len) {
|
2020-01-02 12:34:33 -05:00
|
|
|
buf = yield nread;
|
2019-02-19 12:38:19 -05:00
|
|
|
rr = await this.r.read(buf);
|
2019-07-07 15:20:41 -04:00
|
|
|
nread = rr === Deno.EOF ? 0 : rr;
|
|
|
|
nreadTotal += nread;
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
2020-01-02 12:34:33 -05:00
|
|
|
yield nread;
|
2019-02-19 12:38:19 -05:00
|
|
|
} else {
|
2020-02-07 02:23:38 -05:00
|
|
|
const transferEncoding = this.headers.get("transfer-encoding");
|
|
|
|
if (transferEncoding) {
|
|
|
|
const parts = transferEncoding
|
2019-02-19 12:38:19 -05:00
|
|
|
.split(",")
|
2019-04-24 07:41:23 -04:00
|
|
|
.map((e): string => e.trim().toLowerCase());
|
2020-02-07 02:23:38 -05:00
|
|
|
if (parts.includes("chunked")) {
|
2019-02-19 12:38:19 -05:00
|
|
|
// Based on https://tools.ietf.org/html/rfc2616#section-19.4.6
|
|
|
|
const tp = new TextProtoReader(this.r);
|
2019-05-23 22:04:06 -04:00
|
|
|
let line = await tp.readLine();
|
2019-07-07 15:20:41 -04:00
|
|
|
if (line === Deno.EOF) throw new UnexpectedEOFError();
|
2019-02-19 12:38:19 -05:00
|
|
|
// TODO: handle chunk extension
|
2019-10-05 12:02:34 -04:00
|
|
|
const [chunkSizeString] = line.split(";");
|
2019-02-19 12:38:19 -05:00
|
|
|
let chunkSize = parseInt(chunkSizeString, 16);
|
|
|
|
if (Number.isNaN(chunkSize) || chunkSize < 0) {
|
|
|
|
throw new Error("Invalid chunk size");
|
|
|
|
}
|
|
|
|
while (chunkSize > 0) {
|
2020-01-02 12:34:33 -05:00
|
|
|
let currChunkOffset = 0;
|
|
|
|
// Since given readBuffer might be smaller, loop.
|
|
|
|
while (currChunkOffset < chunkSize) {
|
|
|
|
// Try to be as large as chunkSize. Might be smaller though.
|
|
|
|
const bufferToFill = buf.subarray(0, chunkSize);
|
|
|
|
if ((await this.r.readFull(bufferToFill)) === Deno.EOF) {
|
|
|
|
throw new UnexpectedEOFError();
|
|
|
|
}
|
|
|
|
currChunkOffset += bufferToFill.length;
|
|
|
|
buf = yield bufferToFill.length;
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
|
|
|
await this.r.readLine(); // Consume \r\n
|
2019-05-23 22:04:06 -04:00
|
|
|
line = await tp.readLine();
|
2019-07-07 15:20:41 -04:00
|
|
|
if (line === Deno.EOF) throw new UnexpectedEOFError();
|
2019-02-19 12:38:19 -05:00
|
|
|
chunkSize = parseInt(line, 16);
|
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
const entityHeaders = await tp.readMIMEHeader();
|
2019-07-07 15:20:41 -04:00
|
|
|
if (entityHeaders !== Deno.EOF) {
|
2019-10-05 12:02:34 -04:00
|
|
|
for (const [k, v] of entityHeaders) {
|
2019-02-19 12:38:19 -05:00
|
|
|
this.headers.set(k, v);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Pseudo code from https://tools.ietf.org/html/rfc2616#section-19.4.6
|
|
|
|
length := 0
|
|
|
|
read chunk-size, chunk-extension (if any) and CRLF
|
|
|
|
while (chunk-size > 0) {
|
|
|
|
read chunk-data and CRLF
|
|
|
|
append chunk-data to entity-body
|
|
|
|
length := length + chunk-size
|
|
|
|
read chunk-size and CRLF
|
|
|
|
}
|
|
|
|
read entity-header
|
|
|
|
while (entity-header not empty) {
|
|
|
|
append entity-header to existing header fields
|
|
|
|
read entity-header
|
|
|
|
}
|
|
|
|
Content-Length := length
|
|
|
|
Remove "chunked" from Transfer-Encoding
|
|
|
|
*/
|
|
|
|
return; // Must return here to avoid fall through
|
|
|
|
}
|
|
|
|
// TODO: handle other transfer-encoding types
|
|
|
|
}
|
2020-01-02 12:34:33 -05:00
|
|
|
// Otherwise... Do nothing
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async respond(r: Response): Promise<void> {
|
2019-12-11 19:46:03 -05:00
|
|
|
let err: Error | undefined;
|
|
|
|
try {
|
|
|
|
// Write our response!
|
|
|
|
await writeResponse(this.w, r);
|
|
|
|
} catch (e) {
|
|
|
|
try {
|
|
|
|
// Eagerly close on error.
|
|
|
|
this.conn.close();
|
|
|
|
} catch {}
|
|
|
|
err = e;
|
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
// Signal that this request has been processed and the next pipelined
|
|
|
|
// request on the same connection can be accepted.
|
2019-12-11 19:46:03 -05:00
|
|
|
this.done.resolve(err);
|
|
|
|
if (err) {
|
|
|
|
// Error during responding, rethrow.
|
|
|
|
throw err;
|
|
|
|
}
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-23 11:59:34 -04:00
|
|
|
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");
|
|
|
|
}
|
2019-05-29 13:44:14 -04:00
|
|
|
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(
|
|
|
|
"http: Transfer-Encoding and Content-Length cannot be send together"
|
|
|
|
);
|
|
|
|
}
|
2019-05-23 11:59:34 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-07 14:00:27 -05:00
|
|
|
/**
|
|
|
|
* ParseHTTPVersion parses a HTTP version string.
|
|
|
|
* "HTTP/1.0" returns (1, 0, true).
|
|
|
|
* Ported from https://github.com/golang/go/blob/f5c43b9/src/net/http/request.go#L766-L792
|
|
|
|
*/
|
2019-05-23 22:04:06 -04:00
|
|
|
export function parseHTTPVersion(vers: string): [number, number] {
|
2019-05-25 12:22:30 -04:00
|
|
|
switch (vers) {
|
|
|
|
case "HTTP/1.1":
|
2019-05-23 22:04:06 -04:00
|
|
|
return [1, 1];
|
|
|
|
|
2019-05-25 12:22:30 -04:00
|
|
|
case "HTTP/1.0":
|
2019-05-23 22:04:06 -04:00
|
|
|
return [1, 0];
|
2019-05-25 12:22:30 -04:00
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
default: {
|
|
|
|
const Big = 1000000; // arbitrary upper bound
|
|
|
|
const digitReg = /^\d+$/; // test if string is only digit
|
2019-05-25 12:22:30 -04:00
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
if (!vers.startsWith("HTTP/")) {
|
|
|
|
break;
|
|
|
|
}
|
2019-05-25 12:22:30 -04:00
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
const dot = vers.indexOf(".");
|
|
|
|
if (dot < 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2019-10-05 12:02:34 -04:00
|
|
|
const majorStr = vers.substring(vers.indexOf("/") + 1, dot);
|
|
|
|
const major = parseInt(majorStr);
|
2019-05-23 22:04:06 -04:00
|
|
|
if (
|
|
|
|
!digitReg.test(majorStr) ||
|
|
|
|
isNaN(major) ||
|
|
|
|
major < 0 ||
|
|
|
|
major > Big
|
|
|
|
) {
|
|
|
|
break;
|
|
|
|
}
|
2019-05-25 12:22:30 -04:00
|
|
|
|
2019-10-05 12:02:34 -04:00
|
|
|
const minorStr = vers.substring(dot + 1);
|
|
|
|
const minor = parseInt(minorStr);
|
2019-05-23 22:04:06 -04:00
|
|
|
if (
|
|
|
|
!digitReg.test(minorStr) ||
|
|
|
|
isNaN(minor) ||
|
|
|
|
minor < 0 ||
|
|
|
|
minor > Big
|
|
|
|
) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
return [major, minor];
|
|
|
|
}
|
2019-05-25 12:22:30 -04:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
|
|
|
throw new Error(`malformed HTTP version ${vers}`);
|
2019-05-25 12:22:30 -04:00
|
|
|
}
|
|
|
|
|
2019-05-22 19:28:03 -04:00
|
|
|
export async function readRequest(
|
2019-08-05 18:03:55 -04:00
|
|
|
conn: Conn,
|
2019-05-20 09:17:26 -04:00
|
|
|
bufr: BufReader
|
2019-07-07 15:20:41 -04:00
|
|
|
): Promise<ServerRequest | Deno.EOF> {
|
2019-05-23 22:04:06 -04:00
|
|
|
const tp = new TextProtoReader(bufr);
|
|
|
|
const firstLine = await tp.readLine(); // e.g. GET /index.html HTTP/1.0
|
2019-07-07 15:20:41 -04:00
|
|
|
if (firstLine === Deno.EOF) return Deno.EOF;
|
2019-05-23 22:04:06 -04:00
|
|
|
const headers = await tp.readMIMEHeader();
|
2019-07-07 15:20:41 -04:00
|
|
|
if (headers === Deno.EOF) throw new UnexpectedEOFError();
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2019-02-19 12:38:19 -05:00
|
|
|
const req = new ServerRequest();
|
2019-08-05 18:03:55 -04:00
|
|
|
req.conn = conn;
|
2019-05-20 09:17:26 -04:00
|
|
|
req.r = bufr;
|
|
|
|
[req.method, req.url, req.proto] = firstLine.split(" ", 3);
|
2019-05-23 22:04:06 -04:00
|
|
|
[req.protoMinor, req.protoMajor] = parseHTTPVersion(req.proto);
|
|
|
|
req.headers = headers;
|
2019-05-23 11:59:34 -04:00
|
|
|
fixLength(req);
|
2019-05-23 22:04:06 -04:00
|
|
|
return req;
|
2018-11-07 01:08:51 -05:00
|
|
|
}
|
2018-12-18 20:48:05 -05:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
export class Server implements AsyncIterable<ServerRequest> {
|
|
|
|
private closing = false;
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
constructor(public listener: Listener) {}
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
close(): void {
|
|
|
|
this.closing = true;
|
|
|
|
this.listener.close();
|
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
// Yields all HTTP requests on a single TCP connection.
|
|
|
|
private async *iterateHttpRequests(
|
|
|
|
conn: Conn
|
|
|
|
): AsyncIterableIterator<ServerRequest> {
|
|
|
|
const bufr = new BufReader(conn);
|
2019-05-22 09:30:10 -04:00
|
|
|
const w = new BufWriter(conn);
|
2019-07-07 15:20:41 -04:00
|
|
|
let req: ServerRequest | Deno.EOF;
|
2019-05-23 22:04:06 -04:00
|
|
|
let err: Error | undefined;
|
2019-05-20 09:17:26 -04:00
|
|
|
|
|
|
|
while (!this.closing) {
|
2019-05-22 19:28:03 -04:00
|
|
|
try {
|
2019-08-05 18:03:55 -04:00
|
|
|
req = await readRequest(conn, bufr);
|
2019-05-23 22:04:06 -04:00
|
|
|
} catch (e) {
|
|
|
|
err = e;
|
|
|
|
break;
|
|
|
|
}
|
2019-07-07 15:20:41 -04:00
|
|
|
if (req === Deno.EOF) {
|
2019-05-23 22:04:06 -04:00
|
|
|
break;
|
2019-05-22 19:28:03 -04:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2019-05-22 09:30:10 -04:00
|
|
|
req.w = w;
|
2019-05-20 09:17:26 -04:00
|
|
|
yield req;
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
// Wait for the request to be processed before we accept a new request on
|
|
|
|
// this connection.
|
2020-02-07 02:23:38 -05:00
|
|
|
const procError = await req.done;
|
2019-12-11 19:46:03 -05:00
|
|
|
if (procError) {
|
|
|
|
// Something bad happened during response.
|
|
|
|
// (likely other side closed during pipelined req)
|
|
|
|
// req.done implies this connection already closed, so we can just return.
|
|
|
|
return;
|
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2020-02-07 02:23:38 -05:00
|
|
|
if (req === Deno.EOF) {
|
2019-05-20 09:17:26 -04:00
|
|
|
// The connection was gracefully closed.
|
2020-02-07 02:23:38 -05:00
|
|
|
} else if (err && req) {
|
2019-05-22 19:28:03 -04:00
|
|
|
// An error was thrown while parsing request headers.
|
2019-07-28 07:35:47 -04:00
|
|
|
try {
|
2020-02-07 02:23:38 -05:00
|
|
|
await writeResponse(req.w, {
|
2019-07-28 07:35:47 -04:00
|
|
|
status: 400,
|
2020-01-17 18:44:35 -05:00
|
|
|
body: encoder.encode(`${err.message}\r\n\r\n`)
|
2019-07-28 07:35:47 -04:00
|
|
|
});
|
|
|
|
} catch (_) {
|
|
|
|
// The connection is destroyed.
|
|
|
|
// Ignores the error.
|
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
} else if (this.closing) {
|
|
|
|
// There are more requests incoming but the server is closing.
|
|
|
|
// TODO(ry): send a back a HTTP 503 Service Unavailable status.
|
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
conn.close();
|
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
|
2019-05-20 09:17:26 -04:00
|
|
|
// Accepts a new TCP connection and yields all HTTP requests that arrive on
|
|
|
|
// it. When a connection is accepted, it also creates a new iterator of the
|
|
|
|
// same kind and adds it to the request multiplexer so that another TCP
|
|
|
|
// connection can be accepted.
|
|
|
|
private async *acceptConnAndIterateHttpRequests(
|
|
|
|
mux: MuxAsyncIterator<ServerRequest>
|
|
|
|
): AsyncIterableIterator<ServerRequest> {
|
|
|
|
if (this.closing) return;
|
|
|
|
// Wait for a new connection.
|
2019-11-09 14:40:22 -05:00
|
|
|
const { value, done } = await this.listener.next();
|
|
|
|
if (done) return;
|
|
|
|
const conn = value as Conn;
|
2019-05-20 09:17:26 -04:00
|
|
|
// Try to accept another connection and add it to the multiplexer.
|
|
|
|
mux.add(this.acceptConnAndIterateHttpRequests(mux));
|
|
|
|
// Yield the requests that arrive on the just-accepted connection.
|
|
|
|
yield* this.iterateHttpRequests(conn);
|
2018-12-18 20:48:05 -05:00
|
|
|
}
|
2019-05-20 09:17:26 -04:00
|
|
|
|
|
|
|
[Symbol.asyncIterator](): AsyncIterableIterator<ServerRequest> {
|
|
|
|
const mux: MuxAsyncIterator<ServerRequest> = new MuxAsyncIterator();
|
|
|
|
mux.add(this.acceptConnAndIterateHttpRequests(mux));
|
|
|
|
return mux.iterate();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-04 09:15:23 -05:00
|
|
|
/** Options for creating an HTTP server. */
|
|
|
|
export type HTTPOptions = Omit<Deno.ListenOptions, "transport">;
|
2019-11-06 12:18:28 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Start a HTTP server
|
|
|
|
*
|
|
|
|
* import { serve } from "https://deno.land/std/http/server.ts";
|
2020-01-17 18:44:35 -05:00
|
|
|
* const body = "Hello World\n";
|
2019-11-06 12:18:28 -05:00
|
|
|
* const s = serve({ port: 8000 });
|
|
|
|
* for await (const req of s) {
|
|
|
|
* req.respond({ body });
|
|
|
|
* }
|
|
|
|
*/
|
2020-02-04 09:15:23 -05:00
|
|
|
export function serve(addr: string | HTTPOptions): Server {
|
2019-11-06 12:18:28 -05:00
|
|
|
if (typeof addr === "string") {
|
|
|
|
const [hostname, port] = addr.split(":");
|
|
|
|
addr = { hostname, port: Number(port) };
|
|
|
|
}
|
|
|
|
|
|
|
|
const listener = listen(addr);
|
2019-05-20 09:17:26 -04:00
|
|
|
return new Server(listener);
|
2019-03-09 11:46:53 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function listenAndServe(
|
2020-02-04 09:15:23 -05:00
|
|
|
addr: string | HTTPOptions,
|
2019-03-09 11:46:53 -05:00
|
|
|
handler: (req: ServerRequest) => void
|
2019-03-12 01:51:51 -04:00
|
|
|
): Promise<void> {
|
2019-03-09 11:46:53 -05:00
|
|
|
const server = serve(addr);
|
|
|
|
|
|
|
|
for await (const request of server) {
|
2019-05-20 20:08:39 -04:00
|
|
|
handler(request);
|
2018-12-18 20:48:05 -05:00
|
|
|
}
|
2019-03-09 11:46:53 -05:00
|
|
|
}
|
|
|
|
|
2019-11-04 13:45:29 -05:00
|
|
|
/** Options for creating an HTTPS server. */
|
|
|
|
export type HTTPSOptions = Omit<Deno.ListenTLSOptions, "transport">;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create an HTTPS server with given options
|
2019-11-06 12:18:28 -05:00
|
|
|
*
|
2020-01-17 18:44:35 -05:00
|
|
|
* const body = "Hello HTTPS";
|
2019-11-06 12:18:28 -05:00
|
|
|
* const options = {
|
|
|
|
* hostname: "localhost",
|
|
|
|
* port: 443,
|
|
|
|
* certFile: "./path/to/localhost.crt",
|
|
|
|
* keyFile: "./path/to/localhost.key",
|
|
|
|
* };
|
|
|
|
* for await (const req of serveTLS(options)) {
|
|
|
|
* req.respond({ body });
|
|
|
|
* }
|
|
|
|
*
|
2019-11-04 13:45:29 -05:00
|
|
|
* @param options Server configuration
|
|
|
|
* @return Async iterable server instance for incoming requests
|
|
|
|
*/
|
|
|
|
export function serveTLS(options: HTTPSOptions): Server {
|
|
|
|
const tlsOptions: Deno.ListenTLSOptions = {
|
|
|
|
...options,
|
|
|
|
transport: "tcp"
|
|
|
|
};
|
|
|
|
const listener = listenTLS(tlsOptions);
|
|
|
|
return new Server(listener);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create an HTTPS server with given options and request handler
|
2019-11-07 14:00:27 -05:00
|
|
|
*
|
2020-01-17 18:44:35 -05:00
|
|
|
* const body = "Hello HTTPS";
|
2019-11-07 14:00:27 -05:00
|
|
|
* const options = {
|
|
|
|
* hostname: "localhost",
|
|
|
|
* port: 443,
|
|
|
|
* certFile: "./path/to/localhost.crt",
|
|
|
|
* keyFile: "./path/to/localhost.key",
|
|
|
|
* };
|
|
|
|
* listenAndServeTLS(options, (req) => {
|
|
|
|
* req.respond({ body });
|
|
|
|
* });
|
|
|
|
*
|
2019-11-04 13:45:29 -05:00
|
|
|
* @param options Server configuration
|
|
|
|
* @param handler Request handler
|
|
|
|
*/
|
|
|
|
export async function listenAndServeTLS(
|
|
|
|
options: HTTPSOptions,
|
|
|
|
handler: (req: ServerRequest) => void
|
|
|
|
): Promise<void> {
|
|
|
|
const server = serveTLS(options);
|
|
|
|
|
|
|
|
for await (const request of server) {
|
|
|
|
handler(request);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-17 18:44:35 -05:00
|
|
|
/**
|
|
|
|
* Interface of HTTP server response.
|
|
|
|
* If body is a Reader, response would be chunked.
|
|
|
|
* If body is a string, it would be UTF-8 encoded by default.
|
|
|
|
*/
|
2019-03-09 11:46:53 -05:00
|
|
|
export interface Response {
|
|
|
|
status?: number;
|
|
|
|
headers?: Headers;
|
2020-01-17 18:44:35 -05:00
|
|
|
body?: Uint8Array | Reader | string;
|
2018-12-18 20:48:05 -05:00
|
|
|
}
|