From 60d9ab08dbcf2b9874206bc8411a25ca44e8118e Mon Sep 17 00:00:00 2001 From: lideming Date: Thu, 19 Nov 2020 00:47:47 +0800 Subject: fix(std/http): fix error handling in the request iterator (#8365) If the request body is using chunked encoding, errors may be thrown in "request.finalize()". In this case, we should untrack and close the connection. --- std/http/server.ts | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) (limited to 'std/http/server.ts') diff --git a/std/http/server.ts b/std/http/server.ts index 7bbdb7829..4d9f70723 100644 --- a/std/http/server.ts +++ b/std/http/server.ts @@ -151,10 +151,15 @@ export class Server implements AsyncIterable { error instanceof Deno.errors.UnexpectedEof ) { // An error was thrown while parsing request headers. - await writeResponse(writer, { - status: 400, - body: encode(`${error.message}\r\n\r\n`), - }); + // Try to send the "400 Bad Request" before closing the connection. + try { + await writeResponse(writer, { + status: 400, + body: encode(`${error.message}\r\n\r\n`), + }); + } catch (error) { + // The connection is broken. + } } break; } @@ -175,8 +180,14 @@ export class Server implements AsyncIterable { this.untrackConnection(request.conn); return; } - // Consume unread body and trailers if receiver didn't consume those data - await request.finalize(); + + try { + // Consume unread body and trailers if receiver didn't consume those data + await request.finalize(); + } catch (error) { + // Invalid data was received or the connection was closed. + break; + } } this.untrackConnection(conn); @@ -212,9 +223,12 @@ export class Server implements AsyncIterable { conn = await this.listener.accept(); } catch (error) { if ( + // The listener is closed: error instanceof Deno.errors.BadResource || + // TLS handshake errors: error instanceof Deno.errors.InvalidData || - error instanceof Deno.errors.UnexpectedEof + error instanceof Deno.errors.UnexpectedEof || + error instanceof Deno.errors.ConnectionReset ) { return mux.add(this.acceptConnAndIterateHttpRequests(mux)); } -- cgit v1.2.3