From 6360e9f37a0a65fbc65d9e923db9ef8f5b77ff83 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sat, 4 Jul 2020 02:29:07 +0200 Subject: Server::start: Handle errors with a 500 response If we get errors building the request or Conduit errors, respond with a 500 error. Otherwise, it's a write error, and we should do nothing (ideally log the error), because this means the client closed the connection or there are bigger problems. --- src/server.rs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/server.rs b/src/server.rs index 9416d9c..0f45f5e 100644 --- a/src/server.rs +++ b/src/server.rs @@ -8,6 +8,9 @@ use snafu::{ResultExt, Snafu}; use crate::request; +const HTTP_VERSION: &'static str = "HTTP/1.1"; + + #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("{}", source))] @@ -26,7 +29,19 @@ pub struct Server; impl Server { pub fn start(handler: H) -> io::Result { fastcgi::run(move |mut raw_request| { - handle_request(&mut raw_request, &handler); + match handle_request(&mut raw_request, &handler) { + Ok(_) => (), + + // TODO: log + // Ignore write errors as clients will have closed the + // connection by this point. + Err(Error::Io { .. }) => (), + + Err(Error::RequestBuilder { .. }) => + internal_server_error(&mut raw_request.stdout()), + Err(Error::ConduitResponse { .. }) => + internal_server_error(&mut raw_request.stdout()), + } }); Ok(Server{}) @@ -51,7 +66,8 @@ where H: Handler + 'static + Sync write!( &mut stdout, - "HTTP/1.1 {} {}\r\n", + "{} {} {}\r\n", + HTTP_VERSION, head.status.as_str(), head.status.canonical_reason().unwrap_or("UNKNOWN"), ) @@ -73,3 +89,17 @@ where H: Handler + 'static + Sync Ok(()) } + +fn internal_server_error(mut w: W) { + let code = conduit::StatusCode::INTERNAL_SERVER_ERROR; + + write!( + w, + "{} {} {}\r\n{}\r\n\r\n", + HTTP_VERSION, + code, + code.canonical_reason().unwrap_or_default(), + "Content-Length: 0", + ) + .unwrap_or(()) +} -- cgit v1.2.3