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 udp_target = udp_target
55                    .unseal(&self.keypair)
56                    .map_err(|e| HoprLibError::GeneralError(format!("cannot unseal target: {e}")))?;
57
58                tracing::debug!(
59                    session_id = ?session_id,
60                    %udp_target,
61                    "binding socket to the UDP server"
62                );
63
64                // In UDP, it is impossible to determine if the target is viable,
65                // so we just take the first resolved address.
66                let resolved_udp_target = udp_target
67                    .clone()
68                    .resolve_tokio()
69                    .await
70                    .map_err(|e| HoprLibError::GeneralError(format!("failed to resolve DNS name {udp_target}: {e}")))?
71                    .first()
72                    .ok_or(HoprLibError::GeneralError(format!(
73                        "failed to resolve DNS name {udp_target}"
74                    )))?
75                    .to_owned();
76                tracing::debug!(
77                    ?session_id,
78                    %udp_target,
79                    resolution = ?resolved_udp_target,
80                    "UDP target resolved"
81                );
82
83                if !self.all_ips_allowed(&[resolved_udp_target]) {
84                    return Err(HoprLibError::GeneralError(format!(
85                        "denied target address {resolved_udp_target}"
86                    )));
87                }
88
89                let mut udp_bridge = hopr_network_types::udp::ConnectedUdpStream::builder()
90                    .with_buffer_size(HOPR_UDP_BUFFER_SIZE)
91                    .with_counterparty(resolved_udp_target)
92                    .with_foreign_data_mode(ForeignDataMode::Error)
93                    .with_queue_size(HOPR_UDP_QUEUE_SIZE)
94                    .with_receiver_parallelism(UdpStreamParallelism::Auto)
95                    .build(("0.0.0.0", 0))
96                    .map_err(|e| {
97                        HoprLibError::GeneralError(format!(
98                            "could not bridge the incoming session to {udp_target}: {e}"
99                        ))
100                    })?;
101
102                tracing::debug!(
103                    ?session_id,
104                    %udp_target,
105                    "bridging the session to the UDP server"
106                );
107
108                tokio::task::spawn(async move {
109                    #[cfg(all(feature = "prometheus", not(test)))]
110                    METRIC_ACTIVE_TARGETS.increment(&["udp"], 1.0);
111
112                    match transfer_session(&mut session.session, &mut udp_bridge, HOPR_UDP_BUFFER_SIZE).await {
113                        Ok((session_to_stream_bytes, stream_to_session_bytes)) => tracing::info!(
114                            ?session_id,
115                            session_to_stream_bytes,
116                            stream_to_session_bytes,
117                            %udp_target,
118                            "server bridged session to UDP ended"
119                        ),
120                        Err(e) => tracing::error!(
121                            ?session_id,
122                            %udp_target,
123                            error = %e,
124                            "UDP server stream is closed"
125                        ),
126                    }
127
128                    #[cfg(all(feature = "prometheus", not(test)))]
129                    METRIC_ACTIVE_TARGETS.decrement(&["udp"], 1.0);
130                });
131
132                Ok(())
133            }
134            hopr_lib::SessionTarget::TcpStream(tcp_target) => {
135                let tcp_target = tcp_target
136                    .unseal(&self.keypair)
137                    .map_err(|e| HoprLibError::GeneralError(format!("cannot unseal target: {e}")))?;
138
139                tracing::debug!(?session_id, %tcp_target, "creating a connection to the TCP server");
140
141                // TCP is able to determine which of the resolved multiple addresses is viable,
142                // and therefore we can pass all of them.
143                let resolved_tcp_targets =
144                    tcp_target.clone().resolve_tokio().await.map_err(|e| {
145                        HoprLibError::GeneralError(format!("failed to resolve DNS name {tcp_target}: {e}"))
146                    })?;
147                tracing::debug!(
148                    ?session_id,
149                    %tcp_target,
150                    resolution = ?resolved_tcp_targets,
151                    "TCP target resolved"
152                );
153
154                if !self.all_ips_allowed(&resolved_tcp_targets) {
155                    return Err(HoprLibError::GeneralError(format!(
156                        "denied target address {resolved_tcp_targets:?}"
157                    )));
158                }
159
160                let strategy = tokio_retry::strategy::FixedInterval::new(self.cfg.tcp_target_retry_delay)
161                    .take(self.cfg.max_tcp_target_retries as usize);
162
163                let mut tcp_bridge = tokio_retry::Retry::spawn(strategy, || {
164                    tokio::net::TcpStream::connect(resolved_tcp_targets.as_slice())
165                })
166                .await
167                .map_err(|e| {
168                    HoprLibError::GeneralError(format!("could not bridge the incoming session to {tcp_target}: {e}"))
169                })?;
170
171                tcp_bridge.set_nodelay(true).map_err(|e| {
172                    HoprLibError::GeneralError(format!(
173                        "could not set the TCP_NODELAY option for the bridged session to {tcp_target}: {e}",
174                    ))
175                })?;
176
177                tracing::debug!(
178                    ?session_id,
179                    %tcp_target,
180                    "bridging the session to the TCP server"
181                );
182                tokio::task::spawn(async move {
183                    #[cfg(all(feature = "prometheus", not(test)))]
184                    METRIC_ACTIVE_TARGETS.increment(&["tcp"], 1.0);
185
186                    match transfer_session(&mut session.session, &mut tcp_bridge, HOPR_TCP_BUFFER_SIZE).await {
187                        Ok((session_to_stream_bytes, stream_to_session_bytes)) => tracing::info!(
188                            ?session_id,
189                            session_to_stream_bytes,
190                            stream_to_session_bytes,
191                            %tcp_target,
192                            "server bridged session to TCP ended"
193                        ),
194                        Err(error) => tracing::error!(
195                            ?session_id,
196                            %tcp_target,
197                            %error,
198                            "TCP server stream is closed"
199                        ),
200                    }
201
202                    #[cfg(all(feature = "prometheus", not(test)))]
203                    METRIC_ACTIVE_TARGETS.decrement(&["tcp"], 1.0);
204                });
205
206                Ok(())
207            }
208            hopr_lib::SessionTarget::ExitNode(SERVICE_ID_LOOPBACK) => {
209                tracing::debug!(?session_id, "bridging the session to the loopback service");
210                let (mut reader, mut writer) = tokio::io::split(session.session);
211
212                #[cfg(all(feature = "prometheus", not(test)))]
213                METRIC_ACTIVE_TARGETS.increment(&["loopback"], 1.0);
214
215                // Uses 4 kB buffer for copying
216                match tokio::io::copy(&mut reader, &mut writer).await {
217                    Ok(copied) => tracing::info!(?session_id, copied, "server loopback session service ended"),
218                    Err(error) => tracing::error!(
219                        ?session_id,
220                        %error,
221                        "server loopback session service ended with an error"
222                    ),
223                }
224
225                #[cfg(all(feature = "prometheus", not(test)))]
226                METRIC_ACTIVE_TARGETS.decrement(&["loopback"], 1.0);
227
228                Ok(())
229            }
230            hopr_lib::SessionTarget::ExitNode(_) => Err(HoprLibError::GeneralError(
231                "server does not support internal session processing".into(),
232            )),
233        }
234    }
235}