rings_node/onion/https/
client.rs1use std::time::Duration;
24
25use bytes::Bytes;
26use futures::future::Either;
27use futures::FutureExt;
28use rings_runtime::sleep;
29use serde::Deserialize;
30
31use super::decode_outcome;
32use super::default_method;
33use super::encode_request;
34use super::normalize_method;
35use super::normalize_path;
36use super::OnionHttpsOutcome;
37use super::OnionHttpsRequest;
38use super::OnionHttpsResponse;
39use crate::error::Error;
40use crate::error::Result;
41use crate::onion::proxy::OnionProxyRoute;
42use crate::onion::proxy::OnionProxyTarget;
43use crate::onion::runtime::OnionRuntime;
44use crate::onion::session::client::OnionCreditWindow;
45use crate::onion::session::dial::OnionSessionRequest;
46use crate::onion::session::dial::OnionStreamEvent;
47use crate::onion::sphinx::class::OnionLoopClass;
48use crate::onion::OnionRouteError;
49use crate::onion::OnionServiceName;
50
51pub(crate) const ONION_HTTPS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(30);
53
54const MAX_HTTPS_OUTCOME_BYTES: usize = 9 * 1024 * 1024;
56
57#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
59pub struct OnionHttpsClientRequest {
60 #[serde(default = "default_method")]
62 pub method: String,
63 #[serde(default)]
65 pub path: Option<String>,
66 #[serde(default)]
68 pub headers: Vec<(String, String)>,
69 #[serde(default, deserialize_with = "deserialize_request_body")]
71 pub body: Vec<u8>,
72 #[serde(default)]
78 pub class: Option<OnionLoopClass>,
79}
80
81fn deserialize_request_body<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
84where D: serde::Deserializer<'de> {
85 struct RequestBodyVisitor;
86
87 impl<'de> serde::de::Visitor<'de> for RequestBodyVisitor {
88 type Value = Vec<u8>;
89
90 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.write_str("a byte buffer or byte array")
92 }
93
94 fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E> {
95 Ok(v.to_vec())
96 }
97
98 fn visit_byte_buf<E>(self, v: Vec<u8>) -> std::result::Result<Self::Value, E> {
99 Ok(v)
100 }
101
102 fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
103 where A: serde::de::SeqAccess<'de> {
104 let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(4096));
105 while let Some(byte) = seq.next_element::<u8>()? {
106 bytes.push(byte);
107 }
108 Ok(bytes)
109 }
110 }
111
112 deserializer.deserialize_bytes(RequestBodyVisitor)
113}
114
115#[derive(Debug)]
121pub struct OnionHttpsCall {
122 method: String,
123 path: String,
124 headers: Vec<(String, String)>,
125 body: Vec<u8>,
126 class: OnionLoopClass,
127}
128
129impl OnionHttpsCall {
130 pub fn from_url(
135 url: &str,
136 request: OnionHttpsClientRequest,
137 ) -> Result<(OnionProxyTarget, Self)> {
138 let (target, path) = parse_https_url(url)?;
139 Ok((target, Self::with_default_path(request, path)?))
140 }
141
142 pub const fn with_class(mut self, class: OnionLoopClass) -> Self {
147 self.class = class;
148 self
149 }
150
151 pub const fn class(&self) -> OnionLoopClass {
153 self.class
154 }
155
156 pub(super) fn with_default_path(
158 request: OnionHttpsClientRequest,
159 default_path: &str,
160 ) -> Result<Self> {
161 Ok(Self {
162 method: normalize_method(&request.method),
163 path: normalize_path(request.path.as_deref().unwrap_or(default_path))?,
164 headers: request.headers,
165 body: request.body,
166 class: request.class.unwrap_or(OnionLoopClass::DEFAULT),
167 })
168 }
169
170 pub(super) fn into_request(self) -> OnionHttpsRequest {
173 OnionHttpsRequest {
174 method: self.method,
175 path: self.path,
176 headers: self.headers,
177 body: self.body,
178 }
179 }
180}
181
182#[derive(Clone)]
184pub(crate) struct OnionHttpsClient {
185 runtime: OnionRuntime,
187}
188
189impl OnionHttpsClient {
190 pub(crate) const fn new(runtime: OnionRuntime) -> Self {
192 Self { runtime }
193 }
194
195 pub(crate) async fn request(
205 &self,
206 route: &OnionProxyRoute,
207 call: OnionHttpsCall,
208 ) -> Result<OnionHttpsResponse> {
209 let class = call.class();
210 self.request_with_class(route, call, class).await
211 }
212
213 pub(crate) async fn request_with_class(
225 &self,
226 route: &OnionProxyRoute,
227 call: OnionHttpsCall,
228 class: OnionLoopClass,
229 ) -> Result<OnionHttpsResponse> {
230 let request = encode_request(&call.into_request())?;
231 let (mut sender, mut receiver) = self
232 .runtime
233 .open(OnionSessionRequest {
234 route: route.route.clone(),
235 symbol: OnionServiceName::https(),
236 target: route.target.clone(),
237 class,
238 window: OnionCreditWindow::DEFAULT,
239 })
240 .await?
241 .split();
242 sender.send(Bytes::from(request)).await?;
243 sender.fin().await?;
244 let collect = async {
245 let mut outcome = Vec::new();
246 loop {
247 match receiver.next().await {
248 Some(OnionStreamEvent::Data(bytes)) => {
249 if outcome.len().saturating_add(bytes.len()) > MAX_HTTPS_OUTCOME_BYTES {
250 return Err(Error::NoPermission);
251 }
252 outcome.extend_from_slice(&bytes);
253 }
254 Some(OnionStreamEvent::Fin) => return client_outcome(&outcome),
255 Some(OnionStreamEvent::Failed) | None => {
256 return Err(Error::OnionRouteError(OnionRouteError::HttpsResponseClosed))
257 }
258 }
259 }
260 };
261 let deadline = sleep(ONION_HTTPS_RESPONSE_TIMEOUT).fuse();
262 futures::pin_mut!(collect, deadline);
263 match futures::future::select(collect, deadline).await {
264 Either::Left((outcome, _)) => outcome,
265 Either::Right(_) => Err(Error::OnionProxyRequestTimedOut),
266 }
267 }
268}
269
270fn client_outcome(bytes: &[u8]) -> Result<OnionHttpsResponse> {
272 match decode_outcome(bytes)? {
273 OnionHttpsOutcome::Response(response) => Ok(response),
274 OnionHttpsOutcome::Error(failure) => Err(Error::OnionRouteError(
275 OnionRouteError::ExitFailure(failure),
276 )),
277 }
278}
279
280fn parse_https_url(url: &str) -> Result<(OnionProxyTarget, &str)> {
282 let url = url.trim();
283 let (scheme, rest) = url.split_once("://").ok_or_else(|| {
284 Error::HttpRequestError("HTTPS onion proxy request URL must be absolute".to_string())
285 })?;
286 if !scheme.eq_ignore_ascii_case("https") {
287 return Err(Error::HttpRequestError(format!(
288 "HTTPS onion proxy only supports https URLs, got scheme {scheme:?}"
289 )));
290 }
291 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
292 let (authority, suffix) = rest.split_at(authority_end);
293 if authority.contains('@') {
294 return Err(Error::HttpRequestError(
295 "HTTPS onion proxy URLs must not contain userinfo".to_string(),
296 ));
297 }
298 let authority = https_authority_with_default_port(authority)?;
299 let target = OnionProxyTarget::parse_authority(authority.as_str())?;
300 Ok((target, url_path(suffix)))
301}
302
303fn https_authority_with_default_port(authority: &str) -> Result<String> {
305 let authority = authority.trim();
306 if authority.is_empty() {
307 return Err(Error::HttpRequestError(
308 "HTTPS onion proxy URL host must not be empty".to_string(),
309 ));
310 }
311
312 if let Some(rest) = authority.strip_prefix('[') {
313 let Some((host, suffix)) = rest.split_once(']') else {
314 return Err(Error::HttpRequestError(format!(
315 "invalid IPv6 HTTPS onion proxy authority {authority:?}"
316 )));
317 };
318 if host.is_empty() {
319 return Err(Error::HttpRequestError(
320 "HTTPS onion proxy URL host must not be empty".to_string(),
321 ));
322 }
323 return if suffix.is_empty() {
324 Ok(format!("[{host}]:443"))
325 } else if let Some(port) = suffix.strip_prefix(':') {
326 if port.is_empty() {
327 Err(Error::HttpRequestError(format!(
328 "HTTPS onion proxy authority {authority:?} has an empty port"
329 )))
330 } else {
331 Ok(authority.to_string())
332 }
333 } else {
334 Err(Error::HttpRequestError(format!(
335 "invalid IPv6 HTTPS onion proxy authority {authority:?}"
336 )))
337 };
338 }
339
340 if authority.contains('[') || authority.contains(']') {
341 return Err(Error::HttpRequestError(format!(
342 "invalid HTTPS onion proxy authority {authority:?}"
343 )));
344 }
345 let colon_count = authority.chars().filter(|ch| *ch == ':').count();
346 if colon_count > 1 {
347 return Err(Error::HttpRequestError(
348 "IPv6 HTTPS onion proxy URLs must use bracketed hosts".to_string(),
349 ));
350 }
351 if colon_count == 1 {
352 let Some((host, port)) = authority.rsplit_once(':') else {
353 return Err(Error::HttpRequestError(format!(
354 "invalid HTTPS onion proxy authority {authority:?}"
355 )));
356 };
357 if host.is_empty() || port.is_empty() {
358 return Err(Error::HttpRequestError(format!(
359 "invalid HTTPS onion proxy authority {authority:?}"
360 )));
361 }
362 Ok(authority.to_string())
363 } else {
364 Ok(format!("{authority}:443"))
365 }
366}
367
368fn url_path(suffix: &str) -> &str {
371 suffix
372 .split_once('#')
373 .map_or(suffix, |(before_fragment, _)| before_fragment)
374}