rings_node/onion/proxy/http/
mod.rs1use std::net::SocketAddr;
4use std::sync::Arc;
5use std::time::Duration;
6
7use tokio::io::AsyncReadExt;
8use tokio::io::AsyncWriteExt;
9use tokio::net::TcpListener;
10use tokio::net::TcpStream;
11use tokio::sync::Semaphore;
12use tokio::time::timeout;
13
14use super::OnionProxyTarget;
15use crate::error::Error;
16use crate::error::Result;
17use crate::onion::native::NativeOnionCircuitHandle;
18use crate::processor::Processor;
19
20const MAX_CONNECT_HEADER_BYTES: usize = 8192;
21pub const DEFAULT_CONNECT_HEADER_TIMEOUT_SECS: u64 = 10;
23pub const DEFAULT_MAX_CONNECT_CONNECTIONS: usize = 1024;
25
26pub const fn default_connect_header_timeout_secs() -> u64 {
28 DEFAULT_CONNECT_HEADER_TIMEOUT_SECS
29}
30
31pub const fn default_max_connect_connections() -> usize {
33 DEFAULT_MAX_CONNECT_CONNECTIONS
34}
35
36#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct OnionHttpProxyOptions {
39 pub listen_addr: SocketAddr,
41 pub max_connections: usize,
43 pub header_timeout: Duration,
45}
46
47impl OnionHttpProxyOptions {
48 pub fn new(listen_addr: SocketAddr) -> Self {
50 Self {
51 listen_addr,
52 max_connections: DEFAULT_MAX_CONNECT_CONNECTIONS,
53 header_timeout: Duration::from_secs(DEFAULT_CONNECT_HEADER_TIMEOUT_SECS),
54 }
55 }
56
57 fn validate(&self) -> Result<()> {
58 if self.max_connections == 0 {
59 return Err(Error::InvalidConfig(
60 "onion_http_proxy_max_connections must be greater than zero".to_string(),
61 ));
62 }
63 if self.header_timeout.is_zero() {
64 return Err(Error::InvalidConfig(
65 "onion_http_proxy_header_timeout_secs must be greater than zero".to_string(),
66 ));
67 }
68 Ok(())
69 }
70}
71
72pub async fn run_onion_http_proxy(
74 options: OnionHttpProxyOptions,
75 processor: Arc<Processor>,
76 onion: NativeOnionCircuitHandle,
77) -> Result<()> {
78 options.validate()?;
79 let listener = TcpListener::bind(options.listen_addr)
80 .await
81 .map_err(|error| Error::OnionProxyIoError(format!("bind HTTP proxy listener: {error}")))?;
82 let listen_addr = listener.local_addr().map_err(|error| {
83 Error::OnionProxyIoError(format!("read HTTP proxy listener address: {error}"))
84 })?;
85 println!("Onion HTTP CONNECT proxy endpoint: http://{listen_addr}");
86 let permits = Arc::new(Semaphore::new(options.max_connections));
87
88 loop {
89 let permit = permits
90 .clone()
91 .acquire_owned()
92 .await
93 .map_err(|_| Error::Lock)?;
94 let (stream, peer_addr) = listener.accept().await.map_err(|error| {
95 Error::OnionProxyIoError(format!("accept HTTP proxy connection: {error}"))
96 })?;
97 let tasks = processor.tasks().clone();
98 let processor = processor.clone();
99 let onion = onion.clone();
100 let options = options.clone();
101 tasks.spawn(async move {
103 let _permit = permit;
104 if let Err(error) = handle_connect(stream, processor, onion, options).await {
105 tracing::warn!("onion HTTP proxy request from {peer_addr} failed: {error:?}");
106 }
107 })?;
108 }
109}
110
111async fn handle_connect(
112 mut stream: TcpStream,
113 processor: Arc<Processor>,
114 onion: NativeOnionCircuitHandle,
115 options: OnionHttpProxyOptions,
116) -> Result<()> {
117 let target = match read_connect_target(&mut stream, options.header_timeout).await {
118 Ok(target) => target,
119 Err(error) => {
120 let _ = write_proxy_response(&mut stream, "400 Bad Request").await;
121 return Err(error);
122 }
123 };
124 let opened = onion.open_tcp_target(&processor, target).await;
125 write_proxy_response(&mut stream, connect_status(opened.is_ok())).await?;
126 opened?.relay(stream);
127 Ok(())
128}
129
130const fn connect_status(opened: bool) -> &'static str {
134 if opened {
135 "200 Connection Established"
136 } else {
137 "502 Bad Gateway"
138 }
139}
140
141async fn read_connect_target(
142 stream: &mut TcpStream,
143 header_timeout: Duration,
144) -> Result<OnionProxyTarget> {
145 let header = timeout(header_timeout, read_http_header(stream))
146 .await
147 .map_err(|_| {
148 Error::HttpRequestError(format!(
149 "HTTP CONNECT header timed out after {} ms",
150 header_timeout.as_millis()
151 ))
152 })??;
153 let header = std::str::from_utf8(&header)
154 .map_err(|_| Error::HttpRequestError("HTTP CONNECT header is not UTF-8".to_string()))?;
155 let request_line = header
156 .lines()
157 .next()
158 .ok_or_else(|| Error::HttpRequestError("missing HTTP request line".to_string()))?;
159 parse_connect_request_line(request_line)
160}
161
162async fn read_http_header(stream: &mut TcpStream) -> Result<Vec<u8>> {
163 let mut header = Vec::new();
164 let mut byte = [0_u8; 1];
165 while header.len() < MAX_CONNECT_HEADER_BYTES {
166 let n = stream.read(byte.as_mut_slice()).await.map_err(|error| {
167 Error::HttpRequestError(format!("read HTTP CONNECT header: {error}"))
168 })?;
169 if n == 0 {
170 return Err(Error::HttpRequestError(
171 "connection closed before HTTP CONNECT header completed".to_string(),
172 ));
173 }
174 header.push(byte[0]);
175 if header.ends_with(b"\r\n\r\n") {
176 return Ok(header);
177 }
178 }
179 Err(Error::HttpRequestError(format!(
180 "HTTP CONNECT header exceeded {MAX_CONNECT_HEADER_BYTES} bytes"
181 )))
182}
183
184fn parse_connect_request_line(request_line: &str) -> Result<OnionProxyTarget> {
185 let mut parts = request_line.split_whitespace();
186 let method = parts
187 .next()
188 .ok_or_else(|| Error::HttpRequestError("missing HTTP method".to_string()))?;
189 let authority = parts
190 .next()
191 .ok_or_else(|| Error::HttpRequestError("missing HTTP CONNECT target".to_string()))?;
192 let version = parts
193 .next()
194 .ok_or_else(|| Error::HttpRequestError("missing HTTP version".to_string()))?;
195
196 if parts.next().is_some() {
197 return Err(Error::HttpRequestError(format!(
198 "invalid HTTP CONNECT request line {request_line:?}"
199 )));
200 }
201 if method != "CONNECT" {
202 return Err(Error::HttpRequestError(format!(
203 "unsupported onion proxy method {method:?}; expected CONNECT"
204 )));
205 }
206 if !version.starts_with("HTTP/") {
207 return Err(Error::HttpRequestError(format!(
208 "invalid HTTP version {version:?}"
209 )));
210 }
211
212 OnionProxyTarget::parse_authority(authority)
213}
214
215async fn write_proxy_response(stream: &mut TcpStream, status: &str) -> Result<()> {
216 let response = format!("HTTP/1.1 {status}\r\n\r\n");
217 stream
218 .write_all(response.as_bytes())
219 .await
220 .map_err(|error| Error::HttpRequestError(format!("write HTTP proxy response: {error}")))
221}
222
223#[cfg(test)]
224mod tests;
225
226#[cfg(test)]
227mod test_http_unit;