use std::time::Duration;
use bytes::Bytes;
use futures::future::Either;
use futures::FutureExt;
use rings_runtime::sleep;
use serde::Deserialize;
use super::decode_outcome;
use super::default_method;
use super::encode_request;
use super::normalize_method;
use super::normalize_path;
use super::OnionHttpsOutcome;
use super::OnionHttpsRequest;
use super::OnionHttpsResponse;
use crate::error::Error;
use crate::error::Result;
use crate::onion::proxy::OnionProxyRoute;
use crate::onion::proxy::OnionProxyTarget;
use crate::onion::runtime::OnionRuntime;
use crate::onion::session::client::OnionCreditWindow;
use crate::onion::session::dial::OnionSessionRequest;
use crate::onion::session::dial::OnionStreamEvent;
use crate::onion::sphinx::class::OnionLoopClass;
use crate::onion::OnionRouteError;
use crate::onion::OnionServiceName;
pub(crate) const ONION_HTTPS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_HTTPS_OUTCOME_BYTES: usize = 9 * 1024 * 1024;
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct OnionHttpsClientRequest {
#[serde(default = "default_method")]
pub method: String,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub headers: Vec<(String, String)>,
#[serde(default, deserialize_with = "deserialize_request_body")]
pub body: Vec<u8>,
#[serde(default)]
pub class: Option<OnionLoopClass>,
}
fn deserialize_request_body<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
where D: serde::Deserializer<'de> {
struct RequestBodyVisitor;
impl<'de> serde::de::Visitor<'de> for RequestBodyVisitor {
type Value = Vec<u8>;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a byte buffer or byte array")
}
fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E> {
Ok(v.to_vec())
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> std::result::Result<Self::Value, E> {
Ok(v)
}
fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
where A: serde::de::SeqAccess<'de> {
let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(4096));
while let Some(byte) = seq.next_element::<u8>()? {
bytes.push(byte);
}
Ok(bytes)
}
}
deserializer.deserialize_bytes(RequestBodyVisitor)
}
#[derive(Debug)]
pub struct OnionHttpsCall {
method: String,
path: String,
headers: Vec<(String, String)>,
body: Vec<u8>,
class: OnionLoopClass,
}
impl OnionHttpsCall {
pub fn from_url(
url: &str,
request: OnionHttpsClientRequest,
) -> Result<(OnionProxyTarget, Self)> {
let (target, path) = parse_https_url(url)?;
Ok((target, Self::with_default_path(request, path)?))
}
pub const fn with_class(mut self, class: OnionLoopClass) -> Self {
self.class = class;
self
}
pub const fn class(&self) -> OnionLoopClass {
self.class
}
pub(super) fn with_default_path(
request: OnionHttpsClientRequest,
default_path: &str,
) -> Result<Self> {
Ok(Self {
method: normalize_method(&request.method),
path: normalize_path(request.path.as_deref().unwrap_or(default_path))?,
headers: request.headers,
body: request.body,
class: request.class.unwrap_or(OnionLoopClass::DEFAULT),
})
}
pub(super) fn into_request(self) -> OnionHttpsRequest {
OnionHttpsRequest {
method: self.method,
path: self.path,
headers: self.headers,
body: self.body,
}
}
}
#[derive(Clone)]
pub(crate) struct OnionHttpsClient {
runtime: OnionRuntime,
}
impl OnionHttpsClient {
pub(crate) const fn new(runtime: OnionRuntime) -> Self {
Self { runtime }
}
pub(crate) async fn request(
&self,
route: &OnionProxyRoute,
call: OnionHttpsCall,
) -> Result<OnionHttpsResponse> {
let class = call.class();
self.request_with_class(route, call, class).await
}
pub(crate) async fn request_with_class(
&self,
route: &OnionProxyRoute,
call: OnionHttpsCall,
class: OnionLoopClass,
) -> Result<OnionHttpsResponse> {
let request = encode_request(&call.into_request())?;
let (mut sender, mut receiver) = self
.runtime
.open(OnionSessionRequest {
route: route.route.clone(),
symbol: OnionServiceName::https(),
target: route.target.clone(),
class,
window: OnionCreditWindow::DEFAULT,
})
.await?
.split();
sender.send(Bytes::from(request)).await?;
sender.fin().await?;
let collect = async {
let mut outcome = Vec::new();
loop {
match receiver.next().await {
Some(OnionStreamEvent::Data(bytes)) => {
if outcome.len().saturating_add(bytes.len()) > MAX_HTTPS_OUTCOME_BYTES {
return Err(Error::NoPermission);
}
outcome.extend_from_slice(&bytes);
}
Some(OnionStreamEvent::Fin) => return client_outcome(&outcome),
Some(OnionStreamEvent::Failed) | None => {
return Err(Error::OnionRouteError(OnionRouteError::HttpsResponseClosed))
}
}
}
};
let deadline = sleep(ONION_HTTPS_RESPONSE_TIMEOUT).fuse();
futures::pin_mut!(collect, deadline);
match futures::future::select(collect, deadline).await {
Either::Left((outcome, _)) => outcome,
Either::Right(_) => Err(Error::OnionProxyRequestTimedOut),
}
}
}
fn client_outcome(bytes: &[u8]) -> Result<OnionHttpsResponse> {
match decode_outcome(bytes)? {
OnionHttpsOutcome::Response(response) => Ok(response),
OnionHttpsOutcome::Error(failure) => Err(Error::OnionRouteError(
OnionRouteError::ExitFailure(failure),
)),
}
}
fn parse_https_url(url: &str) -> Result<(OnionProxyTarget, &str)> {
let url = url.trim();
let (scheme, rest) = url.split_once("://").ok_or_else(|| {
Error::HttpRequestError("HTTPS onion proxy request URL must be absolute".to_string())
})?;
if !scheme.eq_ignore_ascii_case("https") {
return Err(Error::HttpRequestError(format!(
"HTTPS onion proxy only supports https URLs, got scheme {scheme:?}"
)));
}
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let (authority, suffix) = rest.split_at(authority_end);
if authority.contains('@') {
return Err(Error::HttpRequestError(
"HTTPS onion proxy URLs must not contain userinfo".to_string(),
));
}
let authority = https_authority_with_default_port(authority)?;
let target = OnionProxyTarget::parse_authority(authority.as_str())?;
Ok((target, url_path(suffix)))
}
fn https_authority_with_default_port(authority: &str) -> Result<String> {
let authority = authority.trim();
if authority.is_empty() {
return Err(Error::HttpRequestError(
"HTTPS onion proxy URL host must not be empty".to_string(),
));
}
if let Some(rest) = authority.strip_prefix('[') {
let Some((host, suffix)) = rest.split_once(']') else {
return Err(Error::HttpRequestError(format!(
"invalid IPv6 HTTPS onion proxy authority {authority:?}"
)));
};
if host.is_empty() {
return Err(Error::HttpRequestError(
"HTTPS onion proxy URL host must not be empty".to_string(),
));
}
return if suffix.is_empty() {
Ok(format!("[{host}]:443"))
} else if let Some(port) = suffix.strip_prefix(':') {
if port.is_empty() {
Err(Error::HttpRequestError(format!(
"HTTPS onion proxy authority {authority:?} has an empty port"
)))
} else {
Ok(authority.to_string())
}
} else {
Err(Error::HttpRequestError(format!(
"invalid IPv6 HTTPS onion proxy authority {authority:?}"
)))
};
}
if authority.contains('[') || authority.contains(']') {
return Err(Error::HttpRequestError(format!(
"invalid HTTPS onion proxy authority {authority:?}"
)));
}
let colon_count = authority.chars().filter(|ch| *ch == ':').count();
if colon_count > 1 {
return Err(Error::HttpRequestError(
"IPv6 HTTPS onion proxy URLs must use bracketed hosts".to_string(),
));
}
if colon_count == 1 {
let Some((host, port)) = authority.rsplit_once(':') else {
return Err(Error::HttpRequestError(format!(
"invalid HTTPS onion proxy authority {authority:?}"
)));
};
if host.is_empty() || port.is_empty() {
return Err(Error::HttpRequestError(format!(
"invalid HTTPS onion proxy authority {authority:?}"
)));
}
Ok(authority.to_string())
} else {
Ok(format!("{authority}:443"))
}
}
fn url_path(suffix: &str) -> &str {
suffix
.split_once('#')
.map_or(suffix, |(before_fragment, _)| before_fragment)
}