Proper handling of prefixed and non-prefixed apps

This commit is contained in:
Tomasz Drwięga 2016-05-12 17:13:26 +02:00
parent 3fc7faf24c
commit 0a85df10e8
8 changed files with 120 additions and 104 deletions

View File

@ -17,7 +17,7 @@
//! Simple REST API //! Simple REST API
use std::sync::Arc; use std::sync::Arc;
use endpoint::{Endpoint, Endpoints, ContentHandler, Handler, HostInfo}; use endpoint::{Endpoint, Endpoints, ContentHandler, Handler, EndpointPath};
pub struct RestApi { pub struct RestApi {
endpoints: Arc<Endpoints>, endpoints: Arc<Endpoints>,
@ -42,7 +42,7 @@ impl RestApi {
} }
impl Endpoint for RestApi { impl Endpoint for RestApi {
fn to_handler(&self, _prefix: &str, _host: Option<HostInfo>) -> Box<Handler> { fn to_handler(&self, _path: EndpointPath) -> Box<Handler> {
Box::new(ContentHandler::new(self.list_pages(), "application/json".to_owned())) Box::new(ContentHandler::new(self.list_pages(), "application/json".to_owned()))
} }
} }

View File

@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::net::SocketAddr;
use endpoint::Endpoints; use endpoint::Endpoints;
use page::PageEndpoint; use page::PageEndpoint;
use proxypac::ProxyPac; use proxypac::ProxyPac;
@ -28,9 +27,9 @@ pub fn main_page() -> &'static str {
"/status/" "/status/"
} }
pub fn all_endpoints(addr: &SocketAddr) -> Endpoints { pub fn all_endpoints() -> Endpoints {
let mut pages = Endpoints::new(); let mut pages = Endpoints::new();
pages.insert("proxy".to_owned(), ProxyPac::new(addr)); pages.insert("proxy".to_owned(), ProxyPac::boxed());
insert::<parity_status::App>(&mut pages, "status"); insert::<parity_status::App>(&mut pages, "status");
insert::<parity_status::App>(&mut pages, "parity"); insert::<parity_status::App>(&mut pages, "parity");

View File

@ -16,7 +16,6 @@
//! URL Endpoint traits //! URL Endpoint traits
use url::Host;
use hyper::status::StatusCode; use hyper::status::StatusCode;
use hyper::{header, server, Decoder, Encoder, Next}; use hyper::{header, server, Decoder, Encoder, Next};
use hyper::net::HttpStream; use hyper::net::HttpStream;
@ -24,13 +23,15 @@ use hyper::net::HttpStream;
use std::io::Write; use std::io::Write;
use std::collections::HashMap; use std::collections::HashMap;
pub struct HostInfo { #[derive(Debug, PartialEq, Default, Clone)]
pub host: Host, pub struct EndpointPath {
pub app_id: String,
pub host: String,
pub port: u16, pub port: u16,
} }
pub trait Endpoint : Send + Sync { pub trait Endpoint : Send + Sync {
fn to_handler(&self, prefix: &str, host: Option<HostInfo>) -> Box<server::Handler<HttpStream>>; fn to_handler(&self, path: EndpointPath) -> Box<server::Handler<HttpStream>>;
} }
pub type Endpoints = HashMap<String, Box<Endpoint>>; pub type Endpoints = HashMap<String, Box<Endpoint>>;

View File

@ -106,7 +106,7 @@ pub struct Server {
impl Server { impl Server {
fn start_http<A: Authorization + 'static>(addr: &SocketAddr, authorization: A, handler: Arc<IoHandler>) -> Result<Server, ServerError> { fn start_http<A: Authorization + 'static>(addr: &SocketAddr, authorization: A, handler: Arc<IoHandler>) -> Result<Server, ServerError> {
let panic_handler = Arc::new(Mutex::new(None)); let panic_handler = Arc::new(Mutex::new(None));
let endpoints = Arc::new(apps::all_endpoints(addr)); let endpoints = Arc::new(apps::all_endpoints());
let authorization = Arc::new(authorization); let authorization = Arc::new(authorization);
let rpc_endpoint = Arc::new(rpc::rpc(handler, panic_handler.clone())); let rpc_endpoint = Arc::new(rpc::rpc(handler, panic_handler.clone()));
let api = Arc::new(api::RestApi::new(endpoints.clone())); let api = Arc::new(api::RestApi::new(endpoints.clone()));

View File

@ -22,7 +22,7 @@ use hyper::header;
use hyper::status::StatusCode; use hyper::status::StatusCode;
use hyper::net::HttpStream; use hyper::net::HttpStream;
use hyper::{Decoder, Encoder, Next}; use hyper::{Decoder, Encoder, Next};
use endpoint::{Endpoint, HostInfo}; use endpoint::{Endpoint, EndpointPath};
use parity_webapp::WebApp; use parity_webapp::WebApp;
pub struct PageEndpoint<T : WebApp + 'static> { pub struct PageEndpoint<T : WebApp + 'static> {
@ -38,12 +38,11 @@ impl<T: WebApp + 'static> PageEndpoint<T> {
} }
impl<T: WebApp> Endpoint for PageEndpoint<T> { impl<T: WebApp> Endpoint for PageEndpoint<T> {
fn to_handler(&self, prefix: &str, _host: Option<HostInfo>) -> Box<server::Handler<HttpStream>> { fn to_handler(&self, path: EndpointPath) -> Box<server::Handler<HttpStream>> {
Box::new(PageHandler { Box::new(PageHandler {
app: self.app.clone(), app: self.app.clone(),
prefix: prefix.to_owned(), path: path,
prefix_with_slash: prefix.to_owned() + "/", file: None,
path: None,
write_pos: 0, write_pos: 0,
}) })
} }
@ -51,25 +50,33 @@ impl<T: WebApp> Endpoint for PageEndpoint<T> {
struct PageHandler<T: WebApp + 'static> { struct PageHandler<T: WebApp + 'static> {
app: Arc<T>, app: Arc<T>,
prefix: String, path: EndpointPath,
prefix_with_slash: String, file: Option<String>,
path: Option<String>,
write_pos: usize, write_pos: usize,
} }
impl<T: WebApp + 'static> PageHandler<T> { impl<T: WebApp + 'static> PageHandler<T> {
fn extract_path(&self, path: &str) -> String { fn extract_path(&self, path: &str) -> String {
let prefix = "/".to_owned() + &self.path.app_id;
let prefix_with_slash = prefix.clone() + "/";
// Index file support // Index file support
match path == &self.prefix || path == &self.prefix_with_slash { match path == "/" || path == &prefix || path == &prefix_with_slash {
true => "index.html".to_owned(), true => "index.html".to_owned(),
false => path[self.prefix_with_slash.len()..].to_owned(), false => if path.starts_with(&prefix_with_slash) {
path[prefix_with_slash.len()..].to_owned()
} else if path.starts_with("/") {
path[1..].to_owned()
} else {
path.to_owned()
}
} }
} }
} }
impl<T: WebApp + 'static> server::Handler<HttpStream> for PageHandler<T> { impl<T: WebApp + 'static> server::Handler<HttpStream> for PageHandler<T> {
fn on_request(&mut self, req: server::Request) -> Next { fn on_request(&mut self, req: server::Request) -> Next {
self.path = match *req.uri() { self.file = match *req.uri() {
RequestUri::AbsolutePath(ref path) => { RequestUri::AbsolutePath(ref path) => {
Some(self.extract_path(path)) Some(self.extract_path(path))
}, },
@ -86,7 +93,7 @@ impl<T: WebApp + 'static> server::Handler<HttpStream> for PageHandler<T> {
} }
fn on_response(&mut self, res: &mut server::Response) -> Next { fn on_response(&mut self, res: &mut server::Response) -> Next {
if let Some(f) = self.path.as_ref().and_then(|f| self.app.file(f)) { if let Some(f) = self.file.as_ref().and_then(|f| self.app.file(f)) {
res.set_status(StatusCode::Ok); res.set_status(StatusCode::Ok);
res.headers_mut().set(header::ContentType(f.content_type.parse().unwrap())); res.headers_mut().set(header::ContentType(f.content_type.parse().unwrap()));
Next::write() Next::write()
@ -98,7 +105,7 @@ impl<T: WebApp + 'static> server::Handler<HttpStream> for PageHandler<T> {
fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next { fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next {
let (wrote, res) = { let (wrote, res) = {
let file = self.path.as_ref().and_then(|f| self.app.file(f)); let file = self.file.as_ref().and_then(|f| self.app.file(f));
match file { match file {
None => (None, Next::end()), None => (None, Next::end()),
Some(f) if self.write_pos == f.content.len() => (None, Next::end()), Some(f) if self.write_pos == f.content.len() => (None, Next::end()),

View File

@ -16,37 +16,31 @@
//! Serving ProxyPac file //! Serving ProxyPac file
use std::net::SocketAddr; use endpoint::{Endpoint, Handler, ContentHandler, EndpointPath};
use endpoint::{Endpoint, Handler, ContentHandler, HostInfo};
use DAPPS_DOMAIN; use DAPPS_DOMAIN;
pub struct ProxyPac { pub struct ProxyPac;
addr: SocketAddr,
}
impl ProxyPac { impl ProxyPac {
pub fn new(addr: &SocketAddr) -> Box<Endpoint> { pub fn boxed() -> Box<Endpoint> {
Box::new(ProxyPac { Box::new(ProxyPac)
addr: addr.clone(),
})
} }
} }
impl Endpoint for ProxyPac { impl Endpoint for ProxyPac {
fn to_handler(&self, _prefix: &str, host: Option<HostInfo>) -> Box<Handler> { fn to_handler(&self, path: EndpointPath) -> Box<Handler> {
let host = host.map_or_else(|| format!("{}", self.addr), |h| format!("{}:{}", h.host, h.port));
let content = format!( let content = format!(
r#" r#"
function FindProxyForURL(url, host) {{ function FindProxyForURL(url, host) {{
if (shExpMatch(host, "*{0}")) if (shExpMatch(host, "*{0}"))
{{ {{
return "PROXY {1}"; return "PROXY {1}:{2}";
}} }}
return "DIRECT"; return "DIRECT";
}} }}
"#, "#,
DAPPS_DOMAIN, host); DAPPS_DOMAIN, path.host, path.port);
Box::new(ContentHandler::new(content, "application/javascript".to_owned())) Box::new(ContentHandler::new(content, "application/javascript".to_owned()))
} }
} }

View File

@ -28,11 +28,18 @@ use hyper;
use hyper::{server, uri, header}; use hyper::{server, uri, header};
use hyper::{Next, Encoder, Decoder}; use hyper::{Next, Encoder, Decoder};
use hyper::net::HttpStream; use hyper::net::HttpStream;
use endpoint::{Endpoint, Endpoints, HostInfo}; use endpoint::{Endpoint, Endpoints, EndpointPath};
use self::url::Url; use self::url::Url;
use self::auth::{Authorization, Authorized}; use self::auth::{Authorization, Authorized};
use self::redirect::Redirection; use self::redirect::Redirection;
#[derive(Debug, PartialEq)]
enum SpecialEndpoint {
Rpc,
Api,
None
}
pub struct Router<A: Authorization + 'static> { pub struct Router<A: Authorization + 'static> {
main_page: &'static str, main_page: &'static str,
endpoints: Arc<Endpoints>, endpoints: Arc<Endpoints>,
@ -42,13 +49,6 @@ pub struct Router<A: Authorization + 'static> {
handler: Box<server::Handler<HttpStream>>, handler: Box<server::Handler<HttpStream>>,
} }
#[derive(Debug, PartialEq)]
struct AppId {
id: String,
prefix: String,
is_rpc: bool,
}
impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> { impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
fn on_request(&mut self, req: server::Request) -> Next { fn on_request(&mut self, req: server::Request) -> Next {
@ -60,23 +60,20 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
Authorized::No(handler) => handler, Authorized::No(handler) => handler,
Authorized::Yes => { Authorized::Yes => {
let url = extract_url(&req); let url = extract_url(&req);
let app_id = extract_app_id(&url); let endpoint = extract_endpoint(&url);
let host = url.map(|u| HostInfo {
host: u.host,
port: u.port
});
match app_id { match endpoint {
// First check RPC requests // First check RPC requests
Some(ref app_id) if app_id.is_rpc && *req.method() != hyper::method::Method::Get => { (ref path, SpecialEndpoint::Rpc) if *req.method() != hyper::method::Method::Get => {
self.rpc.to_handler("", host) self.rpc.to_handler(path.clone().unwrap_or_default())
},
// Check API requests
(ref path, SpecialEndpoint::Api) => {
self.api.to_handler(path.clone().unwrap_or_default())
}, },
// Then delegate to dapp // Then delegate to dapp
Some(ref app_id) if self.endpoints.contains_key(&app_id.id) => { (Some(ref path), _) if self.endpoints.contains_key(&path.app_id) => {
self.endpoints.get(&app_id.id).unwrap().to_handler(&app_id.prefix, host) self.endpoints.get(&path.app_id).unwrap().to_handler(path.clone())
},
Some(ref app_id) if app_id.id == "api" => {
self.api.to_handler(&app_id.prefix, host)
}, },
// Redirection to main page // Redirection to main page
_ if *req.method() == hyper::method::Method::Get => { _ if *req.method() == hyper::method::Method::Get => {
@ -84,7 +81,7 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
}, },
// RPC by default // RPC by default
_ => { _ => {
self.rpc.to_handler("", host) self.rpc.to_handler(EndpointPath::default())
} }
} }
} }
@ -118,7 +115,7 @@ impl<A: Authorization> Router<A> {
api: Arc<Box<Endpoint>>, api: Arc<Box<Endpoint>>,
authorization: Arc<A>) -> Self { authorization: Arc<A>) -> Self {
let handler = rpc.to_handler("", None); let handler = rpc.to_handler(EndpointPath::default());
Router { Router {
main_page: main_page, main_page: main_page,
endpoints: endpoints, endpoints: endpoints,
@ -156,9 +153,16 @@ fn extract_url(req: &server::Request) -> Option<Url> {
} }
} }
fn extract_app_id(url: &Option<Url>) -> Option<AppId> { fn extract_endpoint(url: &Option<Url>) -> (Option<EndpointPath>, SpecialEndpoint) {
fn is_rpc(url: &Url) -> bool { fn special_endpoint(url: &Url) -> SpecialEndpoint {
url.path.len() > 1 && url.path[0] == "rpc" if url.path.len() <= 1 {
return SpecialEndpoint::None;
}
match url.path[0].as_ref() {
"rpc" => SpecialEndpoint::Rpc,
"api" => SpecialEndpoint::Api,
_ => SpecialEndpoint::None,
}
} }
match *url { match *url {
@ -167,64 +171,77 @@ fn extract_app_id(url: &Option<Url>) -> Option<AppId> {
let len = domain.len() - DAPPS_DOMAIN.len(); let len = domain.len() - DAPPS_DOMAIN.len();
let id = domain[0..len].to_owned(); let id = domain[0..len].to_owned();
Some(AppId { (Some(EndpointPath {
id: id, app_id: id,
prefix: "".to_owned(), host: domain.clone(),
is_rpc: is_rpc(url), port: url.port,
}) }), special_endpoint(url))
}, },
_ if url.path.len() > 1 => { _ if url.path.len() > 1 => {
let id = url.path[0].clone(); let id = url.path[0].clone();
Some(AppId { (Some(EndpointPath {
id: id.clone(), app_id: id.clone(),
prefix: "/".to_owned() + &id, host: format!("{}", url.host),
is_rpc: is_rpc(url), port: url.port,
}) }), special_endpoint(url))
}, },
_ => None, _ => (None, special_endpoint(url)),
}, },
_ => None _ => (None, SpecialEndpoint::None)
} }
} }
#[test] #[test]
fn should_extract_app_id() { fn should_extract_endpoint() {
assert_eq!(extract_app_id(&None), None); assert_eq!(extract_endpoint(&None), (None, SpecialEndpoint::None));
// With path prefix // With path prefix
assert_eq!( assert_eq!(
extract_app_id(&Url::parse("http://localhost:8080/status/index.html").ok()), extract_endpoint(&Url::parse("http://localhost:8080/status/index.html").ok()),
Some(AppId { (Some(EndpointPath {
id: "status".to_owned(), app_id: "status".to_owned(),
prefix: "/status".to_owned(), host: "localhost".to_owned(),
is_rpc: false, port: 8080,
})); }), SpecialEndpoint::None)
);
// With path prefix // With path prefix
assert_eq!( assert_eq!(
extract_app_id(&Url::parse("http://localhost:8080/rpc/").ok()), extract_endpoint(&Url::parse("http://localhost:8080/rpc/").ok()),
Some(AppId { (Some(EndpointPath {
id: "rpc".to_owned(), app_id: "rpc".to_owned(),
prefix: "/rpc".to_owned(), host: "localhost".to_owned(),
is_rpc: true, port: 8080,
})); }), SpecialEndpoint::Rpc)
);
// By Subdomain // By Subdomain
assert_eq!( assert_eq!(
extract_app_id(&Url::parse("http://my.status.dapp/test.html").ok()), extract_endpoint(&Url::parse("http://my.status.dapp/test.html").ok()),
Some(AppId { (Some(EndpointPath {
id: "my.status".to_owned(), app_id: "my.status".to_owned(),
prefix: "".to_owned(), host: "my.status.dapp".to_owned(),
is_rpc: false, port: 80,
})); }), SpecialEndpoint::None)
);
// RPC by subdomain // RPC by subdomain
assert_eq!( assert_eq!(
extract_app_id(&Url::parse("http://my.status.dapp/rpc/").ok()), extract_endpoint(&Url::parse("http://my.status.dapp/rpc/").ok()),
Some(AppId { (Some(EndpointPath {
id: "my.status".to_owned(), app_id: "my.status".to_owned(),
prefix: "".to_owned(), host: "my.status.dapp".to_owned(),
is_rpc: true, port: 80,
})); }), SpecialEndpoint::Rpc)
);
// API by subdomain
assert_eq!(
extract_endpoint(&Url::parse("http://my.status.dapp/rpc/").ok()),
(Some(EndpointPath {
app_id: "my.status".to_owned(),
host: "my.status.dapp".to_owned(),
port: 80,
}), SpecialEndpoint::Api)
);
} }

View File

@ -15,11 +15,9 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use hyper::server;
use hyper::net::HttpStream;
use jsonrpc_core::IoHandler; use jsonrpc_core::IoHandler;
use jsonrpc_http_server::{ServerHandler, PanicHandler, AccessControlAllowOrigin}; use jsonrpc_http_server::{ServerHandler, PanicHandler, AccessControlAllowOrigin};
use endpoint::{Endpoint, HostInfo}; use endpoint::{Endpoint, EndpointPath, Handler};
pub fn rpc(handler: Arc<IoHandler>, panic_handler: Arc<Mutex<Option<Box<Fn() -> () + Send>>>>) -> Box<Endpoint> { pub fn rpc(handler: Arc<IoHandler>, panic_handler: Arc<Mutex<Option<Box<Fn() -> () + Send>>>>) -> Box<Endpoint> {
Box::new(RpcEndpoint { Box::new(RpcEndpoint {
@ -36,7 +34,7 @@ struct RpcEndpoint {
} }
impl Endpoint for RpcEndpoint { impl Endpoint for RpcEndpoint {
fn to_handler(&self, _prefix: &str, _host: Option<HostInfo>) -> Box<server::Handler<HttpStream>> { fn to_handler(&self, _path: EndpointPath) -> Box<Handler> {
let panic_handler = PanicHandler { handler: self.panic_handler.clone() }; let panic_handler = PanicHandler { handler: self.panic_handler.clone() };
Box::new(ServerHandler::new(self.handler.clone(), self.cors_domain.clone(), panic_handler)) Box::new(ServerHandler::new(self.handler.clone(), self.cors_domain.clone(), panic_handler))
} }