mirror of
https://github.com/YGGverse/agate.git
synced 2026-04-09 04:55:27 +00:00
Improved request parsing.
Only read up to 1024 bytes plus CRLF. This avoids allocations and copies, and prevents malicious/buggy clients from making us allocate unbounded amounts of memory. We also stop if we see a lone LF, rather than timing out until CRLF is received.
This commit is contained in:
parent
039057b8db
commit
a049beb66b
1 changed files with 21 additions and 20 deletions
41
src/main.rs
41
src/main.rs
|
|
@ -82,30 +82,31 @@ async fn connection(stream: TcpStream) -> Result {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn parse_request(stream: &mut TlsStream<TcpStream>) -> Result<Url> {
|
async fn parse_request(stream: &mut TlsStream<TcpStream>) -> Result<Url> {
|
||||||
let mut stream = async_std::io::BufReader::new(stream);
|
// Read one line up to 1024 bytes, plus 2 bytes for CRLF.
|
||||||
let mut request = Vec::new();
|
let mut request = [0; 1026];
|
||||||
stream.read_until(b'\r', &mut request).await?;
|
let mut buf = &mut request[..];
|
||||||
|
let mut len = 0;
|
||||||
|
while !buf.is_empty() {
|
||||||
|
let n = stream.read(buf).await?;
|
||||||
|
len += n;
|
||||||
|
if n == 0 || request[..len].ends_with(b"\r\n") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buf = &mut request[len..];
|
||||||
|
}
|
||||||
|
if !request[..len].ends_with(b"\r\n") {
|
||||||
|
Err("Missing CRLF")?
|
||||||
|
}
|
||||||
|
let request = str::from_utf8(&request[..len - 2])?;
|
||||||
|
|
||||||
// Check line ending.
|
let url = if request.starts_with("//") {
|
||||||
let eol = &mut [0];
|
Url::parse(&format!("gemini:{}", request))?
|
||||||
stream.read_exact(eol).await?;
|
} else {
|
||||||
if eol != b"\n" {
|
Url::parse(request)?
|
||||||
Err("CR without LF")?
|
};
|
||||||
}
|
|
||||||
// Check request length.
|
|
||||||
if request.len() > 1026 {
|
|
||||||
Err("Too long")?
|
|
||||||
}
|
|
||||||
// Handle scheme-relative URLs.
|
|
||||||
if request.starts_with(b"//") {
|
|
||||||
request.splice(..0, "gemini:".bytes());
|
|
||||||
}
|
|
||||||
// Parse URL.
|
|
||||||
let url = Url::parse(str::from_utf8(&request)?.trim_end())?;
|
|
||||||
if url.scheme() != "gemini" {
|
if url.scheme() != "gemini" {
|
||||||
Err("unsupported URL scheme")?
|
Err("unsupported URL scheme")?
|
||||||
}
|
}
|
||||||
// TODO: Validate hostname and port.
|
|
||||||
Ok(url)
|
Ok(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue