Skip to content

Commit d8be39c

Browse files
estkernestas-poskus
authored andcommitted
feat(server): support HTTP1 and HTTP2 automatically
If an HTTP/1 connection has a parse error, but it starts with the HTTP2 preface, converts the connection automatically into an HTTP2 server connection. Closes hyperium#1486
1 parent 7a99c36 commit d8be39c

File tree

9 files changed

+302
-16
lines changed

9 files changed

+302
-16
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ num_cpus = "1.0"
4545
pretty_env_logger = "0.2.0"
4646
spmc = "0.2"
4747
url = "1.0"
48+
tokio-mockstream = "1.1.0"
4849

4950
[features]
5051
default = [

src/error.rs

+6
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ pub(crate) enum Kind {
6969
pub(crate) enum Parse {
7070
Method,
7171
Version,
72+
VersionH2,
7273
Uri,
7374
Header,
7475
TooLarge,
@@ -164,6 +165,10 @@ impl Error {
164165
Error::new(Kind::Parse(Parse::Version), None)
165166
}
166167

168+
pub(crate) fn new_version_h2() -> Error {
169+
Error::new(Kind::Parse(Parse::VersionH2), None)
170+
}
171+
167172
pub(crate) fn new_mismatched_response() -> Error {
168173
Error::new(Kind::MismatchedResponse, None)
169174
}
@@ -250,6 +255,7 @@ impl StdError for Error {
250255
match self.inner.kind {
251256
Kind::Parse(Parse::Method) => "invalid Method specified",
252257
Kind::Parse(Parse::Version) => "invalid HTTP version specified",
258+
Kind::Parse(Parse::VersionH2) => "invalid HTTP version specified (Http2)",
253259
Kind::Parse(Parse::Uri) => "invalid URI",
254260
Kind::Parse(Parse::Header) => "invalid Header provided",
255261
Kind::Parse(Parse::TooLarge) => "message head is too large",

src/proto/h1/conn.rs

+11
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use proto::{BodyLength, Decode, Http1Transaction, MessageHead};
1212
use super::io::{Buffered};
1313
use super::{EncodedBuf, Encoder, Decoder};
1414

15+
const H2_PREFACE: &'static [u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
1516

1617
/// This handles a connection, which will have been established over an
1718
/// `AsyncRead + AsyncWrite` (like a socket), and will likely include multiple
@@ -107,6 +108,11 @@ where I: AsyncRead + AsyncWrite,
107108
T::should_error_on_parse_eof() && !self.state.is_idle()
108109
}
109110

111+
fn has_h2_prefix(&self) -> bool {
112+
let read_buf = self.io.read_buf();
113+
read_buf.len() >= 24 && read_buf[..24] == *H2_PREFACE
114+
}
115+
110116
pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, bool)>, ::Error> {
111117
debug_assert!(self.can_read_head());
112118
trace!("Conn::read_head");
@@ -124,6 +130,7 @@ where I: AsyncRead + AsyncWrite,
124130
self.io.consume_leading_lines();
125131
let was_mid_parse = e.is_parse() || !self.io.read_buf().is_empty();
126132
return if was_mid_parse || must_error {
133+
// We check if the buf contains the h2 Preface
127134
debug!("parse error ({}) with {} bytes", e, self.io.read_buf().len());
128135
self.on_parse_error(e)
129136
.map(|()| Async::NotReady)
@@ -529,8 +536,12 @@ where I: AsyncRead + AsyncWrite,
529536
// - Client: there is nothing we can do
530537
// - Server: if Response hasn't been written yet, we can send a 4xx response
531538
fn on_parse_error(&mut self, err: ::Error) -> ::Result<()> {
539+
532540
match self.state.writing {
533541
Writing::Init => {
542+
if self.has_h2_prefix() {
543+
return Err(::Error::new_version_h2())
544+
}
534545
if let Some(msg) = T::on_error(&err) {
535546
self.write_head(msg, None);
536547
self.state.error = Some(err);

src/proto/h1/dispatch.rs

+3
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,9 @@ impl<S> Server<S> where S: Service {
332332
service: service,
333333
}
334334
}
335+
pub fn into_service(self) -> S {
336+
self.service
337+
}
335338
}
336339

337340
impl<S, Bs> Dispatch for Server<S>

src/proto/h1/role.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,14 @@ where
186186
use ::error::{Kind, Parse};
187187
let status = match *err.kind() {
188188
Kind::Parse(Parse::Method) |
189-
Kind::Parse(Parse::Version) |
190189
Kind::Parse(Parse::Header) |
191-
Kind::Parse(Parse::Uri) => {
190+
Kind::Parse(Parse::Uri) |
191+
Kind::Parse(Parse::Version) => {
192192
StatusCode::BAD_REQUEST
193193
},
194194
Kind::Parse(Parse::TooLarge) => {
195195
StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
196-
}
196+
},
197197
_ => return None,
198198
};
199199

src/server/conn.rs

+50-13
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use std::fmt;
1313
use std::sync::Arc;
1414
#[cfg(feature = "runtime")] use std::time::Duration;
1515

16+
use super::rewind::Rewind;
1617
use bytes::Bytes;
1718
use futures::{Async, Future, Poll, Stream};
1819
use futures::future::{Either, Executor};
@@ -23,6 +24,7 @@ use common::Exec;
2324
use proto;
2425
use body::{Body, Payload};
2526
use service::{NewService, Service};
27+
use error::{Kind, Parse};
2628

2729
#[cfg(feature = "runtime")] pub use super::tcp::AddrIncoming;
2830

@@ -74,31 +76,32 @@ pub(super) struct SpawnAll<I, S> {
7476
///
7577
/// Polling this future will drive HTTP forward.
7678
#[must_use = "futures do nothing unless polled"]
77-
pub struct Connection<I, S>
79+
pub struct Connection<T, S>
7880
where
7981
S: Service,
8082
{
81-
pub(super) conn: Either<
83+
pub(super) conn: Option<
84+
Either<
8285
proto::h1::Dispatcher<
8386
proto::h1::dispatch::Server<S>,
8487
S::ResBody,
85-
I,
88+
T,
8689
proto::ServerTransaction,
8790
>,
8891
proto::h2::Server<
89-
I,
92+
Rewind<T>,
9093
S,
9194
S::ResBody,
9295
>,
93-
>,
96+
>>,
9497
}
9598

9699
/// Deconstructed parts of a `Connection`.
97100
///
98101
/// This allows taking apart a `Connection` at a later time, in order to
99102
/// reclaim the IO object, and additional related pieces.
100103
#[derive(Debug)]
101-
pub struct Parts<T, S> {
104+
pub struct Parts<T, S> {
102105
/// The original IO object used in the handshake.
103106
pub io: T,
104107
/// A buffer of bytes that have been read but not processed as HTTP.
@@ -239,12 +242,13 @@ impl Http {
239242
let sd = proto::h1::dispatch::Server::new(service);
240243
Either::A(proto::h1::Dispatcher::new(sd, conn))
241244
} else {
242-
let h2 = proto::h2::Server::new(io, service, self.exec.clone());
245+
let rewind_io = Rewind::new(io);
246+
let h2 = proto::h2::Server::new(rewind_io, service, self.exec.clone());
243247
Either::B(h2)
244248
};
245249

246250
Connection {
247-
conn: either,
251+
conn: Some(either),
248252
}
249253
}
250254

@@ -322,7 +326,7 @@ where
322326
/// This `Connection` should continue to be polled until shutdown
323327
/// can finish.
324328
pub fn graceful_shutdown(&mut self) {
325-
match self.conn {
329+
match *self.conn.as_mut().unwrap() {
326330
Either::A(ref mut h1) => {
327331
h1.disable_keep_alive();
328332
},
@@ -334,11 +338,12 @@ where
334338

335339
/// Return the inner IO object, and additional information.
336340
///
341+
/// If the IO object has been "rewound" the io will not contain those bytes rewound.
337342
/// This should only be called after `poll_without_shutdown` signals
338343
/// that the connection is "done". Otherwise, it may not have finished
339344
/// flushing all necessary HTTP bytes.
340345
pub fn into_parts(self) -> Parts<I, S> {
341-
let (io, read_buf, dispatch) = match self.conn {
346+
let (io, read_buf, dispatch) = match self.conn.unwrap() {
342347
Either::A(h1) => {
343348
h1.into_inner()
344349
},
@@ -349,7 +354,7 @@ where
349354
Parts {
350355
io: io,
351356
read_buf: read_buf,
352-
service: dispatch.service,
357+
service: dispatch.into_service(),
353358
_inner: (),
354359
}
355360
}
@@ -362,14 +367,37 @@ where
362367
/// but it is not desired to actally shutdown the IO object. Instead you
363368
/// would take it back using `into_parts`.
364369
pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> {
365-
match self.conn {
370+
match *self.conn.as_mut().unwrap() {
366371
Either::A(ref mut h1) => {
367372
try_ready!(h1.poll_without_shutdown());
368373
Ok(().into())
369374
},
370375
Either::B(ref mut h2) => h2.poll(),
371376
}
372377
}
378+
379+
fn try_h2(&mut self) -> Poll<(), ::Error> {
380+
trace!("Trying to upgrade connection to h2");
381+
let conn = self.conn.take();
382+
383+
let (io, read_buf, dispatch) = match conn.unwrap() {
384+
Either::A(h1) => {
385+
h1.into_inner()
386+
},
387+
Either::B(_h2) => {
388+
panic!("h2 cannot into_inner");
389+
}
390+
};
391+
let mut rewind_io = Rewind::new(io);
392+
rewind_io.rewind(read_buf);
393+
let mut h2 = proto::h2::Server::new(rewind_io, dispatch.into_service(), Exec::Default);
394+
let pr = h2.poll();
395+
396+
debug_assert!(self.conn.is_none());
397+
self.conn = Some(Either::B(h2));
398+
399+
pr
400+
}
373401
}
374402

375403
impl<I, B, S> Future for Connection<I, S>
@@ -384,7 +412,16 @@ where
384412
type Error = ::Error;
385413

386414
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
387-
self.conn.poll()
415+
match self.conn.poll() {
416+
Ok(x) => Ok(x.map(|o| o.unwrap_or_else(|| ()))),
417+
Err(e) => {
418+
debug!("error polling connection protocol: {}", e);
419+
match *e.kind() {
420+
Kind::Parse(Parse::VersionH2) => self.try_h2(),
421+
_ => Err(e),
422+
}
423+
}
424+
}
388425
}
389426
}
390427

src/server/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
5151
pub mod conn;
5252
#[cfg(feature = "runtime")] mod tcp;
53+
mod rewind;
5354

5455
use std::fmt;
5556
#[cfg(feature = "runtime")] use std::net::SocketAddr;

0 commit comments

Comments
 (0)