diff --git a/webapp/src/api.rs b/webapp/src/api.rs index bad49ec61..893e7258a 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 b0a4472f7..21e1102ad 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 dee2cadd8..533570635 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 30431578f..5ee93acc7 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 cd527578b..68d8a14bd 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 000000000..b8162fadf --- /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 15fc496f9..1d8a24585 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 51e171d8d..acd83aed5 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)) }