Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 80 additions & 122 deletions edge-http/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,10 @@ impl<E> std::error::Error for Error<E> where E: std::error::Error {}
impl<'b, const N: usize> RequestHeaders<'b, N> {
/// Parse the headers from the input stream
pub async fn receive<R>(
&mut self,
buf: &'b mut [u8],
mut input: R,
exact: bool,
) -> Result<(&'b mut [u8], usize), Error<R::Error>>
) -> Result<(Self, &'b mut [u8], usize), Error<R::Error>>
where
R: Read,
{
Expand All @@ -114,7 +113,8 @@ impl<'b, const N: usize> RequestHeaders<'b, N> {
Err(e) => return Err(e),
};

let mut parser = httparse::Request::new(&mut self.headers.0);
let mut headers = Headers::<'b, N>::new();
let mut parser = httparse::Request::new(&mut headers.0);

let (headers_buf, body_buf) = buf.split_at_mut(headers_len);

Expand All @@ -128,31 +128,34 @@ impl<'b, const N: usize> RequestHeaders<'b, N> {
unreachable!("Should not happen. HTTP header parsing is indeterminate.")
}

self.http11 = if let Some(version) = parser.version {
if version > 1 {
Err(Error::InvalidHeaders)?;
}

Some(version == 1)
} else {
None
let http11 = match parser.version {
Some(0) => false,
Some(1) => true,
_ => Err(Error::InvalidHeaders)?,
};

self.method = parser.method.and_then(Method::new);
self.path = parser.path;
let method_str = parser.method.ok_or(Error::InvalidHeaders)?;
let method = Method::new(method_str).ok_or(Error::InvalidHeaders)?;
let path = parser.path.ok_or(Error::InvalidHeaders)?;

trace!("Received:\n{}", self);
let result = Self {
http11,
method,
path,
headers,
};

Ok((body_buf, read_len - headers_len))
trace!("Received:\n{}", result);

Ok((result, body_buf, read_len - headers_len))
} else {
unreachable!("Secondary parse of already loaded buffer failed.")
}
}

/// Resolve the connection type and body type from the headers
pub fn resolve<E>(&self) -> Result<(ConnectionType, BodyType), Error<E>> {
self.headers
.resolve::<E>(None, true, self.http11.unwrap_or(false))
self.headers.resolve::<E>(None, true, self.http11)
}

/// Send the headers to the output stream, returning the connection type and body type
Expand All @@ -164,31 +167,29 @@ impl<'b, const N: usize> RequestHeaders<'b, N> {
where
W: Write,
{
let http11 = self.http11.unwrap_or(false);

send_request(http11, self.method, self.path, &mut output).await?;
send_request(self.http11, self.method, self.path, &mut output).await?;

self.headers
.send(None, true, http11, chunked_if_unspecified, output)
.send(None, true, self.http11, chunked_if_unspecified, output)
.await
}
}

impl<'b, const N: usize> ResponseHeaders<'b, N> {
/// Parse the headers from the input stream
pub async fn receive<R>(
&mut self,
buf: &'b mut [u8],
mut input: R,
exact: bool,
) -> Result<(&'b mut [u8], usize), Error<R::Error>>
) -> Result<(Self, &'b mut [u8], usize), Error<R::Error>>
where
R: Read,
{
let (read_len, headers_len) =
raw::read_reply_buf::<N, _>(&mut input, buf, false, exact).await?;

let mut parser = httparse::Response::new(&mut self.headers.0);
let mut headers = Headers::<'b, N>::new();
let mut parser = httparse::Response::new(&mut headers.0);

let (headers_buf, body_buf) = buf.split_at_mut(headers_len);

Expand All @@ -199,22 +200,25 @@ impl<'b, const N: usize> ResponseHeaders<'b, N> {
unreachable!("Should not happen. HTTP header parsing is indeterminate.")
}

self.http11 = if let Some(version) = parser.version {
if version > 1 {
Err(Error::InvalidHeaders)?;
}

Some(version == 1)
} else {
None
let http11 = match parser.version {
Some(0) => false,
Some(1) => true,
_ => Err(Error::InvalidHeaders)?,
};

self.code = parser.code;
self.reason = parser.reason;
let code = parser.code.ok_or(Error::InvalidHeaders)?;
let reason = parser.reason;

let result = Self {
http11,
code,
reason,
headers,
};

trace!("Received:\n{}", self);
trace!("Received:\n{}", result);

Ok((body_buf, read_len - headers_len))
Ok((result, body_buf, read_len - headers_len))
} else {
unreachable!("Secondary parse of already loaded buffer failed.")
}
Expand All @@ -225,11 +229,8 @@ impl<'b, const N: usize> ResponseHeaders<'b, N> {
&self,
request_connection_type: ConnectionType,
) -> Result<(ConnectionType, BodyType), Error<E>> {
self.headers.resolve::<E>(
Some(request_connection_type),
false,
self.http11.unwrap_or(false),
)
self.headers
.resolve::<E>(Some(request_connection_type), false, self.http11)
}

/// Send the headers to the output stream, returning the connection type and body type
Expand All @@ -242,15 +243,13 @@ impl<'b, const N: usize> ResponseHeaders<'b, N> {
where
W: Write,
{
let http11 = self.http11.unwrap_or(false);

send_status(http11, self.code, self.reason, &mut output).await?;
send_status(self.http11, self.code, self.reason, &mut output).await?;

self.headers
.send(
Some(request_connection_type),
false,
http11,
self.http11,
chunked_if_unspecified,
output,
)
Expand All @@ -260,42 +259,56 @@ impl<'b, const N: usize> ResponseHeaders<'b, N> {

pub(crate) async fn send_request<W>(
http11: bool,
method: Option<Method>,
path: Option<&str>,
output: W,
method: Method,
path: &str,
mut output: W,
) -> Result<(), Error<W::Error>>
where
W: Write,
{
raw::send_status_line(
true,
http11,
method.map(|method| method.as_str()),
path,
output,
)
.await
// RFC 9112: request-line = method SP request-target SP HTTP-version

output
.write_all(method.as_str().as_bytes())
.await
.map_err(Error::Io)?;
output.write_all(b" ").await.map_err(Error::Io)?;
output.write_all(path.as_bytes()).await.map_err(Error::Io)?;
output.write_all(b" ").await.map_err(Error::Io)?;
raw::send_version(&mut output, http11).await?;
output.write_all(b"\r\n").await.map_err(Error::Io)?;

Ok(())
}

pub(crate) async fn send_status<W>(
http11: bool,
status: Option<u16>,
status: u16,
reason: Option<&str>,
output: W,
mut output: W,
) -> Result<(), Error<W::Error>>
where
W: Write,
{
let status_str: Option<heapless::String<5>> = status.map(|status| status.try_into().unwrap());
// RFC 9112: status-line = HTTP-version SP status-code SP [ reason-phrase ]

raw::send_status_line(
false,
http11,
status_str.as_ref().map(|status| status.as_str()),
reason,
output,
)
.await
raw::send_version(&mut output, http11).await?;
output.write_all(b" ").await.map_err(Error::Io)?;
let status_str: heapless::String<5> = status.try_into().unwrap();
output
.write_all(status_str.as_bytes())
.await
.map_err(Error::Io)?;
output.write_all(b" ").await.map_err(Error::Io)?;
if let Some(reason) = reason {
output
.write_all(reason.as_bytes())
.await
.map_err(Error::Io)?;
}
output.write_all(b"\r\n").await.map_err(Error::Io)?;

Ok(())
}

pub(crate) async fn send_headers<'a, H, W>(
Expand Down Expand Up @@ -1181,61 +1194,6 @@ mod raw {
}
}

pub(crate) async fn send_status_line<W>(
request: bool,
http11: bool,
token: Option<&str>,
extra: Option<&str>,
mut output: W,
) -> Result<(), Error<W::Error>>
where
W: Write,
{
let mut written = false;

if !request {
send_version(&mut output, http11).await?;
written = true;
}

if let Some(token) = token {
if written {
output.write_all(b" ").await.map_err(Error::Io)?;
}

output
.write_all(token.as_bytes())
.await
.map_err(Error::Io)?;

written = true;
}

if written {
output.write_all(b" ").await.map_err(Error::Io)?;
}
if let Some(extra) = extra {
output
.write_all(extra.as_bytes())
.await
.map_err(Error::Io)?;

written = true;
}

if request {
if written {
output.write_all(b" ").await.map_err(Error::Io)?;
}

send_version(&mut output, http11).await?;
}

output.write_all(b"\r\n").await.map_err(Error::Io)?;

Ok(())
}

pub(crate) async fn send_version<W>(mut output: W, http11: bool) -> Result<(), Error<W::Error>>
where
W: Write,
Expand Down
14 changes: 4 additions & 10 deletions edge-http/src/io/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,16 +174,15 @@ where
let mut state = self.unbind();

let result = async {
match send_request(http11, Some(method), Some(uri), state.io.as_mut().unwrap()).await {
match send_request(http11, method, uri, state.io.as_mut().unwrap()).await {
Ok(_) => (),
Err(Error::Io(_)) => {
if !fresh_connection {
// Attempt to reconnect and re-send the request
state.io = None;
state.io = Some(state.socket.connect(state.addr).await.map_err(Error::Io)?);

send_request(http11, Some(method), Some(uri), state.io.as_mut().unwrap())
.await?;
send_request(http11, method, uri, state.io.as_mut().unwrap()).await?;
}
}
Err(other) => Err(other)?,
Expand Down Expand Up @@ -264,13 +263,8 @@ where
let mut state = self.unbind();
let buf_ptr: *mut [u8] = state.buf;

let mut response = ResponseHeaders::new();

match response
.receive(state.buf, &mut state.io.as_mut().unwrap(), true)
.await
{
Ok((buf, read_len)) => {
match ResponseHeaders::receive(state.buf, &mut state.io.as_mut().unwrap(), true).await {
Ok((response, buf, read_len)) => {
let (connection_type, body_type) =
response.resolve::<T::Error>(request_connection_type)?;

Expand Down
Loading
Loading