Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expose all HTTP headers #60

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ httparse = { default-features = false, features = ["std"], version = "1.3.4" }
log = { default-features = false, version = "0.4.8" }
rand = { default-features = false, features = ["std", "std_rng"], version = "0.8" }
sha-1 = { default-features = false, version = "0.9" }
http = { default-features = false, version = "0.2", optional = true }
http = { default-features = false, version = "0.2" }

[dev-dependencies]
quickcheck = "0.9"
Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ This crate is a heavily modified fork of the [twist][3] crate.

[1]: https://tools.ietf.org/html/rfc6455
[2]: https://crates.io/crates/tokio-codec
[3]: https://crates.io/crates/twist

[3]: https://crates.io/crates/twist
1 change: 0 additions & 1 deletion src/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
//! [handshake]: https://tools.ietf.org/html/rfc6455#section-4

pub mod client;
#[cfg(feature = "http")]
pub mod http;
pub mod server;

Expand Down
28 changes: 16 additions & 12 deletions src/handshake/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use futures::prelude::*;
use sha1::{Digest, Sha1};
use std::{mem, str};

pub use httparse::Header;
pub use http::HeaderMap;

const BLOCK_SIZE: usize = 8 * 1024;

Expand All @@ -32,10 +32,10 @@ pub struct Client<'a, T> {
socket: T,
/// The HTTP host to send the handshake to.
host: &'a str,
/// The HTTP host ressource.
/// The HTTP host resource.
resource: &'a str,
/// The HTTP headers.
headers: &'a [Header<'a>],
headers: Option<&'a HeaderMap>,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it doesn't makes sense to use httparse::Header to construct new headers, the type is used for parsed headers and doesn't check whether the header is valid or not.

however, it still possible to enter some conflicting headers such as host, websocket upgrade and similar as these are configured separately.

/// A buffer holding the base-64 encoded request nonce.
nonce: WebSocketKey,
/// The protocols to include in the handshake.
Expand All @@ -53,7 +53,7 @@ impl<'a, T: AsyncRead + AsyncWrite + Unpin> Client<'a, T> {
socket,
host,
resource,
headers: &[],
headers: None,
nonce: [0; 24],
protocols: Vec::new(),
extensions: Vec::new(),
Expand All @@ -75,8 +75,8 @@ impl<'a, T: AsyncRead + AsyncWrite + Unpin> Client<'a, T> {
/// Set connection headers to a slice. These headers are not checked for validity,
/// the caller of this method is responsible for verification as well as avoiding
/// conflicts with internally set headers.
pub fn set_headers(&mut self, h: &'a [Header]) -> &mut Self {
self.headers = h;
pub fn set_headers(&mut self, h: &'a HeaderMap) -> &mut Self {
self.headers = Some(h);
self
}

Expand Down Expand Up @@ -139,12 +139,16 @@ impl<'a, T: AsyncRead + AsyncWrite + Unpin> Client<'a, T> {
self.buffer.extend_from_slice(b"\r\nUpgrade: websocket\r\nConnection: Upgrade");
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Key: ");
self.buffer.extend_from_slice(&self.nonce);
self.headers.iter().for_each(|h| {
self.buffer.extend_from_slice(b"\r\n");
self.buffer.extend_from_slice(h.name.as_bytes());
self.buffer.extend_from_slice(b": ");
self.buffer.extend_from_slice(h.value);
});

if let Some(headers) = self.headers {
headers.iter().for_each(|(name, value)| {
self.buffer.extend_from_slice(b"\r\n");
self.buffer.extend_from_slice(name.as_ref());
self.buffer.extend_from_slice(b": ");
self.buffer.extend_from_slice(value.as_ref());
});
}

if let Some((last, prefix)) = self.protocols.split_last() {
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Protocol: ");
for p in prefix {
Expand Down
40 changes: 13 additions & 27 deletions src/handshake/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use bytes::BytesMut;
use futures::prelude::*;
use std::{mem, str};

pub use httparse::Header;

// Most HTTP servers default to 8KB limit on headers
const MAX_HEADERS_SIZE: usize = 8 * 1024;
const BLOCK_SIZE: usize = 8 * 1024;
Expand Down Expand Up @@ -142,24 +144,13 @@ impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {
return Err(Error::UnsupportedHttpVersion);
}

let host = with_first_header(&request.headers, "Host", Ok)?;
// do we need to this when all headers are exposed?!.
let _host = with_first_header(&request.headers, "Host", Ok)?;

expect_ascii_header(request.headers, "Upgrade", "websocket")?;
expect_ascii_header(request.headers, "Connection", "upgrade")?;
expect_ascii_header(request.headers, "Sec-WebSocket-Version", "13")?;

let origin =
request.headers.iter().find_map(
|h| {
if h.name.eq_ignore_ascii_case("Origin") {
Some(h.value)
} else {
None
}
},
);
let headers = RequestHeaders { host, origin };

let ws_key = with_first_header(&request.headers, "Sec-WebSocket-Key", |k| {
WebSocketKey::try_from(k).map_err(|_| Error::SecWebSocketKeyInvalidLength(k.len()))
})?;
Expand All @@ -177,7 +168,7 @@ impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {

let path = request.path.unwrap_or("/");

Ok(ClientRequest { ws_key, protocols, path, headers })
Ok(ClientRequest { ws_key, protocols, path, headers: request.headers.to_vec() })
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so, the headers is parsed from an array which is mutally borrowed so I had to clone it the headers unfortunately.

}

// Encode server handshake response.
Expand Down Expand Up @@ -224,16 +215,7 @@ pub struct ClientRequest<'a> {
ws_key: WebSocketKey,
protocols: Vec<&'a str>,
path: &'a str,
headers: RequestHeaders<'a>,
}

/// Select HTTP headers sent by the client.
#[derive(Debug, Copy, Clone)]
pub struct RequestHeaders<'a> {
/// The [`Host`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host) header.
pub host: &'a [u8],
/// The [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) header, if provided.
pub origin: Option<&'a [u8]>,
headers: Vec<Header<'a>>,
}

impl<'a> ClientRequest<'a> {
Expand All @@ -252,9 +234,13 @@ impl<'a> ClientRequest<'a> {
self.path
}

/// Select HTTP headers sent by the client.
pub fn headers(&self) -> RequestHeaders {
self.headers
/// HTTP headers sent by the client.
pub fn headers(&self) -> &'a [Header] {
&self.headers
}

pub fn into_parts(self) -> (WebSocketKey, Vec<&'a str>, &'a str, Vec<Header<'a>>) {
(self.ws_key, self.protocols, self.path, self.headers)
}
}

Expand Down