1use std::{
4 collections::{btree_map::Entry, BTreeMap, HashSet},
5 sync::{Arc, Mutex},
6};
7
8use arti_client::config::onion_service::{OnionServiceConfig, OnionServiceConfigBuilder};
9use futures::{task::SpawnExt, StreamExt as _};
10use tor_config::{
11 define_list_builder_helper, impl_standard_builder, ConfigBuildError, Flatten, Reconfigure,
12 ReconfigureError,
13};
14use tor_error::warn_report;
15use tor_hsrproxy::{config::ProxyConfigBuilder, OnionServiceReverseProxy, ProxyConfig};
16use tor_hsservice::{HsNickname, RunningOnionService};
17use tor_rtcompat::Runtime;
18use tracing::debug;
19
20#[derive(Clone, Debug, Eq, PartialEq)]
28pub struct OnionServiceProxyConfig {
29 pub(crate) svc_cfg: OnionServiceConfig,
31 pub(crate) proxy_cfg: ProxyConfig,
34}
35
36#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Default)]
42#[serde(transparent)]
43pub struct OnionServiceProxyConfigBuilder(Flatten<OnionServiceConfigBuilder, ProxyConfigBuilder>);
44
45impl OnionServiceProxyConfigBuilder {
46 pub fn build(&self) -> Result<OnionServiceProxyConfig, ConfigBuildError> {
50 let svc_cfg = self.0 .0.build()?;
51 let proxy_cfg = self.0 .1.build()?;
52 Ok(OnionServiceProxyConfig { svc_cfg, proxy_cfg })
53 }
54
55 pub fn service(&mut self) -> &mut OnionServiceConfigBuilder {
57 &mut self.0 .0
58 }
59
60 pub fn proxy(&mut self) -> &mut ProxyConfigBuilder {
62 &mut self.0 .1
63 }
64}
65
66impl_standard_builder! { OnionServiceProxyConfig: !Default }
67
68#[cfg(feature = "onion-service-service")]
70pub(crate) type OnionServiceProxyConfigMap = BTreeMap<HsNickname, OnionServiceProxyConfig>;
71
72type ProxyBuilderMap = BTreeMap<HsNickname, OnionServiceProxyConfigBuilder>;
75
76#[cfg(feature = "onion-service-service")]
80define_list_builder_helper! {
81 pub struct OnionServiceProxyConfigMapBuilder {
82 services: [OnionServiceProxyConfigBuilder],
83 }
84 built: OnionServiceProxyConfigMap = build_list(services)?;
85 default = vec![];
86 #[serde(try_from="ProxyBuilderMap", into="ProxyBuilderMap")]
87}
88
89fn build_list(
92 services: Vec<OnionServiceProxyConfig>,
93) -> Result<OnionServiceProxyConfigMap, ConfigBuildError> {
94 let mut map = BTreeMap::new();
100 for service in services {
101 if let Some(previous_value) = map.insert(service.svc_cfg.nickname().clone(), service) {
102 return Err(ConfigBuildError::Inconsistent {
103 fields: vec!["nickname".into()],
104 problem: format!(
105 "Multiple onion services with the nickname {}",
106 previous_value.svc_cfg.nickname()
107 ),
108 });
109 };
110 }
111 Ok(map)
112}
113
114impl TryFrom<ProxyBuilderMap> for OnionServiceProxyConfigMapBuilder {
115 type Error = ConfigBuildError;
116
117 fn try_from(value: ProxyBuilderMap) -> Result<Self, Self::Error> {
118 let mut list_builder = OnionServiceProxyConfigMapBuilder::default();
119 for (nickname, mut cfg) in value {
120 match cfg.0 .0.peek_nickname() {
121 Some(n) if n == &nickname => (),
122 None => (),
123 Some(other) => {
124 return Err(ConfigBuildError::Inconsistent {
125 fields: vec![nickname.to_string(), format!("{nickname}.{other}")],
126 problem: "mismatched nicknames on onion service.".into(),
127 });
128 }
129 }
130 cfg.0 .0.nickname(nickname);
131 list_builder.access().push(cfg);
132 }
133 Ok(list_builder)
134 }
135}
136
137impl From<OnionServiceProxyConfigMapBuilder> for ProxyBuilderMap {
138 fn from(value: OnionServiceProxyConfigMapBuilder) -> Self {
145 let mut map = BTreeMap::new();
146 for cfg in value.services.into_iter().flatten() {
147 let nickname = cfg.0 .0.peek_nickname().cloned().unwrap_or_else(|| {
148 "Unnamed"
149 .to_string()
150 .try_into()
151 .expect("'Unnamed' was not a valid nickname")
152 });
153 map.insert(nickname, cfg);
154 }
155 map
156 }
157}
158
159#[must_use = "a hidden service Proxy object will terminate the service when dropped"]
164struct Proxy {
165 svc: Arc<RunningOnionService>,
169 proxy: Arc<OnionServiceReverseProxy>,
173}
174
175impl Proxy {
176 pub(crate) fn launch_new<R: Runtime>(
179 client: &arti_client::TorClient<R>,
180 config: OnionServiceProxyConfig,
181 ) -> anyhow::Result<Self> {
182 let OnionServiceProxyConfig { svc_cfg, proxy_cfg } = config;
183 let nickname = svc_cfg.nickname().clone();
184 let (svc, request_stream) = client.launch_onion_service(svc_cfg)?;
185 let proxy = OnionServiceReverseProxy::new(proxy_cfg);
186
187 {
188 let proxy = proxy.clone();
189 let runtime_clone = client.runtime().clone();
190 let nickname_clone = nickname.clone();
191 client.runtime().spawn(async move {
192 match proxy
193 .handle_requests(runtime_clone, nickname.clone(), request_stream)
194 .await
195 {
196 Ok(()) => {
197 debug!("Onion service {} exited cleanly.", nickname);
198 }
199 Err(e) => {
200 warn_report!(e, "Onion service {} exited with an error", nickname);
201 }
202 }
203 })?;
204
205 let mut status_stream = svc.status_events();
206 client.runtime().spawn(async move {
207 while let Some(status) = status_stream.next().await {
208 debug!(
209 nickname=%nickname_clone,
210 status=?status.state(),
211 problem=?status.current_problem(),
212 "Onion service status change",
213 );
214 }
215 })?;
216 }
217
218 Ok(Proxy { svc, proxy })
219 }
220
221 fn reconfigure(
224 &mut self,
225 config: OnionServiceProxyConfig,
226 how: Reconfigure,
227 ) -> Result<(), ReconfigureError> {
228 if matches!(how, Reconfigure::AllOrNothing) {
229 self.reconfigure_inner(config.clone(), Reconfigure::CheckAllOrNothing)?;
230 }
231
232 self.reconfigure_inner(config, how)
233 }
234
235 fn reconfigure_inner(
237 &mut self,
238 config: OnionServiceProxyConfig,
239 how: Reconfigure,
240 ) -> Result<(), ReconfigureError> {
241 let OnionServiceProxyConfig { svc_cfg, proxy_cfg } = config;
242
243 self.svc.reconfigure(svc_cfg, how)?;
244 self.proxy.reconfigure(proxy_cfg, how)?;
245
246 Ok(())
247 }
248}
249
250#[must_use = "a hidden service ProxySet object will terminate the services when dropped"]
252pub(crate) struct ProxySet<R: Runtime> {
253 client: arti_client::TorClient<R>,
255 proxies: Mutex<BTreeMap<HsNickname, Proxy>>,
257}
258
259impl<R: Runtime> ProxySet<R> {
260 pub(crate) fn launch_new(
262 client: &arti_client::TorClient<R>,
263 config_list: OnionServiceProxyConfigMap,
264 ) -> anyhow::Result<Self> {
265 let proxies: BTreeMap<_, _> = config_list
266 .into_iter()
267 .map(|(nickname, cfg)| Ok((nickname, Proxy::launch_new(client, cfg)?)))
268 .collect::<anyhow::Result<BTreeMap<_, _>>>()?;
269
270 Ok(Self {
271 client: client.clone(),
272 proxies: Mutex::new(proxies),
273 })
274 }
275
276 pub(crate) fn reconfigure(
282 &self,
283 new_config: OnionServiceProxyConfigMap,
284 ) -> Result<(), anyhow::Error> {
287 let mut proxy_map = self.proxies.lock().expect("lock poisoned");
288
289 let mut defunct_nicknames: HashSet<_> = proxy_map.keys().map(Clone::clone).collect();
291
292 for cfg in new_config.into_values() {
293 let nickname = cfg.svc_cfg.nickname().clone();
294 defunct_nicknames.remove(&nickname);
297
298 match proxy_map.entry(nickname) {
299 Entry::Occupied(mut existing_proxy) => {
300 existing_proxy
303 .get_mut()
304 .reconfigure(cfg, Reconfigure::WarnOnFailures)?;
305 }
306 Entry::Vacant(ent) => {
307 match Proxy::launch_new(&self.client, cfg) {
310 Ok(new_proxy) => {
311 ent.insert(new_proxy);
312 }
313 Err(err) => {
314 warn_report!(err, "Unable to launch onion service {}", ent.key());
315 }
316 }
317 }
318 }
319 }
320
321 for nickname in defunct_nicknames {
322 let defunct_proxy = proxy_map
325 .remove(&nickname)
326 .expect("Somehow a proxy disappeared from the map");
327 drop(defunct_proxy);
329 }
330
331 Ok(())
332 }
333
334 pub(crate) fn is_empty(&self) -> bool {
336 self.proxies.lock().expect("lock poisoned").is_empty()
337 }
338}
339
340impl<R: Runtime> crate::reload_cfg::ReconfigurableModule for ProxySet<R> {
341 fn reconfigure(&self, new: &crate::ArtiCombinedConfig) -> anyhow::Result<()> {
342 ProxySet::reconfigure(self, new.0.onion_services.clone())?;
343 Ok(())
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 #![allow(clippy::bool_assert_comparison)]
351 #![allow(clippy::clone_on_copy)]
352 #![allow(clippy::dbg_macro)]
353 #![allow(clippy::mixed_attributes_style)]
354 #![allow(clippy::print_stderr)]
355 #![allow(clippy::print_stdout)]
356 #![allow(clippy::single_char_pattern)]
357 #![allow(clippy::unwrap_used)]
358 #![allow(clippy::unchecked_duration_subtraction)]
359 #![allow(clippy::useless_vec)]
360 #![allow(clippy::needless_pass_by_value)]
361 use super::*;
363
364 use tor_config::ConfigBuildError;
365 use tor_hsservice::HsNickname;
366
367 fn get_onion_service_proxy_config(nick: &HsNickname) -> OnionServiceProxyConfig {
369 let mut builder = OnionServiceProxyConfigBuilder::default();
370 builder.service().nickname(nick.clone());
371 builder.build().unwrap()
372 }
373
374 #[test]
376 fn fn_build_list() {
377 let nick_1 = HsNickname::new("nick_1".to_string()).unwrap();
378 let nick_2 = HsNickname::new("nick_2".to_string()).unwrap();
379
380 let proxy_configs: Vec<OnionServiceProxyConfig> = [&nick_1, &nick_2]
381 .into_iter()
382 .map(get_onion_service_proxy_config)
383 .collect();
384 let actual = build_list(proxy_configs.clone()).unwrap();
385
386 let expected =
387 OnionServiceProxyConfigMap::from_iter([nick_1, nick_2].into_iter().zip(proxy_configs));
388
389 assert_eq!(actual, expected);
390
391 let nick = HsNickname::new("nick".to_string()).unwrap();
392 let proxy_configs_dup: Vec<OnionServiceProxyConfig> = [&nick, &nick]
393 .into_iter()
394 .map(get_onion_service_proxy_config)
395 .collect();
396 let actual = build_list(proxy_configs_dup).unwrap_err();
397 let ConfigBuildError::Inconsistent { fields, problem } = actual else {
398 panic!("Unexpected error from `build_list`: {actual:?}");
399 };
400
401 assert_eq!(fields, vec!["nickname".to_string()]);
402 assert_eq!(
403 problem,
404 format!("Multiple onion services with the nickname {nick}")
405 );
406 }
407}