diff --git a/examples/server.rs b/examples/server.rs index f0578c3328..a876df36bc 100644 --- a/examples/server.rs +++ b/examples/server.rs @@ -23,12 +23,12 @@ impl Service for Echo { fn call(&self, req: Request) -> Self::Future { ::futures::finished(match (req.method(), req.path()) { - (&Get, Some("/")) | (&Get, Some("/echo")) => { + (&Get, "/") | (&Get, "/echo") => { Response::new() .with_header(ContentLength(INDEX.len() as u64)) .with_body(INDEX) }, - (&Post, Some("/echo")) => { + (&Post, "/echo") => { let mut res = Response::new(); if let Some(len) = req.headers().get::() { res.headers_mut().set(len.clone()); diff --git a/src/client/mod.rs b/src/client/mod.rs index a48633aeaf..0c8ac8bef5 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -23,7 +23,6 @@ use header::{Headers, Host}; use http::{self, TokioBody}; use method::Method; use self::pool::{Pool, Pooled}; -use uri::RequestUri; use {Url}; pub use self::connect::{HttpConnector, Connect}; @@ -120,15 +119,10 @@ impl Service for Client { fn call(&self, req: Request) -> Self::Future { let url = req.url().clone(); - let (mut head, body) = request::split(req); let mut headers = Headers::new(); headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port())); headers.extend(head.headers.iter()); - head.subject.1 = RequestUri::AbsolutePath { - path: url.path().to_owned(), - query: url.query().map(ToOwned::to_owned), - }; head.headers = headers; let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]); diff --git a/src/client/request.rs b/src/client/request.rs index d74ea9ee96..3c9e91ed68 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -5,7 +5,7 @@ use Url; use header::Headers; use http::{Body, RequestHead}; use method::Method; -use uri::RequestUri; +use uri::Uri; use version::HttpVersion; /// A client request to a remote server. @@ -79,8 +79,9 @@ impl fmt::Debug for Request { } pub fn split(req: Request) -> (RequestHead, Option) { + let uri = Uri::new(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is uri"); let head = RequestHead { - subject: ::http::RequestLine(req.method, RequestUri::AbsoluteUri(req.url)), + subject: ::http::RequestLine(req.method, uri), headers: req.headers, version: req.version, }; diff --git a/src/error.rs b/src/error.rs index ed107d944d..ec3691524a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -31,7 +31,7 @@ pub type Result = ::std::result::Result; pub enum Error { /// An invalid `Method`, such as `GE,T`. Method, - /// An invalid `RequestUri`, such as `exam ple.domain`. + /// An invalid `Uri`, such as `exam ple.domain`. Uri(url::ParseError), /// An invalid `HttpVersion`, such as `HTP/1.1` Version, diff --git a/src/http/conn.rs b/src/http/conn.rs index 832f054481..c586bd66a4 100644 --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -574,6 +574,7 @@ mod tests { use mock::AsyncIo; use super::{Conn, Writing}; + use ::uri::Uri; #[test] fn test_conn_init_read() { @@ -585,10 +586,7 @@ mod tests { match conn.poll().unwrap() { Async::Ready(Some(Frame::Message { message, body: false })) => { assert_eq!(message, MessageHead { - subject: ::http::RequestLine(::Get, ::RequestUri::AbsolutePath { - path: "/".to_string(), - query: None, - }), + subject: ::http::RequestLine(::Get, Uri::new("/").unwrap()), .. MessageHead::default() }) }, diff --git a/src/http/mod.rs b/src/http/mod.rs index 4073dd7e73..cdad710e4c 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -6,7 +6,7 @@ use header::{Connection, ConnectionOption}; use header::Headers; use method::Method; use status::StatusCode; -use uri::RequestUri; +use uri::Uri; use version::HttpVersion; use version::HttpVersion::{Http10, Http11}; @@ -51,7 +51,7 @@ pub struct MessageHead { pub type RequestHead = MessageHead; #[derive(Debug, Default, PartialEq)] -pub struct RequestLine(pub Method, pub RequestUri); +pub struct RequestLine(pub Method, pub Uri); impl fmt::Display for RequestLine { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/src/lib.rs b/src/lib.rs index 07a8d92087..6cab904516 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,6 @@ pub use http::{Body, Chunk}; pub use method::Method::{self, Get, Head, Post, Delete}; pub use status::StatusCode::{self, Ok, BadRequest, NotFound}; pub use server::Server; -pub use uri::RequestUri; pub use version::HttpVersion; macro_rules! unimplemented { diff --git a/src/server/request.rs b/src/server/request.rs index ce23b6ffb0..76840478bc 100644 --- a/src/server/request.rs +++ b/src/server/request.rs @@ -10,12 +10,12 @@ use version::HttpVersion; use method::Method; use header::Headers; use http::{RequestHead, MessageHead, RequestLine, Body}; -use uri::RequestUri; +use uri::Uri; /// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. pub struct Request { method: Method, - uri: RequestUri, + uri: Uri, version: HttpVersion, headers: Headers, remote_addr: SocketAddr, @@ -33,7 +33,7 @@ impl Request { /// The target request-uri for this request. #[inline] - pub fn uri(&self) -> &RequestUri { &self.uri } + pub fn uri(&self) -> &Uri { &self.uri } /// The version of HTTP for this request. #[inline] @@ -45,22 +45,14 @@ impl Request { /// The target path of this Request. #[inline] - pub fn path(&self) -> Option<&str> { - match self.uri { - RequestUri::AbsolutePath { path: ref p, .. } => Some(p.as_str()), - RequestUri::AbsoluteUri(ref url) => Some(url.path()), - _ => None, - } + pub fn path(&self) -> &str { + self.uri.path() } /// The query string of this Request. #[inline] pub fn query(&self) -> Option<&str> { - match self.uri { - RequestUri::AbsolutePath { query: ref q, .. } => q.as_ref().map(|x| x.as_str()), - RequestUri::AbsoluteUri(ref url) => url.query(), - _ => None, - } + self.uri.query() } /// Take the `Body` of this `Request`. @@ -73,7 +65,7 @@ impl Request { /// /// Modifying these pieces will have no effect on how hyper behaves. #[inline] - pub fn deconstruct(self) -> (Method, RequestUri, HttpVersion, Headers, Body) { + pub fn deconstruct(self) -> (Method, Uri, HttpVersion, Headers, Body) { (self.method, self.uri, self.version, self.headers, self.body) } } diff --git a/src/uri.rs b/src/uri.rs index c618ef1de1..c7b4823fb2 100644 --- a/src/uri.rs +++ b/src/uri.rs @@ -1,7 +1,7 @@ -//! HTTP RequestUris +use std::borrow::Cow; use std::fmt::{Display, self}; use std::str::FromStr; -use url::Url; +use url::{self, Url}; use url::ParseError as UrlError; use Error; @@ -21,125 +21,301 @@ use Error; /// > / authority-form /// > / asterisk-form /// > ``` -#[derive(Debug, PartialEq, Eq, Hash, Clone)] -pub enum RequestUri { - /// The most common request target, an absolute path and optional query. - /// - /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI - /// as `AbsolutePath { path: "/where".to_string(), query: Some("q=now".to_string()) }`. - AbsolutePath { - /// The path part of the request uri. - path: String, - /// The query part of the request uri. - query: Option, - }, - - /// An absolute URI. Used in conjunction with proxies. - /// - /// > When making a request to a proxy, other than a CONNECT or server-wide - /// > OPTIONS request (as detailed below), a client MUST send the target - /// > URI in absolute-form as the request-target. - /// - /// An example StartLine with an `AbsoluteUri` would be - /// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`. - AbsoluteUri(Url), - - /// The authority form is only for use with `CONNECT` requests. - /// - /// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`. - Authority(String), - - /// The star is used to target the entire server, instead of a specific resource. - /// - /// This is only used for a server-wide `OPTIONS` request. - Star, -} - -impl Default for RequestUri { - fn default() -> RequestUri { - RequestUri::Star - } -} - -impl FromStr for RequestUri { - type Err = Error; +/// +/// # Uri explanations +/// +/// abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1 +/// |-| |-------------------------------||--------| |-------------------| |-----| +/// | | | | | +/// scheme authority path query fragment +#[derive(Clone)] +pub struct Uri { + source: Cow<'static, str>, + scheme_end: Option, + authority_end: Option, + query: Option, + fragment: Option, +} - fn from_str(s: &str) -> Result { +impl Uri { + /// Parse a string into a `Uri`. + pub fn new(s: &str) -> Result { let bytes = s.as_bytes(); if bytes.len() == 0 { Err(Error::Uri(UrlError::RelativeUrlWithoutBase)) } else if bytes == b"*" { - Ok(RequestUri::Star) + Ok(Uri { + source: "*".into(), + scheme_end: None, + authority_end: None, + query: None, + fragment: None, + }) + } else if bytes == b"/" { + Ok(Uri::default()) } else if bytes.starts_with(b"/") { let mut temp = "http://example.com".to_owned(); temp.push_str(s); let url = try!(Url::parse(&temp)); - Ok(RequestUri::AbsolutePath { - path: url.path().to_owned(), - query: url.query().map(|q| q.to_owned()), + let query_len = url.query().unwrap_or("").len(); + let fragment_len = url.fragment().unwrap_or("").len(); + Ok(Uri { + source: s.to_owned().into(), + scheme_end: None, + authority_end: None, + query: if query_len > 0 { Some(query_len) } else { None }, + fragment: if fragment_len > 0 { Some(fragment_len) } else { None }, }) - } else if bytes.contains(&b'/') { - Ok(RequestUri::AbsoluteUri(try!(Url::parse(s)))) + } else if s.contains("://") { + let url = try!(Url::parse(s)); + let query_len = url.query().unwrap_or("").len(); + let v: Vec<&str> = s.split("://").collect(); + let authority_end = v.last().unwrap() + .split(url.path()) + .next() + .unwrap_or(s) + .len() + if v.len() == 2 { v[0].len() + 3 } else { 0 }; + let fragment_len = url.fragment().unwrap_or("").len(); + match url.origin() { + url::Origin::Opaque(_) => Err(Error::Method), + url::Origin::Tuple(scheme, _, _) => { + Ok(Uri { + source: url.to_string().into(), + scheme_end: Some(scheme.len()), + authority_end: if authority_end > 0 { Some(authority_end) } else { None }, + query: if query_len > 0 { Some(query_len) } else { None }, + fragment: if fragment_len > 0 { Some(fragment_len) } else { None }, + }) + } + } } else { - let mut temp = "http://".to_owned(); - temp.push_str(s); - let url = try!(Url::parse(&temp)); - if url.query().is_some() { - return Err(Error::Uri(UrlError::RelativeUrlWithoutBase)); + Ok(Uri { + source: s.to_owned().into(), + scheme_end: None, + authority_end: Some(s.len()), + query: None, + fragment: None, + }) + } + } + + /// Get the path of this `Uri`. + pub fn path(&self) -> &str { + let index = self.authority_end.unwrap_or(self.scheme_end.unwrap_or(0)); + let query_len = self.query.unwrap_or(0); + let fragment_len = self.fragment.unwrap_or(0); + let end = self.source.len() - if query_len > 0 { query_len + 1 } else { 0 } - + if fragment_len > 0 { fragment_len + 1 } else { 0 }; + if index >= end { + "" + } else { + &self.source[index..end] + } + } + + /// Get the scheme of this `Uri`. + pub fn scheme(&self) -> Option<&str> { + if let Some(end) = self.scheme_end { + Some(&self.source[..end]) + } else { + None + } + } + + /// Get the authority of this `Uri`. + pub fn authority(&self) -> Option<&str> { + if let Some(end) = self.authority_end { + let index = self.scheme_end.map(|i| i + 3).unwrap_or(0); + Some(&self.source[index..end]) + } else { + None + } + } + + /// Get the host of this `Uri`. + pub fn host(&self) -> Option<&str> { + if let Some(auth) = self.authority() { + auth.split(":").next() + } else { + None + } + } + + /// Get the port of this `Uri. + pub fn port(&self) -> Option { + if let Some(auth) = self.authority() { + let v: Vec<&str> = auth.split(":").collect(); + if v.len() == 2 { + u16::from_str(v[1]).ok() + } else { + None } - //TODO: compare vs u.authority()? - Ok(RequestUri::Authority(s.to_owned())) + } else { + None + } + } + + /// Get the query string of this `Uri`, starting after the `?`. + pub fn query(&self) -> Option<&str> { + let fragment_len = self.fragment.unwrap_or(0); + let fragment_len = if fragment_len > 0 { fragment_len + 1 } else { 0 }; + if let Some(len) = self.query { + Some(&self.source[self.source.len() - len - fragment_len..self.source.len() - fragment_len]) + } else { + None + } + } + + #[cfg(test)] + fn fragment(&self) -> Option<&str> { + if let Some(len) = self.fragment { + Some(&self.source[self.source.len() - len..]) + } else { + None } } } -impl Display for RequestUri { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - RequestUri::AbsolutePath { ref path, ref query } => { - try!(f.write_str(path)); - match *query { - Some(ref q) => write!(f, "?{}", q), - None => Ok(()), - } - } - RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url), - RequestUri::Authority(ref path) => f.write_str(path), - RequestUri::Star => f.write_str("*") +impl FromStr for Uri { + type Err = Error; + + fn from_str(s: &str) -> Result { + Uri::new(s) + } +} + +impl From for Uri { + fn from(url: Url) -> Uri { + Uri::new(url.as_str()).expect("Uri::From failed") + } +} + +impl PartialEq for Uri { + fn eq(&self, other: &Uri) -> bool { + self.source == other.source + } +} + +impl AsRef for Uri { + fn as_ref(&self) -> &str { + &self.source + } +} + +impl Default for Uri { + fn default() -> Uri { + Uri { + source: "/".into(), + scheme_end: None, + authority_end: None, + query: None, + fragment: None, } } } -#[test] -fn test_uri_fromstr() { - fn parse(s: &str, result: RequestUri) { - assert_eq!(s.parse::().unwrap(), result); +impl fmt::Debug for Uri { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.source.as_ref(), f) } - fn parse_err(s: &str) { - assert!(s.parse::().is_err()); +} + +impl Display for Uri { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&self.source) + } +} + +macro_rules! test_parse { + ( + $test_name:ident, + $str:expr, + $($method:ident = $value:expr,)* + ) => ( + #[test] + fn $test_name() { + let uri = Uri::new($str).unwrap(); + $( + assert_eq!(uri.$method(), $value); + )+ + } + ); +} + +test_parse! { + test_uri_parse_origin_form, + "/some/path/here?and=then&hello#and-bye", + + scheme = None, + authority = None, + path = "/some/path/here", + query = Some("and=then&hello"), + fragment = Some("and-bye"), +} + +test_parse! { + test_uri_parse_absolute_form, + "http://127.0.0.1:61761/chunks", + + scheme = Some("http"), + authority = Some("127.0.0.1:61761"), + path = "/chunks", + query = None, + fragment = None, +} + +test_parse! { + test_uri_parse_absolute_form_without_path, + "https://127.0.0.1:61761", + + scheme = Some("https"), + authority = Some("127.0.0.1:61761"), + path = "/", + query = None, + fragment = None, +} + +test_parse! { + test_uri_parse_asterisk_form, + "*", + + scheme = None, + authority = None, + path = "*", + query = None, + fragment = None, +} + +test_parse! { + test_uri_parse_authority_form, + "localhost:3000", + + scheme = None, + authority = Some("localhost:3000"), + path = "", + query = None, + fragment = None, +} + +#[test] +fn test_uri_parse_error() { + fn err(s: &str) { + Uri::new(s).unwrap_err(); } - parse("*", RequestUri::Star); - parse("**", RequestUri::Authority("**".to_owned())); - parse("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); - parse("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); - parse_err("hyper.rs?key=value"); - parse_err("hyper.rs/"); - parse("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None }); + err("http://"); + //TODO: these should error + //err("htt:p//host"); + //err("hyper.rs/"); + //err("hyper.rs?key=val"); } #[test] -fn test_uri_display() { - fn assert_display(expected_string: &str, request_uri: RequestUri) { - assert_eq!(expected_string, format!("{}", request_uri)); - } - - assert_display("*", RequestUri::Star); - assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); - assert_display("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); - assert_display("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None }); - assert_display("/where?key=value", RequestUri::AbsolutePath { - path: "/where".to_owned(), - query: Some("key=value".to_owned()), - }); +fn test_uri_from_url() { + let uri = Uri::from(Url::parse("http://test.com/nazghul?test=3").unwrap()); + assert_eq!(uri.path(), "/nazghul"); + assert_eq!(uri.authority(), Some("test.com")); + assert_eq!(uri.scheme(), Some("http")); + assert_eq!(uri.query(), Some("test=3")); + assert_eq!(uri.as_ref(), "http://test.com/nazghul?test=3"); } diff --git a/tests/client.rs b/tests/client.rs index 2586a56d5f..a6affce35a 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -47,6 +47,7 @@ macro_rules! test { fn $name() { #![allow(unused)] use hyper::header::*; + let _ = pretty_env_logger::init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); @@ -74,7 +75,7 @@ macro_rules! test { while n < buf.len() && n < expected.len() { n += inc.read(&mut buf[n..]).unwrap(); } - assert_eq!(s(&buf[..n]), expected); + assert_eq!(s(&buf[..n]), expected, "expected is invalid"); inc.write_all($server_reply.as_ref()).unwrap(); tx.complete(()); @@ -85,9 +86,9 @@ macro_rules! test { let work = res.join(rx).map(|r| r.0); let res = core.run(work).unwrap(); - assert_eq!(res.status(), &StatusCode::$client_status); + assert_eq!(res.status(), &StatusCode::$client_status, "status is invalid"); $( - assert_eq!(res.headers().get(), Some(&$response_headers)); + assert_eq!(res.headers().get(), Some(&$response_headers), "headers are invalid"); )* } );