hoprd/
exit.rs

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