Proxy.pac serving

This commit is contained in:
Tomasz Drwięga 2016-05-12 14:45:09 +02:00
parent 06aefb54bc
commit f62d058186
8 changed files with 167 additions and 79 deletions

View File

@ -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<Endpoints>,
@ -46,49 +42,8 @@ impl RestApi {
}
impl Endpoint for RestApi {
fn to_handler(&self, _prefix: &str) -> Box<server::Handler<HttpStream>> {
Box::new(RestApiHandler {
pages: self.list_pages(),
write_pos: 0,
})
fn to_handler(&self, _prefix: &str, _host: Option<HostInfo>) -> Box<Handler> {
Box::new(ContentHandler::new(self.list_pages(), "application/json".to_owned()))
}
}
struct RestApiHandler {
pages: String,
write_pos: usize,
}
impl server::Handler<HttpStream> for RestApiHandler {
fn on_request(&mut self, _request: server::Request) -> Next {
Next::write()
}
fn on_request_readable(&mut self, _decoder: &mut Decoder<HttpStream>) -> 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<HttpStream>) -> 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()
},
}
}
}

View File

@ -14,8 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
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) {}

View File

@ -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<server::Handler<HttpStream>>;
fn to_handler(&self, prefix: &str, host: Option<HostInfo>) -> Box<server::Handler<HttpStream>>;
}
pub type Endpoints = HashMap<String, Box<Endpoint>>;
pub type Handler = server::Handler<HttpStream>;
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<HttpStream> for ContentHandler {
fn on_request(&mut self, _request: server::Request) -> Next {
Next::write()
}
fn on_request_readable(&mut self, _decoder: &mut Decoder<HttpStream>) -> 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<HttpStream>) -> 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()
},
}
}
}

View File

@ -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<IoHandler>,
@ -103,7 +106,7 @@ pub struct Server {
impl Server {
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 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()));

View File

@ -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<T : WebApp + 'static> {
@ -38,7 +38,7 @@ impl<T: WebApp + 'static> PageEndpoint<T> {
}
impl<T: WebApp> Endpoint for PageEndpoint<T> {
fn to_handler(&self, prefix: &str) -> Box<server::Handler<HttpStream>> {
fn to_handler(&self, prefix: &str, _host: Option<HostInfo>) -> Box<server::Handler<HttpStream>> {
Box::new(PageHandler {
app: self.app.clone(),
prefix: prefix.to_owned(),

54
webapp/src/proxypac.rs Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
//! 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<Endpoint> {
Box::new(ProxyPac {
addr: addr.clone(),
})
}
}
impl Endpoint for ProxyPac {
fn to_handler(&self, _prefix: &str, host: Option<HostInfo>) -> Box<Handler> {
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()))
}
}

View File

@ -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<A: Authorization + 'static> {
impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
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<A: Authorization> Router<A> {
api: Arc<Box<Endpoint>>,
authorization: Arc<A>) -> Self {
let handler = rpc.to_handler(&"/");
let handler = rpc.to_handler("/", None);
Router {
main_page: main_page,
endpoints: endpoints,
@ -132,12 +139,14 @@ impl<A: Authorization> Router<A> {
}
}
fn extract_request_path(&self, req: &server::Request) -> Option<String> {
let url = self.extract_url(&req);
match url {
fn extract_app_id(&self, url: &Option<Url>) -> Option<AppId> {
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<A: Authorization> Router<A> {
}
}
}
struct AppId {
id: String,
prefix: String
}

View File

@ -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<IoHandler>, panic_handler: Arc<Mutex<Option<Box<Fn() -> () + Send>>>>) -> Box<Endpoint> {
Box::new(RpcEndpoint {
@ -36,7 +36,7 @@ struct RpcEndpoint {
}
impl Endpoint for RpcEndpoint {
fn to_handler(&self, _prefix: &str) -> Box<server::Handler<HttpStream>> {
fn to_handler(&self, _prefix: &str, _host: Option<HostInfo>) -> Box<server::Handler<HttpStream>> {
let panic_handler = PanicHandler { handler: self.panic_handler.clone() };
Box::new(ServerHandler::new(self.handler.clone(), self.cors_domain.clone(), panic_handler))
}