1use std::{
2 ops::{Deref, DerefMut},
3 sync::Arc,
4};
5
6pub use arti_client;
7pub use safelog::DisplayRedacted;
8pub use tor_cell;
9pub use tor_hsservice;
10
11use snafu::OptionExt;
12use snafu::prelude::*;
13
14use arti_client::{DataStream, TorClientConfig};
15use futures_util::{Stream, StreamExt};
16use tor_cell::relaycell::msg::Connected;
17use tor_hsservice::{RendRequest, StreamRequest};
18
19pub type TorClient = arti_client::TorClient<tor_rtcompat::PreferredRuntime>;
20pub type TorClientBuilder = arti_client::TorClientBuilder<tor_rtcompat::PreferredRuntime>;
21
22#[cfg(feature = "http-client")]
23mod http_client;
24
25#[cfg(feature = "http-client")]
26pub use http_client::{HttpClient, HttpClientBuilder};
27
28#[cfg(feature = "http-server")]
29mod http_server;
30
31#[cfg(feature = "http-server")]
32pub use http_server::HttpServer;
33
34mod error;
35pub use error::*;
36
37pub type Result<T, E = Error> = std::result::Result<T, E>;
38
39#[derive(Clone)]
41pub struct Tor {
42 pub client: TorClient,
44}
45
46impl Deref for Tor {
47 type Target = TorClient;
48
49 fn deref(&self) -> &Self::Target {
50 &self.client
51 }
52}
53
54impl DerefMut for Tor {
55 fn deref_mut(&mut self) -> &mut Self::Target {
56 &mut self.client
57 }
58}
59
60#[derive(Debug, Clone)]
63pub struct TorConfig {
64 pub bootstrap: bool,
66
67 pub client_config: Option<TorClientConfig>,
69}
70
71impl Default for TorConfig {
72 fn default() -> Self {
73 TorConfig {
74 bootstrap: true,
75 client_config: None,
76 }
77 }
78}
79
80impl TorConfig {
81 pub fn new() -> Self {
83 Self::default()
84 }
85
86 pub fn with_bootstrap(mut self, bootstrap: bool) -> Self {
88 self.bootstrap = bootstrap;
89 self
90 }
91
92 pub fn with_client_config(mut self, config: Option<TorClientConfig>) -> Self {
94 self.client_config = config;
95 self
96 }
97}
98
99impl Tor {
100 #[tracing::instrument(err, level = "info")]
102 pub async fn new(config: TorConfig) -> Result<Self, Error> {
103 let client = if config.bootstrap {
104 Self::new_custom(async move |b| {
105 b.config(config.client_config.unwrap_or_default())
106 .create_bootstrapped()
107 .await
108 .context(ArtiClientSnafu)
109 })
110 .await?
111 } else {
112 Self::new_custom(async move |b| {
113 b.config(config.client_config.unwrap_or_default())
114 .create_unbootstrapped_async()
115 .await
116 .context(ArtiClientSnafu)
117 })
118 .await?
119 };
120
121 Ok(client)
122 }
123
124 #[tracing::instrument(err, skip(callback), level = "info")]
126 pub async fn new_custom<
127 T: Future<Output = Result<TorClient, Error>>,
128 F: FnOnce(TorClientBuilder) -> T,
129 >(
130 callback: F,
131 ) -> Result<Self, Error> {
132 let builder = arti_client::TorClient::builder();
133 let client = callback(builder).await?;
134 Ok(Self { client })
135 }
136
137 pub fn service(&self, name: &str) -> Result<HiddenService> {
139 HiddenService::new(self, name)
140 }
141}
142
143pub struct HiddenService {
145 tor: Tor,
146 service: Arc<tor_hsservice::RunningOnionService>,
147 stream: std::pin::Pin<Box<dyn Send + Sync + futures_util::Stream<Item = RendRequest>>>,
148}
149
150impl HiddenService {
151 #[tracing::instrument(skip(tor), err)]
153 pub fn new(tor: &Tor, name: &str) -> Result<Self> {
154 let service = tor_hsservice::config::OnionServiceConfigBuilder::default()
155 .nickname(name.parse().context(InvalidNicknameSnafu)?)
156 .build()
157 .context(ConfigBuildSnafu)?;
158
159 let (service, stream) = tor
160 .client
161 .launch_onion_service(service)
162 .context(ArtiClientSnafu)?
163 .context(EmptyOnionServiceSnafu {
164 name: name.to_owned(),
165 })?;
166
167 Ok(HiddenService {
168 tor: tor.clone(),
169 service,
170 stream: Box::pin(stream),
171 })
172 }
173
174 pub fn tor(&self) -> &Tor {
176 &self.tor
177 }
178
179 #[tracing::instrument(skip(self), err)]
181 pub async fn accept(&mut self) -> Result<Option<TorConnection>> {
182 if let Some(x) = self.stream.next().await {
183 x.accept()
184 .await
185 .map_err(Box::new)
186 .context(ClientSnafu)
187 .map(|stream| {
188 Option::Some(TorConnection {
189 stream: Box::new(stream),
190 })
191 })
192 } else {
193 Ok(None)
194 }
195 }
196
197 #[tracing::instrument(skip(self), err)]
199 pub async fn handle(&mut self) -> std::io::Result<Option<(Address, DataStream)>> {
200 if let Some(x) = self.stream.next().await
201 && let Some(mut conn) = x
202 .accept()
203 .await
204 .map_err(|_| {
205 std::io::Error::new(
206 std::io::ErrorKind::NotConnected,
207 "unable to accept connection",
208 )
209 })
210 .map(|stream| {
211 Option::Some(TorConnection {
212 stream: Box::new(stream),
213 })
214 })?
215 {
216 return conn.accept_next().await.map_err(|_| {
217 std::io::Error::new(
218 std::io::ErrorKind::NotConnected,
219 "unable to open data stream",
220 )
221 });
222 }
223 Ok(None)
224 }
225}
226
227impl Deref for HiddenService {
228 type Target = tor_hsservice::RunningOnionService;
229
230 fn deref(&self) -> &Self::Target {
231 &self.service
232 }
233}
234
235pub struct TorConnection {
237 stream: Box<dyn 'static + Send + Stream<Item = StreamRequest> + Unpin>,
238}
239
240impl TorConnection {
241 #[tracing::instrument(skip(self), err)]
243 pub async fn accept_next(&mut self) -> Result<Option<(Address, DataStream)>> {
244 if let Some(conn) = self.stream.next().await {
245 let addr = match conn.request() {
246 tor_proto::client::stream::IncomingStreamRequest::Begin(begin) => Address {
247 addr: begin.addr().to_vec(),
248 port: begin.port(),
249 },
250 _ => {
251 conn.shutdown_circuit().context(ArtiBugSnafu)?;
252 return Ok(None);
253 }
254 };
255
256 let conn = conn
257 .accept(Connected::new_empty())
258 .await
259 .map_err(Box::new)
260 .context(ClientSnafu)?;
261 return Ok(Some((addr, conn)));
262 }
263
264 Ok(None)
265 }
266}
267
268#[derive(Clone, Debug, PartialEq, Eq)]
270pub struct Address {
271 addr: Vec<u8>,
272 port: u16,
273}
274
275impl Stream for TorConnection {
276 type Item = StreamRequest;
277
278 fn poll_next(
279 mut self: std::pin::Pin<&mut Self>,
280 cx: &mut std::task::Context<'_>,
281 ) -> std::task::Poll<Option<Self::Item>> {
282 self.stream.poll_next_unpin(cx)
283 }
284}