use cache::StoreCache;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
#[cfg(feature = "dir-plugin-backend")]
use tor_dircommon::dir_plugin_backend::DirBackendPlugin;
use tor_error::{internal, warn_report};
use std::{
collections::VecDeque,
convert::Infallible,
panic::{AssertUnwindSafe, catch_unwind},
str::FromStr,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use bytes::Bytes;
use futures::{Stream, StreamExt};
use http::{Method, Request, Response, StatusCode, header};
use http_body::{Body, Frame};
use hyper::{
body::Incoming,
server::conn::http1::{self},
service::service_fn,
};
use hyper_util::rt::TokioIo;
use rusqlite::{Transaction, params};
use tokio::{
io::{AsyncRead, AsyncWrite},
task::JoinSet,
time,
};
use tracing::warn;
#[cfg(feature = "dir-plugin-backend")]
use http_body_util::Full;
#[cfg(feature = "dir-plugin-backend")]
use std::io::Cursor;
use crate::database::{self, ContentEncoding, DocumentId, sql};
mod cache;
type EndpointFn = fn(
&Transaction,
&Request<Incoming>,
) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>>;
struct DocumentBody(VecDeque<Arc<[u8]>>);
type Endpoint = (Method, &'static str, EndpointFn);
#[derive(Debug)]
pub(crate) struct HttpServer {
endpoints: Vec<Endpoint>,
pool: Pool<SqliteConnectionManager>,
}
impl Body for DocumentBody {
type Data = Bytes;
type Error = Infallible;
fn poll_frame(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
Poll::Ready(
self.0
.pop_front()
.map(|bytes| Ok(Frame::data(Bytes::from_owner(bytes)))),
)
}
}
impl HttpServer {
pub(crate) fn new(endpoints: Vec<Endpoint>, pool: Pool<SqliteConnectionManager>) -> Self {
Self { endpoints, pool }
}
#[cfg(feature = "dir-plugin-backend")]
pub(crate) async fn serve_backend<I, S, E, B>(
mut listener: I,
backend: B,
) -> Result<(), tor_error::Bug>
where
I: Stream<Item = Result<S, E>> + Unpin,
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
E: std::error::Error + 'static,
B: DirBackendPlugin,
{
let failure = |code| -> _ {
Response::builder()
.status(code)
.body(Default::default())
.expect("response builder should not fail")
};
let backend = Arc::new(backend);
let mut tasks: JoinSet<Result<(), hyper::Error>> = JoinSet::new();
loop {
tokio::select! {
res = listener.next() => match res {
Some(Ok(s)) => {
let stream = TokioIo::new(s);
let backend = backend.clone();
let service = service_fn(move |requ: Request<Incoming>| {
let backend = backend.clone();
async move {
if requ.method() != Method::GET {
warn!("Unsupported method: {}", requ.method());
return Ok(failure(StatusCode::BAD_REQUEST));
}
if !requ.body().is_end_stream() {
warn!("HTTP GET with non-empty body?");
return Ok(failure(StatusCode::BAD_REQUEST));
}
let requ = requ.map(|_| ());
backend
.get(&requ)
.map(|resp| resp.map(|body| Full::new(Cursor::new(body))))
}
});
tasks.spawn(http1::Builder::new().serve_connection(stream, service));
},
Some(Err(e)) => {
warn_report!(e, "listener accept failure");
continue;
}
None => return Err(internal!("listener was closed externally?")),
},
Some(res) = tasks.join_next() => match res {
Ok(Ok(())) => {},
Ok(Err(e)) => warn_report!(e, "client task encountered an error"),
Err(e) => warn_report!(e, "client task exited ungracefully"),
},
}
}
}
pub(crate) async fn serve<I, S, E>(self, mut listener: I) -> Result<(), tor_error::Bug>
where
I: Stream<Item = Result<S, E>> + Unpin,
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
E: std::error::Error,
{
let cache = Arc::new(StoreCache::new());
let endpoints: Arc<[Endpoint]> = self.endpoints.into();
let pool = self.pool;
let mut hyper_tasks: JoinSet<Result<(), hyper::Error>> = JoinSet::new();
let mut misc_tasks: JoinSet<()> = JoinSet::new();
misc_tasks.spawn({
let cache = cache.clone();
async move {
loop {
cache.gc();
time::sleep(Duration::from_secs(60)).await;
}
}
});
loop {
tokio::select! {
res = listener.next() => match res {
Some(Ok(s)) => Self::dispatch_stream(&cache, &endpoints, &pool, &mut hyper_tasks, s),
Some(Err(e)) => {
warn!("listener accept failure: {e}");
continue;
}
None => return Err(internal!("listener was closed externally?")),
},
Some(res) = hyper_tasks.join_next() => match res {
Ok(Ok(())) => {},
Ok(Err(e)) => warn!("client task encountered an error: {e}"),
Err(e) => warn!("client task exited ungracefully: {e}"),
},
}
}
}
fn dispatch_stream<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
cache: &Arc<StoreCache>,
endpoints: &Arc<[Endpoint]>,
pool: &Pool<SqliteConnectionManager>,
tasks: &mut JoinSet<Result<(), hyper::Error>>,
stream: S,
) {
let stream = TokioIo::new(stream);
let cache = cache.clone();
let endpoints = endpoints.clone();
let pool = pool.clone();
let service = service_fn(move |requ| {
let cache = cache.clone();
let endpoints = endpoints.clone();
let pool = pool.clone();
async move { Self::handler(cache, endpoints, pool, requ).await }
});
tasks.spawn(http1::Builder::new().serve_connection(stream, service));
}
#[allow(clippy::unused_async)] async fn handler(
cache: Arc<StoreCache>,
endpoints: Arc<[Endpoint]>,
pool: Pool<SqliteConnectionManager>,
requ: Request<Incoming>,
) -> Result<Response<DocumentBody>, Infallible> {
Ok(
database::read_tx(&pool, |tx| Self::handler_tx(&cache, &endpoints, tx, &requ))
.unwrap_or_else(|e| {
warn!("database error: {e}");
Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR)
}),
)
}
fn handler_tx(
cache: &Arc<StoreCache>,
endpoints: &[Endpoint],
tx: &Transaction,
requ: &Request<Incoming>,
) -> Response<DocumentBody> {
let (encoding, advertise_encoding) = Self::determine_encoding(requ);
let endpoint_fn = match Self::match_endpoint(endpoints, requ) {
Some((_, _, endpoint_fn)) => endpoint_fn,
None => return Self::empty_response(StatusCode::NOT_FOUND),
};
let endpoint_fn_resp = match catch_unwind(AssertUnwindSafe(|| endpoint_fn(tx, requ))) {
Ok(Ok(r)) => r,
Ok(Err(e)) => {
warn!(
"{} {}: endpoint function failed: {e}",
requ.method(),
requ.uri()
);
return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
}
Err(_) => {
warn!(
"{} {}: endpoint function crashed",
requ.method(),
requ.uri()
);
return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
}
};
let (endpoint_fn_parts, docids) = endpoint_fn_resp.into_parts();
let docids = docids
.into_iter()
.map(|docid| Self::map_encoding(tx, docid, encoding))
.collect::<Result<Vec<_>, _>>();
let docids = match docids {
Ok(s) => s,
Err(e) => {
warn!(
"{} {}: unable to find compressed document: {e}",
requ.method(),
requ.uri()
);
return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
}
};
let mut documents = VecDeque::new();
for docid in docids {
let document = match cache.get(tx, docid) {
Ok(document) => document,
Err(e) => {
warn!(
"{} {}: unable to access the cache: {e}",
requ.method(),
requ.uri()
);
return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
}
};
documents.push_back(document);
}
let mut resp = Response::from_parts(endpoint_fn_parts, DocumentBody(documents));
if advertise_encoding {
resp.headers_mut().insert(
header::CONTENT_ENCODING,
encoding
.to_string()
.try_into()
.expect("strum serialized a non-valid header?!?"),
);
}
resp
}
fn determine_encoding<B: Body>(requ: &Request<B>) -> (ContentEncoding, bool) {
let z_suffix = requ.uri().path().ends_with(".z");
#[allow(clippy::collapsible_else_if)]
if let Some(accept_encoding) = requ.headers().get(header::ACCEPT_ENCODING) {
let encodings = accept_encoding
.to_str()
.unwrap_or("")
.split(",")
.filter_map(|encoding| ContentEncoding::from_str(encoding.trim()).ok())
.collect::<Vec<_>>();
if z_suffix {
(ContentEncoding::Deflate, true)
} else {
if let Some(encoding) = encodings.first() {
let include_in_header = *encoding != ContentEncoding::Identity;
(*encoding, include_in_header)
} else {
(ContentEncoding::Identity, false)
}
}
} else {
if z_suffix {
(ContentEncoding::Deflate, false)
} else {
(ContentEncoding::Identity, false)
}
}
}
fn match_endpoint<'a, B: Body>(
endpoints: &'a [Endpoint],
requ: &Request<B>,
) -> Option<&'a Endpoint> {
let requ_path = requ.uri().path();
let requ_path = requ_path.strip_suffix(".z").unwrap_or(requ_path);
let requ_path = requ_path.split('/').collect::<Vec<_>>();
let mut res = None;
for tuple in endpoints.iter() {
let (method, path, _endpoint_fn) = tuple;
let path = path.split('/').collect::<Vec<_>>();
if requ.method() != method {
continue;
}
if path.len() != requ_path.len() {
continue;
}
let mut is_match = true;
for (this, incoming) in path.iter().zip(&requ_path) {
if this == incoming || *this == "*" {
continue;
} else {
is_match = false;
break;
}
}
if is_match {
res = Some(tuple);
break;
}
}
res
}
fn map_encoding(
tx: &Transaction,
docid: DocumentId,
encoding: ContentEncoding,
) -> Result<DocumentId, rusqlite::Error> {
if encoding == ContentEncoding::Identity {
return Ok(docid);
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT compressed_docid
FROM compressed_document
WHERE identity_docid = ?1
AND algorithm = ?2
"
))?;
let compressed_docid =
stmt.query_one(params![docid, encoding.to_string()], |row| row.get(0))?;
Ok(compressed_docid)
}
fn empty_response(status: StatusCode) -> Response<DocumentBody> {
Response::builder()
.status(status)
.body(DocumentBody(VecDeque::new()))
.expect("response builder for empty response failed?!?")
}
}
#[cfg(test)]
pub(in crate::http) mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::string_slice)] use crate::database;
use super::*;
use std::{
io::{Cursor, Write},
str::FromStr,
};
use flate2::{
Compression,
write::{DeflateDecoder, DeflateEncoder, GzEncoder},
};
use http::Version;
use http_body_util::{BodyExt, Empty};
use lazy_static::lazy_static;
use tokio::{
net::{TcpListener, TcpStream},
task,
};
use tokio_stream::wrappers::TcpListenerStream;
pub(in crate::http) const IDENTITY: &str = "Lorem ipsum dolor sit amet.";
lazy_static! {
pub(in crate::http) static ref IDENTITY_DOCID: DocumentId =
hex_to_docid("DD14CBBF0E74909AAC7F248A85D190AFD8DA98265CEF95FC90DFDDABEA7C2E66");
pub(in crate::http) static ref DEFLATE_DOCID: DocumentId =
hex_to_docid("07564DD13A7F4A6AD98B997F2938B1CEE11F8C7F358C444374521BA54D50D05E");
pub(in crate::http) static ref GZIP_DOCID: DocumentId =
hex_to_docid("1518107D3EF1EC6EAC3F3249DF26B2F845BC8226C326309F4822CAEF2E664104");
pub(in crate::http) static ref XZ_STD_DOCID: DocumentId =
hex_to_docid("17416948501F8E627CC9A8F7EFE7A2F32788D53CB84A5F67AC8FD4C1B59184CF");
pub(in crate::http) static ref X_TOR_LZMA_DOCID: DocumentId =
hex_to_docid("B5549F79A69113BDAF3EF0AD1D7D339D0083BC31400ECEE1B673F331CF26E239");
}
pub(in crate::http) fn create_test_db_pool() -> Pool<SqliteConnectionManager> {
let pool = database::open("").unwrap();
database::rw_tx(&pool, init_test_db).unwrap();
pool
}
fn hex_to_docid(s: &str) -> DocumentId {
let data: [u8; 32] = hex::decode(s).unwrap().try_into().unwrap();
data.into()
}
fn init_test_db(tx: &Transaction) {
assert_eq!(DocumentId::digest(IDENTITY.as_bytes()), *IDENTITY_DOCID);
let deflate = {
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
encoder.write_all(IDENTITY.as_bytes()).unwrap();
encoder.finish().unwrap()
};
assert_eq!(DocumentId::digest(&deflate), *DEFLATE_DOCID);
let gzip = {
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
encoder.write_all(IDENTITY.as_bytes()).unwrap();
encoder.finish().unwrap()
};
assert_eq!(DocumentId::digest(&gzip), *GZIP_DOCID);
let xz_std = zstd::encode_all(IDENTITY.as_bytes(), 3).unwrap();
assert_eq!(DocumentId::digest(&xz_std), *XZ_STD_DOCID);
let mut x_tor_lzma = Vec::new();
lzma_rs::lzma_compress(&mut Cursor::new(IDENTITY), &mut x_tor_lzma).unwrap();
assert_eq!(DocumentId::digest(&x_tor_lzma), *X_TOR_LZMA_DOCID);
tx.execute(
sql!(
"
INSERT INTO store(docid, content) VALUES
(?1, ?2), -- identity
(?3, ?4), -- deflate
(?5, ?6), -- gzip
(?7, ?8), -- xzstd
(?9, ?10) -- lzma
"
),
params![
*IDENTITY_DOCID,
IDENTITY.as_bytes().to_vec(),
*DEFLATE_DOCID,
deflate,
*GZIP_DOCID,
gzip,
*XZ_STD_DOCID,
xz_std,
*X_TOR_LZMA_DOCID,
x_tor_lzma
],
)
.unwrap();
tx.execute(
sql!(
"
INSERT INTO compressed_document(algorithm, identity_docid, compressed_docid) VALUES
('deflate', ?1, ?2),
('gzip', ?1, ?3),
('x-zstd', ?1, ?4),
('x-tor-lzma', ?1, ?5)
"
),
params![
*IDENTITY_DOCID,
*DEFLATE_DOCID,
*GZIP_DOCID,
*XZ_STD_DOCID,
*X_TOR_LZMA_DOCID
],
)
.unwrap();
}
#[test]
fn content_encoding() {
assert_eq!(ContentEncoding::Identity.to_string(), "identity");
assert_eq!(
ContentEncoding::from_str("identity").unwrap(),
ContentEncoding::Identity
);
assert_eq!(ContentEncoding::Deflate.to_string(), "deflate");
assert_eq!(
ContentEncoding::from_str("DeFlaTe").unwrap(),
ContentEncoding::Deflate
);
assert_eq!(ContentEncoding::Gzip.to_string(), "gzip");
assert_eq!(
ContentEncoding::from_str("GzIP").unwrap(),
ContentEncoding::Gzip
);
assert_eq!(ContentEncoding::XZstd.to_string(), "x-zstd");
assert_eq!(
ContentEncoding::from_str("x-zStD").unwrap(),
ContentEncoding::XZstd
);
assert_eq!(ContentEncoding::XTorLzma.to_string(), "x-tor-lzma");
assert_eq!(
ContentEncoding::from_str("x-tOr-lzMa").unwrap(),
ContentEncoding::XTorLzma
);
}
#[test]
fn determine_encoding() {
let requ = Request::builder()
.header("Accept-Encoding", "deflate,identity , gzip")
.uri("/foo.z")
.body(String::new())
.unwrap();
assert_eq!(
HttpServer::determine_encoding(&requ),
(ContentEncoding::Deflate, true)
);
let requ = Request::builder()
.header("Accept-Encoding", " gzip ")
.uri("/foo")
.body(String::new())
.unwrap();
assert_eq!(
HttpServer::determine_encoding(&requ),
(ContentEncoding::Gzip, true)
);
let requ = Request::builder()
.header("Accept-Encoding", "identity")
.uri("/foo")
.body(String::new())
.unwrap();
assert_eq!(
HttpServer::determine_encoding(&requ),
(ContentEncoding::Identity, false)
);
let requ = Request::builder()
.header("Accept-Encoding", " unSuppOrtEd_EncODing_SCHEMA , yeah ")
.uri("/foo")
.body(String::new())
.unwrap();
assert_eq!(
HttpServer::determine_encoding(&requ),
(ContentEncoding::Identity, false)
);
let requ = Request::builder()
.uri("/foo.z")
.body(String::new())
.unwrap();
assert_eq!(
HttpServer::determine_encoding(&requ),
(ContentEncoding::Deflate, false)
);
let requ = Request::builder().uri("/foo").body(String::new()).unwrap();
assert_eq!(
HttpServer::determine_encoding(&requ),
(ContentEncoding::Identity, false)
);
}
#[test]
fn match_endpoint() {
fn dummy(
_: &Transaction,
_: &Request<Incoming>,
) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>> {
todo!()
}
let endpoints: Vec<Endpoint> = vec![
(Method::GET, "/foo/bar/baz", dummy),
(Method::GET, "/foo/*/baz", dummy),
(Method::GET, "/bar/*", dummy),
(Method::GET, "/", dummy),
];
macro_rules! check_match {
($uri:literal, $endpoint:literal) => {
let requ = Request::builder().uri($uri).body(String::new()).unwrap();
let left: *const Endpoint = HttpServer::match_endpoint(&endpoints, &requ).unwrap();
let right: *const Endpoint = &endpoints[$endpoint];
assert_eq!(left, right);
};
}
macro_rules! check_no_match {
($uri:literal) => {
let requ = Request::builder().uri($uri).body(String::new()).unwrap();
assert!(HttpServer::match_endpoint(&endpoints, &requ).is_none());
};
}
check_match!("/foo/bar/baz", 0);
check_match!("/foo/bar/baz.z", 0);
check_no_match!("/foo/bar/baz1");
check_no_match!("/foo/bar/baz/");
check_match!("/foo/I_DONT_CARE/baz", 1);
check_match!("/foo/I_DONT_CARE/baz.z", 1);
check_match!("/foo//baz", 1);
check_no_match!("/foo/");
check_no_match!("/foo/foo");
check_no_match!("/foo/foo/foo");
check_match!("/bar/", 2);
check_match!("/bar/.z", 2);
check_match!("/bar/foo", 2);
check_match!("/bar/foo.z", 2);
check_no_match!("/bar/foo/");
check_no_match!("/bar/foo/foo");
check_match!("/", 3);
check_match!("/.z", 3);
}
#[test]
fn map_encoding() {
let pool = create_test_db_pool();
let data = [
(ContentEncoding::Identity, *IDENTITY_DOCID),
(ContentEncoding::Deflate, *DEFLATE_DOCID),
(ContentEncoding::Gzip, *GZIP_DOCID),
(ContentEncoding::XZstd, *XZ_STD_DOCID),
(ContentEncoding::XTorLzma, *X_TOR_LZMA_DOCID),
];
database::read_tx(&pool, |tx| {
for (encoding, compressed_docid) in data {
println!("{encoding}");
assert_eq!(
HttpServer::map_encoding(tx, *IDENTITY_DOCID, encoding).unwrap(),
compressed_docid
);
}
})
.unwrap();
}
#[tokio::test]
async fn basic_http_server() {
#[allow(clippy::unnecessary_wraps)]
fn identity(
_tx: &Transaction<'_>,
_requ: &Request<Incoming>,
) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>> {
Ok(Response::new(vec![*IDENTITY_DOCID]))
}
let pool = create_test_db_pool();
let server = HttpServer::new(
vec![(Method::GET, "/tor/status-vote/current/consensus", identity)],
pool,
);
let listener = TcpListener::bind("[::1]:0").await.unwrap();
let local_addr = listener.local_addr().unwrap();
let listener = TcpListenerStream::new(listener);
task::spawn(async move {
server.serve(listener).await.unwrap();
});
let stream = TcpStream::connect(local_addr).await.unwrap();
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
.await
.unwrap();
task::spawn(async move {
if let Err(e) = conn.await {
println!("Connection failed: {e:?}");
}
});
let requ = Request::builder()
.version(Version::HTTP_11)
.uri("/tor/status-vote/current/consensus")
.body(Empty::<Bytes>::new())
.unwrap();
let mut resp = sender.send_request(requ).await.unwrap();
let mut resp_body: Vec<u8> = Vec::new();
while let Some(next) = resp.frame().await {
resp_body.append(&mut next.unwrap().data_ref().unwrap().as_ref().to_vec());
}
assert_eq!(IDENTITY, String::from_utf8_lossy(&resp_body));
let requ = Request::builder()
.version(Version::HTTP_11)
.uri("/tor/status-vote/current/consensus.z")
.body(Empty::<Bytes>::new())
.unwrap();
let mut resp = sender.send_request(requ).await.unwrap();
let mut resp_body: Vec<u8> = Vec::new();
while let Some(next) = resp.frame().await {
resp_body.append(&mut next.unwrap().data_ref().unwrap().as_ref().to_vec());
}
let mut decoder = DeflateDecoder::new(Vec::new());
decoder.write_all(&resp_body).unwrap();
let decoded_resp = decoder.finish().unwrap();
assert_eq!(IDENTITY, String::from_utf8_lossy(&decoded_resp));
}
}