client/rpc/
http_common.rs

1#![allow(dead_code)]
2// Copyright 2015-2019 Parity Technologies (UK) Ltd.
3// This file is part of Parity Ethereum.
4
5// Parity Ethereum is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// Parity Ethereum is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with Parity Ethereum.  If not, see <http://www.gnu.org/licenses/>.
17
18//! Transport-specific metadata extractors.
19
20use jsonrpc_core;
21use jsonrpc_http_server::{self as http, hyper};
22
23/// HTTP RPC server impl-independent metadata extractor
24pub trait HttpMetaExtractor: Send + Sync + 'static {
25    /// Type of Metadata
26    type Metadata: jsonrpc_core::Metadata;
27    /// Extracts metadata from given params.
28    fn read_metadata(
29        &self, origin: Option<String>, user_agent: Option<String>,
30    ) -> Self::Metadata;
31}
32
33pub struct MetaExtractor<T> {
34    extractor: T,
35}
36
37impl<T> MetaExtractor<T> {
38    pub fn new(extractor: T) -> Self { MetaExtractor { extractor } }
39}
40
41impl<M, T> http::MetaExtractor<M> for MetaExtractor<T>
42where
43    T: HttpMetaExtractor<Metadata = M>,
44    M: jsonrpc_core::Metadata,
45{
46    fn read_metadata(&self, req: &hyper::Request<hyper::Body>) -> M {
47        let as_string = |header: Option<&hyper::header::HeaderValue>| {
48            header.and_then(|val| val.to_str().ok().map(ToOwned::to_owned))
49        };
50
51        let origin = as_string(req.headers().get("origin"));
52        let user_agent = as_string(req.headers().get("user-agent"));
53        self.extractor.read_metadata(origin, user_agent)
54    }
55}