hoprd/
exit.rs

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