summaryrefslogtreecommitdiff
path: root/std/http/io.ts
diff options
context:
space:
mode:
authorNayeem Rahman <nayeemrmn99@gmail.com>2020-04-01 09:24:05 +0100
committerGitHub <noreply@github.com>2020-04-01 10:24:05 +0200
commit017a611131a35ccf5dbfce6a2a665fa569e32ec1 (patch)
tree49f07dfc25f8fdf45dae2f812941f42e9274bea6 /std/http/io.ts
parent857d96001d63c1cb847f3f228124d69c40d267e7 (diff)
feat(std/http/server): Respond with 400 on request parse failure (#4551)
Diffstat (limited to 'std/http/io.ts')
-rw-r--r--std/http/io.ts35
1 files changed, 28 insertions, 7 deletions
diff --git a/std/http/io.ts b/std/http/io.ts
index 2875be44f..e12c9fb6e 100644
--- a/std/http/io.ts
+++ b/std/http/io.ts
@@ -342,17 +342,38 @@ export function parseHTTPVersion(vers: string): [number, number] {
export async function readRequest(
conn: Deno.Conn,
- bufr: BufReader
+ // The reader and writer buffers may be constructed externally so they can be
+ // shared by requests on the same connection -- see `Server`.
+ reader?: BufReader,
+ writer?: BufWriter
): Promise<ServerRequest | Deno.EOF> {
- const tp = new TextProtoReader(bufr);
- const firstLine = await tp.readLine(); // e.g. GET /index.html HTTP/1.0
- if (firstLine === Deno.EOF) return Deno.EOF;
- const headers = await tp.readMIMEHeader();
- if (headers === Deno.EOF) throw new Deno.errors.UnexpectedEof();
+ reader = reader ?? new BufReader(conn);
+ writer = writer ?? new BufWriter(conn);
+ const tp = new TextProtoReader(reader);
+ let firstLine: string | Deno.EOF;
+ let headers: Headers | Deno.EOF;
+ try {
+ firstLine = await tp.readLine(); // e.g. GET /index.html HTTP/1.0
+ if (firstLine == Deno.EOF) {
+ return Deno.EOF;
+ }
+ headers = await tp.readMIMEHeader();
+ if (headers == Deno.EOF) {
+ throw new Deno.errors.UnexpectedEof();
+ }
+ } catch (error) {
+ // An error was thrown while parsing request headers.
+ await writeResponse(writer, {
+ status: 400,
+ body: encoder.encode(`${error.message}\r\n\r\n`),
+ });
+ throw error;
+ }
const req = new ServerRequest();
req.conn = conn;
- req.r = bufr;
+ req.r = reader;
+ req.w = writer;
[req.method, req.url, req.proto] = firstLine.split(" ", 3);
[req.protoMinor, req.protoMajor] = parseHTTPVersion(req.proto);
req.headers = headers;