use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use bytes::Bytes;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
const H2_PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
#[derive(Debug)]
pub struct PrefixedIo<I> {
prefix: Bytes,
inner: I,
}
impl<I> PrefixedIo<I> {
fn new(prefix: Bytes, inner: I) -> Self {
Self { prefix, inner }
}
}
impl<I: AsyncRead + Unpin> AsyncRead for PrefixedIo<I> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
if !self.prefix.is_empty() {
let n = self.prefix.len().min(buf.remaining());
let chunk = self.prefix.split_to(n);
buf.put_slice(&chunk);
return Poll::Ready(Ok(()));
}
Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
impl<I: AsyncWrite + Unpin> AsyncWrite for PrefixedIo<I> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[std::io::IoSlice<'_>],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.inner.is_write_vectored()
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum PrefaceError {
#[error("no request bytes within {0:?}")]
Timeout(Duration),
#[error("connection closed before any request bytes")]
Eof,
#[error(transparent)]
Io(#[from] std::io::Error),
}
pub async fn sniff_h2_preface<I>(
mut io: I,
deadline: Duration,
) -> Result<PrefixedIo<I>, PrefaceError>
where
I: AsyncRead + Unpin,
{
let mut buf = [0u8; H2_PREFACE.len()];
let mut filled = 0usize;
let read_to_a_decision = async {
while filled < H2_PREFACE.len() {
let n = io.read(&mut buf[filled..]).await?;
if n == 0 {
return Err(PrefaceError::Eof);
}
let new_filled = filled + n;
let diverged = buf[filled..new_filled] != H2_PREFACE[filled..new_filled];
filled = new_filled;
if diverged {
break;
}
}
Ok(())
};
match tokio::time::timeout(deadline, read_to_a_decision).await {
Ok(Ok(())) => Ok(PrefixedIo::new(Bytes::copy_from_slice(&buf[..filled]), io)),
Ok(Err(e)) => Err(e),
Err(_elapsed) => Err(PrefaceError::Timeout(deadline)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const DEADLINE: Duration = Duration::from_secs(30);
async fn read_exact_n<R: tokio::io::AsyncRead + Unpin>(io: &mut R, n: usize) -> Vec<u8> {
let mut buf = vec![0u8; n];
io.read_exact(&mut buf).await.expect("read_exact");
buf
}
#[tokio::test]
async fn resolves_at_the_first_byte_of_an_http1_request() {
let (mut client, server) = tokio::io::duplex(1024);
tokio::spawn(async move {
client
.write_all(b"GET /hello HTTP/1.1\r\nHost: x\r\n\r\n")
.await
.expect("write");
});
let mut io = sniff_h2_preface(server, DEADLINE)
.await
.expect("an HTTP/1 request resolves the version");
let replayed = read_exact_n(&mut io, 32).await;
assert_eq!(
&replayed[..],
b"GET /hello HTTP/1.1\r\nHost: x\r\n\r\n".as_slice(),
"every sniffed byte must be replayed, in order — hyper's own detection reads them \
again from this stream and would otherwise see a truncated request"
);
}
#[tokio::test]
async fn resolves_on_a_complete_h2_preface() {
let (mut client, server) = tokio::io::duplex(1024);
tokio::spawn(async move {
client
.write_all(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
.await
.expect("write");
});
let mut io = sniff_h2_preface(server, DEADLINE)
.await
.expect("a complete preface resolves the version");
let replayed = read_exact_n(&mut io, 24).await;
assert_eq!(
&replayed[..],
b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".as_slice(),
"all 24 preface bytes replayed byte-exact"
);
}
#[tokio::test]
async fn propfind_resolves_at_the_diverging_byte() {
let (mut client, server) = tokio::io::duplex(1024);
tokio::spawn(async move {
client
.write_all(b"PROPFIND /dav HTTP/1.1\r\n\r\n")
.await
.expect("write");
});
let mut io = sniff_h2_preface(server, DEADLINE)
.await
.expect("PROPFIND resolves as non-h2 at its third byte");
let replayed = read_exact_n(&mut io, 26).await;
assert_eq!(&replayed[..], b"PROPFIND /dav HTTP/1.1\r\n\r\n".as_slice());
}
#[tokio::test]
async fn a_preface_like_method_resolves_without_waiting_for_bytes_the_client_never_sends() {
let (mut client, server) = tokio::io::duplex(1024);
tokio::spawn(async move {
client.write_all(b"PR").await.expect("write prefix");
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(20)).await;
client
.write_all(b"OPFIND / HTTP/1.1\r\n\r\n")
.await
.expect("write rest");
});
let mut io =
tokio::time::timeout(Duration::from_secs(5), sniff_h2_preface(server, DEADLINE))
.await
.expect("detection must not wait for bytes the client already considers sent")
.expect("PROPFIND resolves as non-h2");
let replayed = read_exact_n(&mut io, 23).await;
assert_eq!(
&replayed[..],
b"PROPFIND / HTTP/1.1\r\n\r\n".as_slice(),
"bytes from both reads replay in order"
);
}
#[tokio::test]
async fn partial_preface_then_silence_times_out() {
let (mut client, server) = tokio::io::duplex(1024);
client.write_all(b"P").await.expect("write");
let err = sniff_h2_preface(server, Duration::from_millis(150))
.await
.expect_err("a partial preface followed by silence must not resolve");
assert!(
matches!(err, PrefaceError::Timeout(_)),
"expected a timeout, got {err:?}"
);
drop(client);
}
#[tokio::test]
async fn silence_from_the_first_byte_times_out() {
let (client, server) = tokio::io::duplex(1024);
let err = sniff_h2_preface(server, Duration::from_millis(150))
.await
.expect_err("a client that sends nothing must not resolve");
assert!(
matches!(err, PrefaceError::Timeout(_)),
"expected a timeout, got {err:?}"
);
drop(client);
}
#[tokio::test]
async fn eof_before_a_decision_is_reported_as_eof() {
let (mut client, server) = tokio::io::duplex(1024);
client.write_all(b"PR").await.expect("write");
drop(client);
let err = sniff_h2_preface(server, DEADLINE)
.await
.expect_err("a half-sent preface then EOF cannot resolve");
assert!(
matches!(err, PrefaceError::Eof),
"expected Eof, got {err:?}"
);
}
#[tokio::test]
async fn prefixed_io_reads_across_the_boundary_and_passes_writes_through() {
let (mut client, server) = tokio::io::duplex(1024);
client.write_all(b"GET /x").await.expect("write head");
let mut io = sniff_h2_preface(server, DEADLINE)
.await
.expect("resolves at the first byte");
tokio::spawn(async move {
client
.write_all(b" HTTP/1.1\r\n\r\n")
.await
.expect("write tail");
let mut echoed = vec![0u8; 4];
client.read_exact(&mut echoed).await.expect("read echo");
assert_eq!(
&echoed, b"pong",
"writes must reach the inner stream unchanged"
);
});
let spanning = read_exact_n(&mut io, 19).await;
assert_eq!(
&spanning[..],
b"GET /x HTTP/1.1\r\n\r\n".as_slice(),
"one read spanning prefix and socket returns the bytes in send order"
);
io.write_all(b"pong").await.expect("write through");
io.flush().await.expect("flush");
}
}