Skip to main content

hopr_builder/
exit.rs

1use std::{net::SocketAddr, num::NonZeroUsize};
2
3use hopr_lib::{
4    OffchainKeypair, ServiceId,
5    errors::HoprLibError,
6    prelude::{ConnectedUdpStream, ForeignDataMode, UdpStreamParallelism},
7    transfer_session,
8};
9
10use crate::config::SessionIpForwardingConfig;
11
12#[cfg(all(feature = "telemetry", not(test)))]
13lazy_static::lazy_static! {
14    static ref METRIC_ACTIVE_TARGETS: hopr_metrics::MultiGauge = hopr_metrics::MultiGauge::new(
15        "hopr_session_hoprd_target_connections",
16        "Number of currently active HOPR session target connections on this Exit node",
17        &["type"]
18    ).unwrap();
19}
20
21/// Size of the buffer for forwarding data to/from a TCP stream.
22pub const HOPR_TCP_BUFFER_SIZE: usize = 4096;
23
24/// Size of the buffer for forwarding data to/from a UDP stream.
25pub const HOPR_UDP_BUFFER_SIZE: usize = 16384;
26
27/// Size of the queue (back-pressure) for data incoming from a UDP stream.
28pub const HOPR_UDP_QUEUE_SIZE: usize = 8192;
29
30/// Implementation of `HoprSessionServer` that facilitates
31/// bridging of TCP or UDP sockets from the Session Exit node to a destination.
32#[derive(Debug, Clone)]
33pub struct HoprServerIpForwardingReactor {
34    keypair: OffchainKeypair,
35    cfg: SessionIpForwardingConfig,
36}
37
38impl HoprServerIpForwardingReactor {
39    pub fn new(keypair: OffchainKeypair, cfg: SessionIpForwardingConfig) -> Self {
40        Self { keypair, cfg }
41    }
42
43    fn all_ips_allowed(&self, addrs: &[SocketAddr]) -> bool {
44        if self.cfg.use_target_allow_list {
45            for addr in addrs {
46                if !self.cfg.target_allow_list.contains(addr) {
47                    tracing::error!(%addr, "address not allowed by the target allow list, denying the target");
48                    return false;
49                }
50                tracing::debug!(%addr, "address allowed by the target allow list, accepting the target");
51            }
52        }
53        true
54    }
55}
56
57pub const SERVICE_ID_LOOPBACK: ServiceId = 0;
58
59#[async_trait::async_trait]
60impl hopr_lib::traits::session::HoprSessionServer for HoprServerIpForwardingReactor {
61    #[tracing::instrument(level = "debug", skip(self, session))]
62    async fn process(
63        &self,
64        mut session: hopr_lib::exports::transport::IncomingSession,
65    ) -> hopr_lib::errors::Result<()> {
66        let session_id = *session.session.id();
67        match session.target {
68            hopr_lib::SessionTarget::UdpStream(udp_target) => {
69                let kp = self.keypair.clone();
70                let udp_target = hopr_lib::utils::hopr_parallelize::cpu::spawn_blocking(
71                    move || udp_target.unseal(&kp),
72                    "udp_unseal",
73                )
74                .await
75                .map_err(|e| HoprLibError::GeneralError(format!("failed to spawn unseal task: {e}")))?
76                .map_err(|e| HoprLibError::GeneralError(format!("cannot unseal target: {e}")))?;
77
78                tracing::debug!(
79                    session_id = ?session_id,
80                    %udp_target,
81                    "binding socket to the UDP server"
82                );
83
84                // In UDP, it is impossible to determine if the target is viable,
85                // so we just take the first resolved address.
86                let resolved_udp_target = udp_target
87                    .clone()
88                    .resolve_tokio()
89                    .await
90                    .map_err(|e| HoprLibError::GeneralError(format!("failed to resolve DNS name {udp_target}: {e}")))?
91                    .first()
92                    .ok_or(HoprLibError::GeneralError(format!(
93                        "failed to resolve DNS name {udp_target}"
94                    )))?
95                    .to_owned();
96                tracing::debug!(
97                    ?session_id,
98                    %udp_target,
99                    resolution = ?resolved_udp_target,
100                    "UDP target resolved"
101                );
102
103                if !self.all_ips_allowed(&[resolved_udp_target]) {
104                    return Err(HoprLibError::GeneralError(format!(
105                        "denied target address {resolved_udp_target}"
106                    )));
107                }
108
109                let mut udp_bridge = ConnectedUdpStream::builder()
110                    .with_buffer_size(HOPR_UDP_BUFFER_SIZE)
111                    .with_counterparty(resolved_udp_target)
112                    .with_foreign_data_mode(ForeignDataMode::Error)
113                    .with_queue_size(HOPR_UDP_QUEUE_SIZE)
114                    .with_receiver_parallelism(
115                        std::env::var("HOPRD_SESSION_EXIT_UDP_RX_PARALLELISM")
116                            .ok()
117                            .and_then(|s| s.parse::<NonZeroUsize>().ok())
118                            .map(UdpStreamParallelism::Specific)
119                            .unwrap_or(UdpStreamParallelism::Auto),
120                    )
121                    .build(("0.0.0.0", 0))
122                    .map_err(|e| {
123                        HoprLibError::GeneralError(format!(
124                            "could not bridge the incoming session to {udp_target}: {e}"
125                        ))
126                    })?;
127
128                tracing::debug!(
129                    ?session_id,
130                    %udp_target,
131                    "bridging the session to the UDP server"
132                );
133
134                tokio::task::spawn(async move {
135                    #[cfg(all(feature = "telemetry", not(test)))]
136                    let _g = hopr_metrics::MultiGaugeGuard::new(&METRIC_ACTIVE_TARGETS, &["udp"], 1.0);
137
138                    // The Session forwards the termination to the udp_bridge, terminating
139                    // the UDP socket.
140                    match transfer_session(&mut session.session, &mut udp_bridge, HOPR_UDP_BUFFER_SIZE, None).await {
141                        Ok((session_to_stream_bytes, stream_to_session_bytes)) => tracing::info!(
142                            ?session_id,
143                            session_to_stream_bytes,
144                            stream_to_session_bytes,
145                            %udp_target,
146                            "server bridged session to UDP ended"
147                        ),
148                        Err(e) => tracing::error!(
149                            ?session_id,
150                            %udp_target,
151                            error = %e,
152                            "UDP server stream is closed"
153                        ),
154                    }
155                });
156
157                Ok(())
158            }
159            hopr_lib::SessionTarget::TcpStream(tcp_target) => {
160                let kp = self.keypair.clone();
161                let tcp_target = hopr_lib::utils::hopr_parallelize::cpu::spawn_blocking(
162                    move || tcp_target.unseal(&kp),
163                    "tcp_unseal",
164                )
165                .await
166                .map_err(|e| HoprLibError::GeneralError(format!("failed to spawn unseal task: {e}")))?
167                .map_err(|e| HoprLibError::GeneralError(format!("cannot unseal target: {e}")))?;
168
169                tracing::debug!(?session_id, %tcp_target, "creating a connection to the TCP server");
170
171                // TCP is able to determine which of the resolved multiple addresses is viable,
172                // and therefore we can pass all of them.
173                let resolved_tcp_targets =
174                    tcp_target.clone().resolve_tokio().await.map_err(|e| {
175                        HoprLibError::GeneralError(format!("failed to resolve DNS name {tcp_target}: {e}"))
176                    })?;
177                tracing::debug!(
178                    ?session_id,
179                    %tcp_target,
180                    resolution = ?resolved_tcp_targets,
181                    "TCP target resolved"
182                );
183
184                if !self.all_ips_allowed(&resolved_tcp_targets) {
185                    return Err(HoprLibError::GeneralError(format!(
186                        "denied target address {resolved_tcp_targets:?}"
187                    )));
188                }
189
190                let strategy = tokio_retry::strategy::FixedInterval::new(self.cfg.tcp_target_retry_delay)
191                    .take(self.cfg.max_tcp_target_retries as usize);
192
193                let mut tcp_bridge = tokio_retry::Retry::spawn(strategy, || {
194                    tokio::net::TcpStream::connect(resolved_tcp_targets.as_slice())
195                })
196                .await
197                .map_err(|e| {
198                    HoprLibError::GeneralError(format!("could not bridge the incoming session to {tcp_target}: {e}"))
199                })?;
200
201                tcp_bridge.set_nodelay(true).map_err(|e| {
202                    HoprLibError::GeneralError(format!(
203                        "could not set the TCP_NODELAY option for the bridged session to {tcp_target}: {e}",
204                    ))
205                })?;
206
207                tracing::debug!(
208                    ?session_id,
209                    %tcp_target,
210                    "bridging the session to the TCP server"
211                );
212
213                tokio::task::spawn(async move {
214                    #[cfg(all(feature = "telemetry", not(test)))]
215                    let _g = hopr_metrics::MultiGaugeGuard::new(&METRIC_ACTIVE_TARGETS, &["tcp"], 1.0);
216
217                    match transfer_session(&mut session.session, &mut tcp_bridge, HOPR_TCP_BUFFER_SIZE, None).await {
218                        Ok((session_to_stream_bytes, stream_to_session_bytes)) => tracing::info!(
219                            ?session_id,
220                            session_to_stream_bytes,
221                            stream_to_session_bytes,
222                            %tcp_target,
223                            "server bridged session to TCP ended"
224                        ),
225                        Err(error) => tracing::error!(
226                            ?session_id,
227                            %tcp_target,
228                            %error,
229                            "TCP server stream is closed"
230                        ),
231                    }
232                });
233
234                Ok(())
235            }
236            hopr_lib::SessionTarget::ExitNode(SERVICE_ID_LOOPBACK) => {
237                tracing::debug!(?session_id, "bridging the session to the loopback service");
238                let (mut reader, mut writer) = tokio::io::split(session.session);
239
240                #[cfg(all(feature = "telemetry", not(test)))]
241                let _g = hopr_metrics::MultiGaugeGuard::new(&METRIC_ACTIVE_TARGETS, &["loopback"], 1.0);
242
243                // Uses 4 kB buffer for copying
244                match tokio::io::copy(&mut reader, &mut writer).await {
245                    Ok(copied) => tracing::info!(?session_id, copied, "server loopback session service ended"),
246                    Err(error) => tracing::error!(
247                        ?session_id,
248                        %error,
249                        "server loopback session service ended with an error"
250                    ),
251                }
252
253                Ok(())
254            }
255            hopr_lib::SessionTarget::ExitNode(_) => Err(HoprLibError::GeneralError(
256                "server does not support internal session processing".into(),
257            )),
258        }
259    }
260}