openethereum/signer/src/ws_server/mod.rs

184 lines
5.3 KiB
Rust
Raw Normal View History

2016-05-27 13:03:00 +02:00
// 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/>.
//! `WebSockets` server.
use ws;
use std;
use std::thread;
use std::path::PathBuf;
2016-05-27 17:46:15 +02:00
use std::default::Default;
2016-05-27 13:03:00 +02:00
use std::ops::Drop;
use std::sync::Arc;
use std::net::SocketAddr;
use io::{PanicHandler, OnPanicListener, MayPanic};
2016-05-27 17:46:15 +02:00
use jsonrpc_core::{IoHandler, IoDelegate};
use rpc::{Extendable, ConfirmationsQueue};
2016-05-27 17:46:15 +02:00
mod session;
2016-05-27 13:03:00 +02:00
/// Signer startup error
#[derive(Debug)]
pub enum ServerError {
/// Wrapped `std::io::Error`
IoError(std::io::Error),
/// Other `ws-rs` error
2016-05-27 15:46:07 +02:00
WebSocket(ws::Error)
2016-05-27 13:03:00 +02:00
}
impl From<ws::Error> for ServerError {
fn from(err: ws::Error) -> Self {
match err.kind {
ws::ErrorKind::Io(e) => ServerError::IoError(e),
2016-05-27 15:46:07 +02:00
_ => ServerError::WebSocket(err),
2016-05-27 13:03:00 +02:00
}
}
}
2016-05-27 17:46:15 +02:00
/// Builder for `WebSockets` server
pub struct ServerBuilder {
queue: Arc<ConfirmationsQueue>,
2016-05-27 17:46:15 +02:00
handler: Arc<IoHandler>,
authcodes_path: PathBuf,
skip_origin_validation: bool,
2016-05-27 17:46:15 +02:00
}
impl Extendable for ServerBuilder {
fn add_delegate<D: Send + Sync + 'static>(&self, delegate: IoDelegate<D>) {
self.handler.add_delegate(delegate);
}
}
2016-05-27 17:46:15 +02:00
impl ServerBuilder {
/// Creates new `ServerBuilder`
pub fn new(queue: Arc<ConfirmationsQueue>, authcodes_path: PathBuf) -> Self {
2016-05-27 17:46:15 +02:00
ServerBuilder {
queue: queue,
handler: Arc::new(IoHandler::new()),
authcodes_path: authcodes_path,
skip_origin_validation: false,
2016-05-27 17:46:15 +02:00
}
}
/// If set to `true` server will not verify Origin of incoming requests.
/// Not recommended. Use only for development.
pub fn skip_origin_validation(mut self, skip: bool) -> Self {
self.skip_origin_validation = skip;
self
}
2016-05-27 17:46:15 +02:00
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
pub fn start(self, addr: SocketAddr) -> Result<Server, ServerError> {
Server::start(addr, self.handler, self.queue, self.authcodes_path, self.skip_origin_validation)
2016-05-27 17:46:15 +02:00
}
}
2016-05-27 13:03:00 +02:00
/// `WebSockets` server implementation.
pub struct Server {
2016-05-27 17:46:15 +02:00
handle: Option<thread::JoinHandle<ws::WebSocket<session::Factory>>>,
2016-05-30 20:23:19 +02:00
broadcaster_handle: Option<thread::JoinHandle<()>>,
queue: Arc<ConfirmationsQueue>,
2016-05-27 13:03:00 +02:00
panic_handler: Arc<PanicHandler>,
}
impl Server {
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
fn start(addr: SocketAddr, handler: Arc<IoHandler>, queue: Arc<ConfirmationsQueue>, authcodes_path: PathBuf, skip_origin_validation: bool) -> Result<Server, ServerError> {
2016-05-27 13:03:00 +02:00
let config = {
let mut config = ws::Settings::default();
// accept only handshakes beginning with GET
2016-05-27 13:03:00 +02:00
config.method_strict = true;
Bumping topbar. Fixing ws server closing when suspending (#1312) * More meaningful errors when sending transaction * Fixing returned value * Consolidating all RPC error codes * Fixed loosing peers on incoming connections. (#1293) * Deactivate peer if it has no new data * Fixed node table timer registration * Fixed handshake timeout expiration * Extra trace * Fixed session count calculation * Only deactivate incapable peers in ChainHead state * Timer registration is not needed * x64 path * firewall rules * Fix read-ahead bug. Re-ahead 8 bytes rather than 3 to ensure large blocks import fine. * Refactor to use a const. * Update README.md * Gas price statistics. (#1291) * Gas price statistics. Affects eth_gasPrice. Added ethcore_gasPriceStatistics. Closes #1265 * Fix a bug in eth_gasPrice * Fix tests. * Revert minor alteration. * Tests for gas_price_statistics. - Tests; - Additional infrastructure for generating test blocks with transactions. * Key load avoid warning (#1303) * avoid warning with key * fix intendations * more intendation fix * ok() instead of expect() * Appveyor config for windows build+installer (#1302) * appveyor * proper dist name * quote * win-build config * proper build section * tests in release * plugin dir * cache binaries * quotes * escaped quotes * forces user dir * fixes * syntax * proper cahce dir * quotes? * root nsis instead of bin * submodules init * artifact path fix * no submodule * raw link here * another way to force cargo cache * include vc++ 2015 redist * fix name of the dist * ETHCORE -> Ethcore * Bumping topbar. Fixing ws server closing when suspending
2016-06-18 15:10:36 +02:00
// Was shutting down server when suspending on linux:
config.shutdown_on_interrupt = false;
2016-05-27 13:03:00 +02:00
config
};
// Create WebSocket
let origin = format!("{}", addr);
let ws = try!(ws::Builder::new().with_settings(config).build(
session::Factory::new(handler, origin, authcodes_path, skip_origin_validation)
));
2016-05-27 13:03:00 +02:00
let panic_handler = PanicHandler::new_in_arc();
let ph = panic_handler.clone();
let broadcaster = ws.broadcaster();
2016-05-30 20:23:19 +02:00
2016-05-27 13:03:00 +02:00
// Spawn a thread with event loop
let handle = thread::spawn(move || {
ph.catch_panic(move || {
match ws.listen(addr).map_err(ServerError::from) {
Err(ServerError::IoError(io)) => die(format!(
"Signer: Could not start listening on specified address. Make sure that no other instance is running on Signer's port. Details: {:?}",
io
)),
Err(any_error) => die(format!(
2016-07-19 20:42:23 +02:00
"Signer: Unknown error occurred when starting Signer. Details: {:?}",
any_error
)),
Ok(server) => server,
}
2016-05-27 13:03:00 +02:00
}).unwrap()
});
2016-05-30 20:23:19 +02:00
// Spawn a thread for broadcasting
let ph = panic_handler.clone();
let q = queue.clone();
let broadcaster_handle = thread::spawn(move || {
ph.catch_panic(move || {
q.start_listening(|_message| {
// TODO [ToDr] Some better structure here for messages.
broadcaster.send("new_message").unwrap();
2016-05-30 20:39:20 +02:00
}).expect("It's the only place we are running start_listening. It shouldn't fail.");
let res = broadcaster.shutdown();
if let Err(e) = res {
warn!("Signer: Broadcaster was not closed cleanly. Details: {:?}", e);
}
2016-05-30 20:23:19 +02:00
}).unwrap()
});
2016-05-27 13:03:00 +02:00
// Return a handle
2016-05-30 20:23:19 +02:00
Ok(Server {
2016-05-27 13:03:00 +02:00
handle: Some(handle),
2016-05-30 20:23:19 +02:00
broadcaster_handle: Some(broadcaster_handle),
queue: queue,
2016-05-27 13:03:00 +02:00
panic_handler: panic_handler,
2016-05-30 20:23:19 +02:00
})
2016-05-27 13:03:00 +02:00
}
}
impl MayPanic for Server {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
impl Drop for Server {
fn drop(&mut self) {
2016-05-30 20:23:19 +02:00
self.queue.finish();
self.broadcaster_handle.take().unwrap().join().unwrap();
2016-05-27 13:03:00 +02:00
self.handle.take().unwrap().join().unwrap();
2016-05-27 13:03:00 +02:00
}
}
fn die(msg: String) -> ! {
println!("ERROR: {}", msg);
std::process::exit(1);
}