From f62d0581861be825676b3ad3941b736cf9b311cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Thu, 12 May 2016 14:45:09 +0200 Subject: [PATCH 1/4] Proxy.pac serving --- webapp/src/api.rs | 51 ++------------------------------ webapp/src/apps.rs | 14 +++++---- webapp/src/endpoint.rs | 64 ++++++++++++++++++++++++++++++++++++++-- webapp/src/lib.rs | 5 +++- webapp/src/page/mod.rs | 4 +-- webapp/src/proxypac.rs | 54 +++++++++++++++++++++++++++++++++ webapp/src/router/mod.rs | 50 ++++++++++++++++++++----------- webapp/src/rpc.rs | 4 +-- 8 files changed, 167 insertions(+), 79 deletions(-) create mode 100644 webapp/src/proxypac.rs diff --git a/webapp/src/api.rs b/webapp/src/api.rs index bad49ec6165..893e7258a31 100644 --- a/webapp/src/api.rs +++ b/webapp/src/api.rs @@ -16,12 +16,8 @@ //! Simple REST API -use std::io::Write; use std::sync::Arc; -use hyper::status::StatusCode; -use hyper::{header, server, Decoder, Encoder, Next}; -use hyper::net::HttpStream; -use endpoint::{Endpoint, Endpoints}; +use endpoint::{Endpoint, Endpoints, ContentHandler, Handler, HostInfo}; pub struct RestApi { endpoints: Arc, @@ -46,49 +42,8 @@ impl RestApi { } impl Endpoint for RestApi { - fn to_handler(&self, _prefix: &str) -> Box> { - Box::new(RestApiHandler { - pages: self.list_pages(), - write_pos: 0, - }) + fn to_handler(&self, _prefix: &str, _host: Option) -> Box { + Box::new(ContentHandler::new(self.list_pages(), "application/json".to_owned())) } } -struct RestApiHandler { - pages: String, - write_pos: usize, -} - -impl server::Handler for RestApiHandler { - fn on_request(&mut self, _request: server::Request) -> Next { - Next::write() - } - - fn on_request_readable(&mut self, _decoder: &mut Decoder) -> Next { - Next::write() - } - - fn on_response(&mut self, res: &mut server::Response) -> Next { - res.set_status(StatusCode::Ok); - res.headers_mut().set(header::ContentType("application/json".parse().unwrap())); - Next::write() - } - - fn on_response_writable(&mut self, encoder: &mut Encoder) -> Next { - let bytes = self.pages.as_bytes(); - if self.write_pos == bytes.len() { - return Next::end(); - } - - match encoder.write(&bytes[self.write_pos..]) { - Ok(bytes) => { - self.write_pos += bytes; - Next::write() - }, - Err(e) => match e.kind() { - ::std::io::ErrorKind::WouldBlock => Next::write(), - _ => Next::end() - }, - } - } -} diff --git a/webapp/src/apps.rs b/webapp/src/apps.rs index b0a4472f7c1..21e1102adf4 100644 --- a/webapp/src/apps.rs +++ b/webapp/src/apps.rs @@ -14,8 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +use std::net::SocketAddr; use endpoint::Endpoints; use page::PageEndpoint; +use proxypac::ProxyPac; extern crate parity_status; #[cfg(feature = "parity-wallet")] @@ -26,17 +28,17 @@ pub fn main_page() -> &'static str { "/status/" } -pub fn all_endpoints() -> Endpoints { +pub fn all_endpoints(addr: &SocketAddr) -> Endpoints { let mut pages = Endpoints::new(); pages.insert("status".to_owned(), Box::new(PageEndpoint::new(parity_status::App::default()))); + pages.insert("proxy".to_owned(), ProxyPac::new(addr)); + wallet_page(&mut pages); pages } -#[cfg(feature = "parity-wallet")] fn wallet_page(pages: &mut Endpoints) { - pages.insert("wallet".to_owned(), Box::new(PageEndpoint::new(parity_wallet::App::default()))); + if cfg!(feature = "parity-wallet") { + pages.insert("wallet".to_owned(), Box::new(PageEndpoint::new(parity_wallet::App::default()))); + } } - -#[cfg(not(feature = "parity-wallet"))] -fn wallet_page(_pages: &mut Endpoints) {} diff --git a/webapp/src/endpoint.rs b/webapp/src/endpoint.rs index dee2cadd85b..53357063592 100644 --- a/webapp/src/endpoint.rs +++ b/webapp/src/endpoint.rs @@ -16,12 +16,72 @@ //! URL Endpoint traits -use hyper::server; +use url::Host; +use hyper::status::StatusCode; +use hyper::{header, server, Decoder, Encoder, Next}; use hyper::net::HttpStream; + +use std::io::Write; use std::collections::HashMap; +pub struct HostInfo { + pub host: Host, + pub port: u16, +} + pub trait Endpoint : Send + Sync { - fn to_handler(&self, prefix: &str) -> Box>; + fn to_handler(&self, prefix: &str, host: Option) -> Box>; } pub type Endpoints = HashMap>; +pub type Handler = server::Handler; + +pub struct ContentHandler { + content: String, + mimetype: String, + write_pos: usize, +} + +impl ContentHandler { + pub fn new(content: String, mimetype: String) -> Self { + ContentHandler { + content: content, + mimetype: mimetype, + write_pos: 0 + } + } +} + +impl server::Handler for ContentHandler { + fn on_request(&mut self, _request: server::Request) -> Next { + Next::write() + } + + fn on_request_readable(&mut self, _decoder: &mut Decoder) -> Next { + Next::write() + } + + fn on_response(&mut self, res: &mut server::Response) -> Next { + res.set_status(StatusCode::Ok); + res.headers_mut().set(header::ContentType(self.mimetype.parse().unwrap())); + Next::write() + } + + fn on_response_writable(&mut self, encoder: &mut Encoder) -> Next { + let bytes = self.content.as_bytes(); + if self.write_pos == bytes.len() { + return Next::end(); + } + + match encoder.write(&bytes[self.write_pos..]) { + Ok(bytes) => { + self.write_pos += bytes; + Next::write() + }, + Err(e) => match e.kind() { + ::std::io::ErrorKind::WouldBlock => Next::write(), + _ => Next::end() + }, + } + } +} diff --git a/webapp/src/lib.rs b/webapp/src/lib.rs index 30431578fcc..5ee93acc774 100644 --- a/webapp/src/lib.rs +++ b/webapp/src/lib.rs @@ -57,12 +57,15 @@ mod page; mod router; mod rpc; mod api; +mod proxypac; use std::sync::{Arc, Mutex}; use std::net::SocketAddr; use jsonrpc_core::{IoHandler, IoDelegate}; use router::auth::{Authorization, NoAuth, HttpBasicAuth}; +static DAPPS_DOMAIN : &'static str = "dapp"; + /// Webapps HTTP+RPC server build. pub struct ServerBuilder { handler: Arc, @@ -103,7 +106,7 @@ pub struct Server { impl Server { fn start_http(addr: &SocketAddr, authorization: A, handler: Arc) -> Result { let panic_handler = Arc::new(Mutex::new(None)); - let endpoints = Arc::new(apps::all_endpoints()); + let endpoints = Arc::new(apps::all_endpoints(addr)); let authorization = Arc::new(authorization); let rpc_endpoint = Arc::new(rpc::rpc(handler, panic_handler.clone())); let api = Arc::new(api::RestApi::new(endpoints.clone())); diff --git a/webapp/src/page/mod.rs b/webapp/src/page/mod.rs index cd527578b2a..68d8a14bd7a 100644 --- a/webapp/src/page/mod.rs +++ b/webapp/src/page/mod.rs @@ -22,7 +22,7 @@ use hyper::header; use hyper::status::StatusCode; use hyper::net::HttpStream; use hyper::{Decoder, Encoder, Next}; -use endpoint::Endpoint; +use endpoint::{Endpoint, HostInfo}; use parity_webapp::WebApp; pub struct PageEndpoint { @@ -38,7 +38,7 @@ impl PageEndpoint { } impl Endpoint for PageEndpoint { - fn to_handler(&self, prefix: &str) -> Box> { + fn to_handler(&self, prefix: &str, _host: Option) -> Box> { Box::new(PageHandler { app: self.app.clone(), prefix: prefix.to_owned(), diff --git a/webapp/src/proxypac.rs b/webapp/src/proxypac.rs new file mode 100644 index 00000000000..b8162fadfff --- /dev/null +++ b/webapp/src/proxypac.rs @@ -0,0 +1,54 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Serving ProxyPac file + +use std::net::SocketAddr; +use endpoint::{Endpoint, Handler, ContentHandler, HostInfo}; +use DAPPS_DOMAIN; + +pub struct ProxyPac { + addr: SocketAddr, +} + +impl ProxyPac { + pub fn new(addr: &SocketAddr) -> Box { + Box::new(ProxyPac { + addr: addr.clone(), + }) + } +} + +impl Endpoint for ProxyPac { + fn to_handler(&self, _prefix: &str, host: Option) -> Box { + let host = host.map_or_else(|| format!("{}", self.addr), |h| format!("{}:{}", h.host, h.port)); + let content = format!( +r#" +function FindProxyForURL(url, host) {{ + if (shExpMatch(host, "*.{0}")) + {{ + return "PROXY {1}"; + }} + + return "DIRECT"; +}} +"#, + DAPPS_DOMAIN, host); + Box::new(ContentHandler::new(content, "application/javascript".to_owned())) + } +} + + diff --git a/webapp/src/router/mod.rs b/webapp/src/router/mod.rs index 15fc496f9d7..1d8a24585b5 100644 --- a/webapp/src/router/mod.rs +++ b/webapp/src/router/mod.rs @@ -26,7 +26,7 @@ use hyper; use hyper::{server, uri, header}; use hyper::{Next, Encoder, Decoder}; use hyper::net::HttpStream; -use endpoint::{Endpoint, Endpoints}; +use endpoint::{Endpoint, Endpoints, HostInfo}; use self::url::Url; use self::auth::{Authorization, Authorized}; use self::redirect::Redirection; @@ -43,32 +43,39 @@ pub struct Router { impl server::Handler for Router { fn on_request(&mut self, req: server::Request) -> Next { + // Check authorization let auth = self.authorization.is_authorized(&req); + + // Choose proper handler depending on path / domain self.handler = match auth { Authorized::No(handler) => handler, Authorized::Yes => { - let path = self.extract_request_path(&req); - match path { - Some(ref url) if self.endpoints.contains_key(url) => { - let prefix = "/".to_owned() + url; - self.endpoints.get(url).unwrap().to_handler(&prefix) + let url = self.extract_url(&req); + let app_id = self.extract_app_id(&url); + let host = url.map(|u| HostInfo { + host: u.host, + port: u.port + }); + + match app_id { + Some(ref app_id) if self.endpoints.contains_key(&app_id.id) => { + self.endpoints.get(&app_id.id).unwrap().to_handler(&app_id.prefix, host) }, - Some(ref url) if url == "api" => { - self.api.to_handler("/api") + Some(ref app_id) if app_id.id == "api" => { + self.api.to_handler(&app_id.prefix, host) }, _ if *req.method() == hyper::method::Method::Get => { Redirection::new(self.main_page) }, _ => { - self.rpc.to_handler(&"/") + self.rpc.to_handler("/", host) } } } }; - self.handler.on_request(req) - // Check authorization - // Choose proper handler depending on path + // Delegate on_request to proper handler + self.handler.on_request(req) } /// This event occurs each time the `Request` is ready to be read from. @@ -95,7 +102,7 @@ impl Router { api: Arc>, authorization: Arc) -> Self { - let handler = rpc.to_handler(&"/"); + let handler = rpc.to_handler("/", None); Router { main_page: main_page, endpoints: endpoints, @@ -132,12 +139,14 @@ impl Router { } } - fn extract_request_path(&self, req: &server::Request) -> Option { - let url = self.extract_url(&req); - match url { + fn extract_app_id(&self, url: &Option) -> Option { + match *url { Some(ref url) if url.path.len() > 1 => { - let part = url.path[0].clone(); - Some(part) + let id = url.path[0].clone(); + Some(AppId { + id: id.clone(), + prefix: "/".to_owned() + &id + }) }, _ => { None @@ -145,3 +154,8 @@ impl Router { } } } + +struct AppId { + id: String, + prefix: String +} diff --git a/webapp/src/rpc.rs b/webapp/src/rpc.rs index 51e171d8d93..acd83aed5b7 100644 --- a/webapp/src/rpc.rs +++ b/webapp/src/rpc.rs @@ -19,7 +19,7 @@ use hyper::server; use hyper::net::HttpStream; use jsonrpc_core::IoHandler; use jsonrpc_http_server::{ServerHandler, PanicHandler, AccessControlAllowOrigin}; -use endpoint::Endpoint; +use endpoint::{Endpoint, HostInfo}; pub fn rpc(handler: Arc, panic_handler: Arc () + Send>>>>) -> Box { Box::new(RpcEndpoint { @@ -36,7 +36,7 @@ struct RpcEndpoint { } impl Endpoint for RpcEndpoint { - fn to_handler(&self, _prefix: &str) -> Box> { + fn to_handler(&self, _prefix: &str, _host: Option) -> Box> { let panic_handler = PanicHandler { handler: self.panic_handler.clone() }; Box::new(ServerHandler::new(self.handler.clone(), self.cors_domain.clone(), panic_handler)) } From 3fc7faf24c08b6ea88ab4cea53f4830772e15c46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Thu, 12 May 2016 15:05:59 +0200 Subject: [PATCH 2/4] Subdomains router for dapps --- webapp/src/apps.rs | 18 +++-- webapp/src/lib.rs | 2 +- webapp/src/page/mod.rs | 26 +++++-- webapp/src/proxypac.rs | 2 +- webapp/src/router/mod.rs | 145 +++++++++++++++++++++++++++++---------- 5 files changed, 141 insertions(+), 52 deletions(-) diff --git a/webapp/src/apps.rs b/webapp/src/apps.rs index 21e1102adf4..7470786a5dc 100644 --- a/webapp/src/apps.rs +++ b/webapp/src/apps.rs @@ -18,27 +18,35 @@ use std::net::SocketAddr; use endpoint::Endpoints; use page::PageEndpoint; use proxypac::ProxyPac; +use parity_webapp::WebApp; extern crate parity_status; #[cfg(feature = "parity-wallet")] extern crate parity_wallet; - pub fn main_page() -> &'static str { "/status/" } pub fn all_endpoints(addr: &SocketAddr) -> Endpoints { let mut pages = Endpoints::new(); - pages.insert("status".to_owned(), Box::new(PageEndpoint::new(parity_status::App::default()))); pages.insert("proxy".to_owned(), ProxyPac::new(addr)); + insert::(&mut pages, "status"); + insert::(&mut pages, "parity"); + wallet_page(&mut pages); pages } +#[cfg(feature = "parity-wallet")] fn wallet_page(pages: &mut Endpoints) { - if cfg!(feature = "parity-wallet") { - pages.insert("wallet".to_owned(), Box::new(PageEndpoint::new(parity_wallet::App::default()))); - } + insert::(pages, "wallet"); +} + +#[cfg(not(feature = "parity-wallet"))] +fn wallet_page(_pages: &mut Endpoints) {} + +fn insert(pages: &mut Endpoints, id: &str) { + pages.insert(id.to_owned(), Box::new(PageEndpoint::new(T::default()))); } diff --git a/webapp/src/lib.rs b/webapp/src/lib.rs index 5ee93acc774..18b0880056e 100644 --- a/webapp/src/lib.rs +++ b/webapp/src/lib.rs @@ -64,7 +64,7 @@ use std::net::SocketAddr; use jsonrpc_core::{IoHandler, IoDelegate}; use router::auth::{Authorization, NoAuth, HttpBasicAuth}; -static DAPPS_DOMAIN : &'static str = "dapp"; +static DAPPS_DOMAIN : &'static str = ".dapp"; /// Webapps HTTP+RPC server build. pub struct ServerBuilder { diff --git a/webapp/src/page/mod.rs b/webapp/src/page/mod.rs index 68d8a14bd7a..b2cf9615b40 100644 --- a/webapp/src/page/mod.rs +++ b/webapp/src/page/mod.rs @@ -57,15 +57,27 @@ struct PageHandler { write_pos: usize, } +impl PageHandler { + fn extract_path(&self, path: &str) -> String { + // Index file support + match path == &self.prefix || path == &self.prefix_with_slash { + true => "index.html".to_owned(), + false => path[self.prefix_with_slash.len()..].to_owned(), + } + } +} + impl server::Handler for PageHandler { fn on_request(&mut self, req: server::Request) -> Next { - if let RequestUri::AbsolutePath(ref path) = *req.uri() { - // Index file support - self.path = match path == &self.prefix || path == &self.prefix_with_slash { - true => Some("index.html".to_owned()), - false => Some(path[self.prefix_with_slash.len()..].to_owned()), - }; - } + self.path = match *req.uri() { + RequestUri::AbsolutePath(ref path) => { + Some(self.extract_path(path)) + }, + RequestUri::AbsoluteUri(ref url) => { + Some(self.extract_path(url.path())) + }, + _ => None, + }; Next::write() } diff --git a/webapp/src/proxypac.rs b/webapp/src/proxypac.rs index b8162fadfff..b39c725006e 100644 --- a/webapp/src/proxypac.rs +++ b/webapp/src/proxypac.rs @@ -38,7 +38,7 @@ impl Endpoint for ProxyPac { let content = format!( r#" function FindProxyForURL(url, host) {{ - if (shExpMatch(host, "*.{0}")) + if (shExpMatch(host, "*{0}")) {{ return "PROXY {1}"; }} diff --git a/webapp/src/router/mod.rs b/webapp/src/router/mod.rs index 1d8a24585b5..dc8abdadae3 100644 --- a/webapp/src/router/mod.rs +++ b/webapp/src/router/mod.rs @@ -21,7 +21,9 @@ mod url; mod redirect; pub mod auth; +use DAPPS_DOMAIN; use std::sync::Arc; +use url::Host; use hyper; use hyper::{server, uri, header}; use hyper::{Next, Encoder, Decoder}; @@ -40,6 +42,13 @@ pub struct Router { handler: Box>, } +#[derive(Debug, PartialEq)] +struct AppId { + id: String, + prefix: String, + is_rpc: bool, +} + impl server::Handler for Router { fn on_request(&mut self, req: server::Request) -> Next { @@ -50,25 +59,32 @@ impl server::Handler for Router { self.handler = match auth { Authorized::No(handler) => handler, Authorized::Yes => { - let url = self.extract_url(&req); - let app_id = self.extract_app_id(&url); + let url = extract_url(&req); + let app_id = extract_app_id(&url); let host = url.map(|u| HostInfo { host: u.host, port: u.port }); match app_id { + // First check RPC requests + Some(ref app_id) if app_id.is_rpc && *req.method() != hyper::method::Method::Get => { + self.rpc.to_handler("", host) + }, + // Then delegate to dapp Some(ref app_id) if self.endpoints.contains_key(&app_id.id) => { self.endpoints.get(&app_id.id).unwrap().to_handler(&app_id.prefix, host) }, Some(ref app_id) if app_id.id == "api" => { self.api.to_handler(&app_id.prefix, host) }, + // Redirection to main page _ if *req.method() == hyper::method::Method::Get => { Redirection::new(self.main_page) }, + // RPC by default _ => { - self.rpc.to_handler("/", host) + self.rpc.to_handler("", host) } } } @@ -102,7 +118,7 @@ impl Router { api: Arc>, authorization: Arc) -> Self { - let handler = rpc.to_handler("/", None); + let handler = rpc.to_handler("", None); Router { main_page: main_page, endpoints: endpoints, @@ -112,50 +128,103 @@ impl Router { handler: handler, } } +} - fn extract_url(&self, req: &server::Request) -> Option { - match *req.uri() { - uri::RequestUri::AbsoluteUri(ref url) => { - match Url::from_generic_url(url.clone()) { - Ok(url) => Some(url), - _ => None, - } - }, - uri::RequestUri::AbsolutePath(ref path) => { - // Attempt to prepend the Host header (mandatory in HTTP/1.1) - let url_string = match req.headers().get::() { - Some(ref host) => { - format!("http://{}:{}{}", host.hostname, host.port.unwrap_or(80), path) - }, - None => return None, - }; +fn extract_url(req: &server::Request) -> Option { + match *req.uri() { + uri::RequestUri::AbsoluteUri(ref url) => { + match Url::from_generic_url(url.clone()) { + Ok(url) => Some(url), + _ => None, + } + }, + uri::RequestUri::AbsolutePath(ref path) => { + // Attempt to prepend the Host header (mandatory in HTTP/1.1) + let url_string = match req.headers().get::() { + Some(ref host) => { + format!("http://{}:{}{}", host.hostname, host.port.unwrap_or(80), path) + }, + None => return None, + }; + + match Url::parse(&url_string) { + Ok(url) => Some(url), + _ => None, + } + }, + _ => None, + } +} - match Url::parse(&url_string) { - Ok(url) => Some(url), - _ => None, - } - }, - _ => None, - } +fn extract_app_id(url: &Option) -> Option { + fn is_rpc(url: &Url) -> bool { + url.path.len() > 1 && url.path[0] == "rpc" } - fn extract_app_id(&self, url: &Option) -> Option { - match *url { - Some(ref url) if url.path.len() > 1 => { + match *url { + Some(ref url) => match url.host { + Host::Domain(ref domain) if domain.ends_with(DAPPS_DOMAIN) => { + let len = domain.len() - DAPPS_DOMAIN.len(); + let id = domain[0..len].to_owned(); + + Some(AppId { + id: id, + prefix: "".to_owned(), + is_rpc: is_rpc(url), + }) + }, + _ if url.path.len() > 1 => { let id = url.path[0].clone(); Some(AppId { id: id.clone(), - prefix: "/".to_owned() + &id + prefix: "/".to_owned() + &id, + is_rpc: is_rpc(url), }) }, - _ => { - None - }, - } + _ => None, + }, + _ => None } } -struct AppId { - id: String, - prefix: String +#[test] +fn should_extract_app_id() { + assert_eq!(extract_app_id(&None), None); + + // With path prefix + assert_eq!( + extract_app_id(&Url::parse("http://localhost:8080/status/index.html").ok()), + Some(AppId { + id: "status".to_owned(), + prefix: "/status".to_owned(), + is_rpc: false, + })); + + // With path prefix + assert_eq!( + extract_app_id(&Url::parse("http://localhost:8080/rpc/").ok()), + Some(AppId { + id: "rpc".to_owned(), + prefix: "/rpc".to_owned(), + is_rpc: true, + })); + + // By Subdomain + assert_eq!( + extract_app_id(&Url::parse("http://my.status.dapp/test.html").ok()), + Some(AppId { + id: "my.status".to_owned(), + prefix: "".to_owned(), + is_rpc: false, + })); + + // RPC by subdomain + assert_eq!( + extract_app_id(&Url::parse("http://my.status.dapp/rpc/").ok()), + Some(AppId { + id: "my.status".to_owned(), + prefix: "".to_owned(), + is_rpc: true, + })); + } From 0a85df10e8c0413c28c61fc54610a86bdc90fa0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Thu, 12 May 2016 17:13:26 +0200 Subject: [PATCH 3/4] Proper handling of prefixed and non-prefixed apps --- webapp/src/api.rs | 4 +- webapp/src/apps.rs | 5 +- webapp/src/endpoint.rs | 9 +-- webapp/src/lib.rs | 2 +- webapp/src/page/mod.rs | 33 +++++---- webapp/src/proxypac.rs | 20 ++---- webapp/src/router/mod.rs | 147 ++++++++++++++++++++++----------------- webapp/src/rpc.rs | 6 +- 8 files changed, 121 insertions(+), 105 deletions(-) diff --git a/webapp/src/api.rs b/webapp/src/api.rs index 893e7258a31..75cdb4c5874 100644 --- a/webapp/src/api.rs +++ b/webapp/src/api.rs @@ -17,7 +17,7 @@ //! Simple REST API use std::sync::Arc; -use endpoint::{Endpoint, Endpoints, ContentHandler, Handler, HostInfo}; +use endpoint::{Endpoint, Endpoints, ContentHandler, Handler, EndpointPath}; pub struct RestApi { endpoints: Arc, @@ -42,7 +42,7 @@ impl RestApi { } impl Endpoint for RestApi { - fn to_handler(&self, _prefix: &str, _host: Option) -> Box { + fn to_handler(&self, _path: EndpointPath) -> Box { Box::new(ContentHandler::new(self.list_pages(), "application/json".to_owned())) } } diff --git a/webapp/src/apps.rs b/webapp/src/apps.rs index 7470786a5dc..c07e9919cf1 100644 --- a/webapp/src/apps.rs +++ b/webapp/src/apps.rs @@ -14,7 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use std::net::SocketAddr; use endpoint::Endpoints; use page::PageEndpoint; use proxypac::ProxyPac; @@ -28,9 +27,9 @@ pub fn main_page() -> &'static str { "/status/" } -pub fn all_endpoints(addr: &SocketAddr) -> Endpoints { +pub fn all_endpoints() -> Endpoints { let mut pages = Endpoints::new(); - pages.insert("proxy".to_owned(), ProxyPac::new(addr)); + pages.insert("proxy".to_owned(), ProxyPac::boxed()); insert::(&mut pages, "status"); insert::(&mut pages, "parity"); diff --git a/webapp/src/endpoint.rs b/webapp/src/endpoint.rs index 53357063592..d367734c4a5 100644 --- a/webapp/src/endpoint.rs +++ b/webapp/src/endpoint.rs @@ -16,7 +16,6 @@ //! URL Endpoint traits -use url::Host; use hyper::status::StatusCode; use hyper::{header, server, Decoder, Encoder, Next}; use hyper::net::HttpStream; @@ -24,13 +23,15 @@ use hyper::net::HttpStream; use std::io::Write; use std::collections::HashMap; -pub struct HostInfo { - pub host: Host, +#[derive(Debug, PartialEq, Default, Clone)] +pub struct EndpointPath { + pub app_id: String, + pub host: String, pub port: u16, } pub trait Endpoint : Send + Sync { - fn to_handler(&self, prefix: &str, host: Option) -> Box>; + fn to_handler(&self, path: EndpointPath) -> Box>; } pub type Endpoints = HashMap>; diff --git a/webapp/src/lib.rs b/webapp/src/lib.rs index 18b0880056e..45157f07642 100644 --- a/webapp/src/lib.rs +++ b/webapp/src/lib.rs @@ -106,7 +106,7 @@ pub struct Server { impl Server { fn start_http(addr: &SocketAddr, authorization: A, handler: Arc) -> Result { 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 rpc_endpoint = Arc::new(rpc::rpc(handler, panic_handler.clone())); let api = Arc::new(api::RestApi::new(endpoints.clone())); diff --git a/webapp/src/page/mod.rs b/webapp/src/page/mod.rs index b2cf9615b40..abcd1930bf1 100644 --- a/webapp/src/page/mod.rs +++ b/webapp/src/page/mod.rs @@ -22,7 +22,7 @@ use hyper::header; use hyper::status::StatusCode; use hyper::net::HttpStream; use hyper::{Decoder, Encoder, Next}; -use endpoint::{Endpoint, HostInfo}; +use endpoint::{Endpoint, EndpointPath}; use parity_webapp::WebApp; pub struct PageEndpoint { @@ -38,12 +38,11 @@ impl PageEndpoint { } impl Endpoint for PageEndpoint { - fn to_handler(&self, prefix: &str, _host: Option) -> Box> { + fn to_handler(&self, path: EndpointPath) -> Box> { Box::new(PageHandler { app: self.app.clone(), - prefix: prefix.to_owned(), - prefix_with_slash: prefix.to_owned() + "/", - path: None, + path: path, + file: None, write_pos: 0, }) } @@ -51,25 +50,33 @@ impl Endpoint for PageEndpoint { struct PageHandler { app: Arc, - prefix: String, - prefix_with_slash: String, - path: Option, + path: EndpointPath, + file: Option, write_pos: usize, } impl PageHandler { fn extract_path(&self, path: &str) -> String { + let prefix = "/".to_owned() + &self.path.app_id; + let prefix_with_slash = prefix.clone() + "/"; + // 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(), - 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 server::Handler for PageHandler { fn on_request(&mut self, req: server::Request) -> Next { - self.path = match *req.uri() { + self.file = match *req.uri() { RequestUri::AbsolutePath(ref path) => { Some(self.extract_path(path)) }, @@ -86,7 +93,7 @@ impl server::Handler for PageHandler { } 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.headers_mut().set(header::ContentType(f.content_type.parse().unwrap())); Next::write() @@ -98,7 +105,7 @@ impl server::Handler for PageHandler { fn on_response_writable(&mut self, encoder: &mut Encoder) -> Next { 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 { None => (None, Next::end()), Some(f) if self.write_pos == f.content.len() => (None, Next::end()), diff --git a/webapp/src/proxypac.rs b/webapp/src/proxypac.rs index b39c725006e..da2cab916bb 100644 --- a/webapp/src/proxypac.rs +++ b/webapp/src/proxypac.rs @@ -16,37 +16,31 @@ //! Serving ProxyPac file -use std::net::SocketAddr; -use endpoint::{Endpoint, Handler, ContentHandler, HostInfo}; +use endpoint::{Endpoint, Handler, ContentHandler, EndpointPath}; use DAPPS_DOMAIN; -pub struct ProxyPac { - addr: SocketAddr, -} +pub struct ProxyPac; impl ProxyPac { - pub fn new(addr: &SocketAddr) -> Box { - Box::new(ProxyPac { - addr: addr.clone(), - }) + pub fn boxed() -> Box { + Box::new(ProxyPac) } } impl Endpoint for ProxyPac { - fn to_handler(&self, _prefix: &str, host: Option) -> Box { - let host = host.map_or_else(|| format!("{}", self.addr), |h| format!("{}:{}", h.host, h.port)); + fn to_handler(&self, path: EndpointPath) -> Box { let content = format!( r#" function FindProxyForURL(url, host) {{ if (shExpMatch(host, "*{0}")) {{ - return "PROXY {1}"; + return "PROXY {1}:{2}"; }} return "DIRECT"; }} "#, - DAPPS_DOMAIN, host); + DAPPS_DOMAIN, path.host, path.port); Box::new(ContentHandler::new(content, "application/javascript".to_owned())) } } diff --git a/webapp/src/router/mod.rs b/webapp/src/router/mod.rs index dc8abdadae3..11205068a19 100644 --- a/webapp/src/router/mod.rs +++ b/webapp/src/router/mod.rs @@ -28,11 +28,18 @@ use hyper; use hyper::{server, uri, header}; use hyper::{Next, Encoder, Decoder}; use hyper::net::HttpStream; -use endpoint::{Endpoint, Endpoints, HostInfo}; +use endpoint::{Endpoint, Endpoints, EndpointPath}; use self::url::Url; use self::auth::{Authorization, Authorized}; use self::redirect::Redirection; +#[derive(Debug, PartialEq)] +enum SpecialEndpoint { + Rpc, + Api, + None +} + pub struct Router { main_page: &'static str, endpoints: Arc, @@ -42,13 +49,6 @@ pub struct Router { handler: Box>, } -#[derive(Debug, PartialEq)] -struct AppId { - id: String, - prefix: String, - is_rpc: bool, -} - impl server::Handler for Router { fn on_request(&mut self, req: server::Request) -> Next { @@ -60,23 +60,20 @@ impl server::Handler for Router { Authorized::No(handler) => handler, Authorized::Yes => { let url = extract_url(&req); - let app_id = extract_app_id(&url); - let host = url.map(|u| HostInfo { - host: u.host, - port: u.port - }); + let endpoint = extract_endpoint(&url); - match app_id { + match endpoint { // First check RPC requests - Some(ref app_id) if app_id.is_rpc && *req.method() != hyper::method::Method::Get => { - self.rpc.to_handler("", host) + (ref path, SpecialEndpoint::Rpc) if *req.method() != hyper::method::Method::Get => { + self.rpc.to_handler(path.clone().unwrap_or_default()) }, - // Then delegate to dapp - Some(ref app_id) if self.endpoints.contains_key(&app_id.id) => { - self.endpoints.get(&app_id.id).unwrap().to_handler(&app_id.prefix, host) + // Check API requests + (ref path, SpecialEndpoint::Api) => { + self.api.to_handler(path.clone().unwrap_or_default()) }, - Some(ref app_id) if app_id.id == "api" => { - self.api.to_handler(&app_id.prefix, host) + // Then delegate to dapp + (Some(ref path), _) if self.endpoints.contains_key(&path.app_id) => { + self.endpoints.get(&path.app_id).unwrap().to_handler(path.clone()) }, // Redirection to main page _ if *req.method() == hyper::method::Method::Get => { @@ -84,7 +81,7 @@ impl server::Handler for Router { }, // RPC by default _ => { - self.rpc.to_handler("", host) + self.rpc.to_handler(EndpointPath::default()) } } } @@ -118,7 +115,7 @@ impl Router { api: Arc>, authorization: Arc) -> Self { - let handler = rpc.to_handler("", None); + let handler = rpc.to_handler(EndpointPath::default()); Router { main_page: main_page, endpoints: endpoints, @@ -156,9 +153,16 @@ fn extract_url(req: &server::Request) -> Option { } } -fn extract_app_id(url: &Option) -> Option { - fn is_rpc(url: &Url) -> bool { - url.path.len() > 1 && url.path[0] == "rpc" +fn extract_endpoint(url: &Option) -> (Option, SpecialEndpoint) { + fn special_endpoint(url: &Url) -> SpecialEndpoint { + if url.path.len() <= 1 { + return SpecialEndpoint::None; + } + match url.path[0].as_ref() { + "rpc" => SpecialEndpoint::Rpc, + "api" => SpecialEndpoint::Api, + _ => SpecialEndpoint::None, + } } match *url { @@ -167,64 +171,77 @@ fn extract_app_id(url: &Option) -> Option { let len = domain.len() - DAPPS_DOMAIN.len(); let id = domain[0..len].to_owned(); - Some(AppId { - id: id, - prefix: "".to_owned(), - is_rpc: is_rpc(url), - }) + (Some(EndpointPath { + app_id: id, + host: domain.clone(), + port: url.port, + }), special_endpoint(url)) }, _ if url.path.len() > 1 => { let id = url.path[0].clone(); - Some(AppId { - id: id.clone(), - prefix: "/".to_owned() + &id, - is_rpc: is_rpc(url), - }) + (Some(EndpointPath { + app_id: id.clone(), + host: format!("{}", url.host), + port: url.port, + }), special_endpoint(url)) }, - _ => None, + _ => (None, special_endpoint(url)), }, - _ => None + _ => (None, SpecialEndpoint::None) } } #[test] -fn should_extract_app_id() { - assert_eq!(extract_app_id(&None), None); +fn should_extract_endpoint() { + assert_eq!(extract_endpoint(&None), (None, SpecialEndpoint::None)); // With path prefix assert_eq!( - extract_app_id(&Url::parse("http://localhost:8080/status/index.html").ok()), - Some(AppId { - id: "status".to_owned(), - prefix: "/status".to_owned(), - is_rpc: false, - })); + extract_endpoint(&Url::parse("http://localhost:8080/status/index.html").ok()), + (Some(EndpointPath { + app_id: "status".to_owned(), + host: "localhost".to_owned(), + port: 8080, + }), SpecialEndpoint::None) + ); // With path prefix assert_eq!( - extract_app_id(&Url::parse("http://localhost:8080/rpc/").ok()), - Some(AppId { - id: "rpc".to_owned(), - prefix: "/rpc".to_owned(), - is_rpc: true, - })); + extract_endpoint(&Url::parse("http://localhost:8080/rpc/").ok()), + (Some(EndpointPath { + app_id: "rpc".to_owned(), + host: "localhost".to_owned(), + port: 8080, + }), SpecialEndpoint::Rpc) + ); // By Subdomain assert_eq!( - extract_app_id(&Url::parse("http://my.status.dapp/test.html").ok()), - Some(AppId { - id: "my.status".to_owned(), - prefix: "".to_owned(), - is_rpc: false, - })); + extract_endpoint(&Url::parse("http://my.status.dapp/test.html").ok()), + (Some(EndpointPath { + app_id: "my.status".to_owned(), + host: "my.status.dapp".to_owned(), + port: 80, + }), SpecialEndpoint::None) + ); // RPC by subdomain assert_eq!( - extract_app_id(&Url::parse("http://my.status.dapp/rpc/").ok()), - Some(AppId { - id: "my.status".to_owned(), - prefix: "".to_owned(), - is_rpc: true, - })); - + 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::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) + ); } diff --git a/webapp/src/rpc.rs b/webapp/src/rpc.rs index acd83aed5b7..7ba0b958478 100644 --- a/webapp/src/rpc.rs +++ b/webapp/src/rpc.rs @@ -15,11 +15,9 @@ // along with Parity. If not, see . use std::sync::{Arc, Mutex}; -use hyper::server; -use hyper::net::HttpStream; use jsonrpc_core::IoHandler; use jsonrpc_http_server::{ServerHandler, PanicHandler, AccessControlAllowOrigin}; -use endpoint::{Endpoint, HostInfo}; +use endpoint::{Endpoint, EndpointPath, Handler}; pub fn rpc(handler: Arc, panic_handler: Arc () + Send>>>>) -> Box { Box::new(RpcEndpoint { @@ -36,7 +34,7 @@ struct RpcEndpoint { } impl Endpoint for RpcEndpoint { - fn to_handler(&self, _prefix: &str, _host: Option) -> Box> { + fn to_handler(&self, _path: EndpointPath) -> Box { let panic_handler = PanicHandler { handler: self.panic_handler.clone() }; Box::new(ServerHandler::new(self.handler.clone(), self.cors_domain.clone(), panic_handler)) } From 237bd3703011bb01c882043a33078b6665d832ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 16 May 2016 13:01:56 +0200 Subject: [PATCH 4/4] Changing dapps domain to parity --- webapp/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/lib.rs b/webapp/src/lib.rs index 45157f07642..2c74dbdc39a 100644 --- a/webapp/src/lib.rs +++ b/webapp/src/lib.rs @@ -64,7 +64,7 @@ use std::net::SocketAddr; use jsonrpc_core::{IoHandler, IoDelegate}; use router::auth::{Authorization, NoAuth, HttpBasicAuth}; -static DAPPS_DOMAIN : &'static str = ".dapp"; +static DAPPS_DOMAIN : &'static str = ".parity"; /// Webapps HTTP+RPC server build. pub struct ServerBuilder {