2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-02-26 10:48:35 -05:00
|
|
|
import { BufReader, BufWriter } from "../io/bufio.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";
|
2020-02-24 22:49:39 -05:00
|
|
|
import {
|
|
|
|
bodyReader,
|
|
|
|
chunkedBodyReader,
|
2020-02-26 10:48:35 -05:00
|
|
|
emptyReader,
|
|
|
|
writeResponse,
|
|
|
|
readRequest
|
2020-02-24 22:49:39 -05:00
|
|
|
} from "./io.ts";
|
2020-02-26 10:48:35 -05:00
|
|
|
import { encode } from "../strings/mod.ts";
|
|
|
|
import Listener = Deno.Listener;
|
|
|
|
import Conn = Deno.Conn;
|
|
|
|
import Reader = Deno.Reader;
|
|
|
|
const { listen, listenTLS } = Deno;
|
2019-05-20 09:17:26 -04:00
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2020-02-24 22:49:39 -05:00
|
|
|
private _body: Deno.Reader | null = null;
|
2020-01-02 12:34:33 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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);
|
|
|
|
* }
|
|
|
|
*/
|
2020-02-24 22:49:39 -05:00
|
|
|
get body(): Deno.Reader {
|
2020-01-02 12:34:33 -05:00
|
|
|
if (!this._body) {
|
2020-02-24 22:49:39 -05:00
|
|
|
if (this.contentLength != null) {
|
|
|
|
this._body = bodyReader(this.contentLength, this.r);
|
|
|
|
} else {
|
|
|
|
const transferEncoding = this.headers.get("transfer-encoding");
|
|
|
|
if (transferEncoding != null) {
|
|
|
|
const parts = transferEncoding
|
|
|
|
.split(",")
|
|
|
|
.map((e): string => e.trim().toLowerCase());
|
|
|
|
assert(
|
|
|
|
parts.includes("chunked"),
|
|
|
|
'transfer-encoding must include "chunked" if content-length is not set'
|
|
|
|
);
|
|
|
|
this._body = chunkedBodyReader(this.headers, this.r);
|
|
|
|
} else {
|
|
|
|
// Neither content-length nor transfer-encoding: chunked
|
|
|
|
this._body = emptyReader();
|
2019-02-19 12:38:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
return this._body;
|
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
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
|
|
|
|
private finalized = false;
|
|
|
|
async finalize(): Promise<void> {
|
|
|
|
if (this.finalized) return;
|
|
|
|
// Consume unread body
|
|
|
|
const body = this.body;
|
|
|
|
const buf = new Uint8Array(1024);
|
|
|
|
while ((await body.read(buf)) !== Deno.EOF) {}
|
|
|
|
this.finalized = true;
|
|
|
|
}
|
2019-02-19 12:38:19 -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);
|
2020-02-19 15:36:18 -05:00
|
|
|
let req: ServerRequest | Deno.EOF | undefined;
|
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;
|
|
|
|
}
|
2020-02-24 22:49:39 -05:00
|
|
|
// Consume unread body and trailers if receiver didn't consume those data
|
|
|
|
await req.finalize();
|
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-02-26 10:48:35 -05:00
|
|
|
body: 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.
|
2020-03-10 15:14:22 -04:00
|
|
|
let conn: Conn;
|
|
|
|
try {
|
|
|
|
conn = await this.listener.accept();
|
|
|
|
} catch (error) {
|
|
|
|
if (error instanceof Deno.errors.BadResource) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw error;
|
|
|
|
}
|
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
|
|
|
|
|
|
|
/**
|
2020-03-14 10:17:44 -04:00
|
|
|
* Create a HTTP server
|
2019-11-06 12:18:28 -05:00
|
|
|
*
|
|
|
|
* 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
|
|
|
}
|
|
|
|
|
2020-03-14 10:17:44 -04:00
|
|
|
/**
|
|
|
|
* Start an HTTP server with given options and request handler
|
|
|
|
*
|
|
|
|
* const body = "Hello World\n";
|
|
|
|
* const options = { port: 8000 };
|
|
|
|
* listenAndServeTLS(options, (req) => {
|
|
|
|
* req.respond({ body });
|
|
|
|
* });
|
|
|
|
*
|
|
|
|
* @param options Server configuration
|
|
|
|
* @param handler Request handler
|
|
|
|
*/
|
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);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-03-14 10:17:44 -04:00
|
|
|
* Start 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;
|
2020-02-10 11:38:48 -05:00
|
|
|
trailers?: () => Promise<Headers> | Headers;
|
2018-12-18 20:48:05 -05:00
|
|
|
}
|