Skip to main content

tor_chanmgr/
builder.rs

1//! Implement a concrete type to build channels over a transport.
2
3use async_trait::async_trait;
4use futures::{AsyncRead, AsyncWrite};
5use std::io;
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8use tracing::instrument;
9
10use crate::factory::{BootstrapReporter, ChannelFactory, IncomingChannelFactory};
11use crate::transport::TransportImplHelper;
12use crate::{Error, event::ChanMgrEventSender};
13
14use safelog::MaybeSensitive;
15use tor_basic_utils::rand_hostname;
16use tor_error::internal;
17use tor_linkspec::{ChanTarget, HasChanMethod, IntoOwnedChanTarget, OwnedChanTarget};
18use tor_proto::channel::ChannelType;
19use tor_proto::channel::kist::KistParams;
20use tor_proto::channel::params::ChannelPaddingInstructionsUpdates;
21use tor_proto::memquota::ChannelAccount;
22use tor_proto::peer::PeerAddr;
23use tor_rtcompat::SpawnExt;
24use tor_rtcompat::{CertifiedConn, Runtime, StreamOps, TlsProvider, tls::TlsConnector};
25
26#[cfg(feature = "relay")]
27use {
28    crate::mgr::ChannelBandwidthPools, safelog::Sensitive, std::net::SocketAddr,
29    tor_async_utils::global_rate_limit::GlobalRateLimitedConn, tor_error::bad_api_usage,
30    tor_proto::RelayChannelAuthMaterial, tor_proto::relay::CreateRequestHandler,
31};
32
33/// TLS-based channel builder.
34///
35/// This is a separate type so that we can keep our channel management code
36/// network-agnostic.
37///
38/// It uses a provided `TransportHelper` type to make a connection (possibly
39/// directly over TCP, and possibly over some other protocol).  It then
40/// negotiates TLS over that connection, and negotiates a Tor channel over that
41/// TLS session.
42///
43/// This channel builder does not retry on failure, but it _does_ implement a
44/// time-out.
45pub struct ChanBuilder<R: Runtime, H: TransportImplHelper>
46where
47    R: tor_rtcompat::TlsProvider<H::Stream>,
48{
49    /// Asynchronous runtime for TLS, TCP, spawning, and timeouts.
50    runtime: R,
51    /// The transport object that we use to construct streams.
52    transport: H,
53    /// Object to build TLS connections.
54    tls_connector: <R as TlsProvider<H::Stream>>::Connector,
55    /// Object to accept TLS connections.
56    #[cfg(feature = "relay")]
57    tls_acceptor: Option<<R as TlsProvider<H::Stream>>::Acceptor>,
58    /// Relay authentication key material needed for relay channels.
59    #[cfg(feature = "relay")]
60    auth_material: Option<Arc<RelayChannelAuthMaterial>>,
61    /// Our address(es) to use in the NETINFO cell.
62    // TODO: We might want one day to support updating the addresses here in the same way we
63    // support updating the auth_material. One use case for this is the relay config reload.
64    #[cfg(feature = "relay")]
65    my_addrs: Vec<SocketAddr>,
66    /// Provided to each new channel so that they can handle CREATE* requests.
67    #[cfg(feature = "relay")]
68    create_request_handler: Option<Arc<CreateRequestHandler>>,
69    /// Bandwidth pools shared by all channels for global rate limiting.
70    #[cfg(feature = "relay")]
71    bw_pools: Option<ChannelBandwidthPools>,
72    /// Allow outgoing relay channels to all addresses, including local and private
73    /// addresses.
74    #[cfg(feature = "relay")]
75    allow_any_addrs: bool,
76}
77
78impl<R: Runtime, H: TransportImplHelper> ChanBuilder<R, H>
79where
80    R: TlsProvider<H::Stream>,
81{
82    /// Construct a new client specific ChanBuilder.
83    pub fn new_client(runtime: R, transport: H) -> Self {
84        let tls_connector = <R as TlsProvider<H::Stream>>::tls_connector(&runtime);
85        ChanBuilder {
86            runtime,
87            transport,
88            tls_connector,
89            #[cfg(feature = "relay")]
90            tls_acceptor: None,
91            #[cfg(feature = "relay")]
92            auth_material: None,
93            #[cfg(feature = "relay")]
94            my_addrs: Vec::new(),
95            #[cfg(feature = "relay")]
96            create_request_handler: None,
97            #[cfg(feature = "relay")]
98            bw_pools: None,
99            #[cfg(feature = "relay")]
100            allow_any_addrs: false,
101        }
102    }
103
104    /// Construct a new relay specific ChanBuilder.
105    #[cfg(feature = "relay")]
106    pub fn new_relay(
107        runtime: R,
108        transport: H,
109        auth_material: Arc<RelayChannelAuthMaterial>,
110        my_addrs: Vec<SocketAddr>,
111        create_request_handler: Option<Arc<CreateRequestHandler>>,
112    ) -> crate::Result<Self> {
113        use tor_error::into_internal;
114        use tor_rtcompat::tls::TlsAcceptorSettings;
115
116        // Build the TLS acceptor.
117        let tls_settings = TlsAcceptorSettings::new(auth_material.tls_key_and_cert().clone())
118            .map_err(into_internal!("Unable to build TLS acceptor setting"))?;
119        let tls_acceptor = <R as TlsProvider<H::Stream>>::tls_acceptor(&runtime, tls_settings)
120            .map_err(into_internal!("Unable to build TLS acceptor"))?;
121
122        // Same builder as a client but with auth material and acceptor.
123        let mut builder = Self::new_client(runtime, transport);
124        builder.auth_material = Some(auth_material);
125        builder.tls_acceptor = Some(tls_acceptor);
126        builder.my_addrs = my_addrs;
127        builder.create_request_handler = create_request_handler;
128
129        Ok(builder)
130    }
131
132    /// Set the bandwidth pools used to rate limit all channels.
133    #[cfg(feature = "relay")]
134    pub(crate) fn with_bandwidth_pools(mut self, bw_pools: Option<ChannelBandwidthPools>) -> Self {
135        self.bw_pools = bw_pools;
136        self
137    }
138
139    /// Set whether outgoing relay channels may connect to all addresses, including local
140    /// and private addresses.
141    #[cfg(feature = "relay")]
142    pub(crate) fn allow_any_addrs(mut self, allow_any_addrs: bool) -> Self {
143        self.allow_any_addrs = allow_any_addrs;
144        self
145    }
146
147    /// Build a new `ChanBuilder` with the given `auth_material`,
148    /// cloning everything else.
149    ///
150    /// This is needed because some relay keys rotate over time.
151    #[cfg(feature = "relay")]
152    pub fn rebuild_with_auth_material(
153        &self,
154        auth_material: Arc<RelayChannelAuthMaterial>,
155    ) -> crate::Result<Self>
156    where
157        H: Clone,
158    {
159        Self::new_relay(
160            self.runtime.clone(),
161            self.transport.clone(),
162            auth_material,
163            self.my_addrs.clone(),
164            self.create_request_handler.as_ref().map(Arc::clone),
165        )
166        .map(|b| {
167            b.with_bandwidth_pools(self.bw_pools.as_ref().map(ChannelBandwidthPools::share))
168                .allow_any_addrs(self.allow_any_addrs)
169        })
170    }
171
172    /// Build a new `ChanBuilder` with the given CREATE* request `handler`,
173    /// cloning everything else.
174    ///
175    /// This is needed so that we can set the handler,
176    /// which isn't known when the builder is initially created.
177    #[cfg(feature = "relay")]
178    pub fn rebuild_with_create_request_handler(
179        &self,
180        handler: Arc<CreateRequestHandler>,
181    ) -> crate::Result<Self>
182    where
183        H: Clone,
184    {
185        let auth_material = self.auth_material.clone().ok_or_else(|| {
186            internal!("Trying to set a CREATE* request handler for a non-relay channel builder")
187        })?;
188
189        Self::new_relay(
190            self.runtime.clone(),
191            self.transport.clone(),
192            auth_material,
193            self.my_addrs.clone(),
194            Some(handler),
195        )
196        .map(|b| {
197            b.with_bandwidth_pools(self.bw_pools.as_ref().map(ChannelBandwidthPools::share))
198                .allow_any_addrs(self.allow_any_addrs)
199        })
200    }
201
202    /// Return `stream` rate limited by our bandwidth pools, or unlimited if we have none.
203    #[cfg(feature = "relay")]
204    fn rate_limit<S>(&self, stream: S) -> GlobalRateLimitedConn<S> {
205        match &self.bw_pools {
206            Some(bw_pools) => bw_pools.rate_limit(stream),
207            None => GlobalRateLimitedConn::unlimited(stream),
208        }
209    }
210
211    /// Return the outbound channel type of this config.
212    ///
213    /// The channel type is used when creating outbound channels. Relays always initiate channels
214    /// as "relay initiator" while client and bridges behave like a "client initiator".
215    ///
216    /// Important: The wrong channel type is returned if this is called before `with_identities()`
217    /// is called.
218    fn outbound_chan_type(&self) -> ChannelType {
219        #[cfg(feature = "relay")]
220        if self.auth_material.is_some() {
221            return ChannelType::RelayInitiator;
222        }
223        ChannelType::ClientInitiator
224    }
225}
226
227#[async_trait]
228impl<R: Runtime, H: TransportImplHelper> ChannelFactory for ChanBuilder<R, H>
229where
230    R: tor_rtcompat::TlsProvider<H::Stream> + Send + Sync,
231    H: Send + Sync,
232{
233    #[instrument(skip_all, level = "trace")]
234    async fn connect_via_transport(
235        &self,
236        target: &OwnedChanTarget,
237        reporter: BootstrapReporter,
238        memquota: ChannelAccount,
239    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
240        use tor_rtcompat::SleepProviderExt;
241
242        // TODO: make this an option.  And make a better value.
243        let delay = if target.chan_method().is_direct() {
244            std::time::Duration::new(5, 0)
245        } else {
246            std::time::Duration::new(10, 0)
247        };
248
249        self.runtime
250            .timeout(delay, self.connect_no_timeout(target, reporter.0, memquota))
251            .await
252            .map_err(|_| Error::ChanTimeout {
253                peer: target.to_logged(),
254            })?
255    }
256}
257
258#[async_trait]
259impl<R: Runtime, H: TransportImplHelper> IncomingChannelFactory for ChanBuilder<R, H>
260where
261    R: tor_rtcompat::TlsProvider<H::Stream> + Send + Sync,
262    H: Send + Sync,
263{
264    type Stream = H::Stream;
265
266    #[cfg(feature = "relay")]
267    async fn accept_from_transport(
268        &self,
269        peer: Sensitive<std::net::SocketAddr>,
270        stream: Self::Stream,
271        memquota: ChannelAccount,
272    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
273        use tor_linkspec::OwnedChanTargetBuilder;
274        use tor_proto::relay::MaybeVerifiableRelayResponderChannel;
275
276        // Note that as we accept a connection, we don't expect any specific identities and so we
277        // can only build a target from the peer address. This means that the verification process
278        // will not match the identities seen (if a relay <-> relay channel) to this target which
279        // is fine as we are a responder.
280        let target_no_ids = OwnedChanTargetBuilder::default()
281            .addrs(vec![peer.into_inner()])
282            .build()
283            .map_err(|e| internal!("Unable to build chan target from peer sockaddr: {e}"))?;
284        // Convert into a PeerAddr but keep it sensitive, this can be a client/bridge.
285        let peer_addr: MaybeSensitive<PeerAddr> =
286            MaybeSensitive::sensitive(peer.into_inner().into());
287
288        // Helpers: For error mapping.
289        let map_ioe = |ioe, action| Error::Io {
290            action,
291            peer: peer_addr.clone(),
292            source: ioe,
293        };
294        let map_proto = |source, target: &OwnedChanTarget, clock_skew| Error::Proto {
295            source,
296            peer: target.to_logged(),
297            clock_skew,
298        };
299
300        let tls = self
301            .tls_acceptor
302            .as_ref()
303            .ok_or_else(|| internal!("Accepting connection without TLS acceptor"))?
304            .negotiate_unvalidated(stream, "ignored")
305            .await
306            .map_err(|e| map_ioe(e.into(), "TLS negotiation"))?;
307        let auth_material = self
308            .auth_material
309            .as_ref()
310            .ok_or_else(|| internal!("Unable to build relay channel without auth material"))?
311            .clone();
312
313        let our_cert = tls
314            .own_certificate()
315            .map_err(|e| map_ioe(e.into(), "TLS Certs"))?
316            .ok_or_else(|| Error::Internal(internal!("TLS connection without our certificate")))?
317            .into_owned();
318
319        let create_request_handler = self.create_request_handler.as_ref().ok_or_else(|| {
320            bad_api_usage!("Can't create a relay channel without a CREATE* request handler")
321        })?;
322
323        let builder = tor_proto::RelayChannelBuilder::new();
324
325        let unverified = builder
326            .accept(
327                Sensitive::new(peer_addr.inner()),
328                self.my_addrs.clone(),
329                self.rate_limit(tls),
330                self.runtime.clone(),
331                auth_material,
332                memquota,
333                Arc::clone(create_request_handler),
334            )
335            .handshake(|| self.runtime.wallclock())
336            .await
337            .map_err(|e| map_proto(e, &target_no_ids, None))?;
338
339        let (chan, reactor) = match unverified {
340            MaybeVerifiableRelayResponderChannel::Verifiable(c) => {
341                let clock_skew = c.clock_skew();
342                let now = self.runtime.wallclock();
343                c.verify(&target_no_ids, &our_cert, Some(now))
344                    .map_err(|e| map_proto(e, &target_no_ids, Some(clock_skew)))?
345                    .finish()
346                    .await
347                    .map_err(|e| map_proto(e, &target_no_ids, Some(clock_skew)))?
348            }
349            MaybeVerifiableRelayResponderChannel::NonVerifiable(c) => {
350                c.finish().map_err(|e| map_proto(e, &target_no_ids, None))?
351            }
352        };
353
354        // Launch a task to run the channel reactor.
355        self.runtime
356            .spawn(async {
357                let _ = reactor.run().await;
358            })
359            .map_err(|e| Error::from_spawn("responder channel reactor", e))?;
360
361        Ok(chan)
362    }
363}
364
365impl<R: Runtime, H: TransportImplHelper> ChanBuilder<R, H>
366where
367    R: tor_rtcompat::TlsProvider<H::Stream> + Send + Sync,
368    H: Send + Sync,
369{
370    /// Perform the work of `connect_via_transport`, but without enforcing a timeout.
371    ///
372    /// Return a [`Channel`](tor_proto::channel::Channel) on success.
373    #[instrument(skip_all, level = "trace")]
374    async fn connect_no_timeout(
375        &self,
376        target: &OwnedChanTarget,
377        event_sender: Arc<Mutex<ChanMgrEventSender>>,
378        memquota: ChannelAccount,
379    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
380        use tor_rtcompat::tls::CertifiedConn;
381
382        {
383            event_sender.lock().expect("Lock poisoned").record_attempt();
384        }
385
386        // Before actually doing the connect, we need to validate the channel target based on this
387        // build outbound channel type. There are restrictions we need to apply.
388        self.validate_target(target)?;
389
390        // 1a. Negotiate the TCP connection or other stream.
391
392        // The returned PeerAddr is the actual address we are connected to.
393        let (peer_addr, stream) = self.transport.connect(target).await?;
394        // The peer could be a bridge/guard or a relay. We have to shield it right away to avoid
395        // leaking the info in the logs but we also want the info for a relay<-> relay.
396        let peer_addr = match self.outbound_chan_type() {
397            ChannelType::ClientInitiator => MaybeSensitive::sensitive(peer_addr),
398            ChannelType::RelayInitiator => MaybeSensitive::not_sensitive(peer_addr),
399            _ => return Err(Error::Internal(internal!("Unknown outbound channel type"))),
400        };
401
402        let map_ioe = |action: &'static str| {
403            let peer = peer_addr.clone();
404            move |ioe: io::Error| Error::Io {
405                action,
406                peer,
407                source: ioe.into(),
408            }
409        };
410
411        {
412            // TODO(nickm): At some point, it would be helpful to the
413            // bootstrapping logic if we could distinguish which
414            // transport just succeeded.
415            event_sender
416                .lock()
417                .expect("Lock poisoned")
418                .record_tcp_success();
419        }
420
421        // 1b. Negotiate TLS.
422
423        let hostname = rand_hostname::random_hostname(&mut rand::rng());
424
425        let tls = self
426            .tls_connector
427            .negotiate_unvalidated(stream, hostname.as_str())
428            .await
429            .map_err(map_ioe("TLS negotiation"))?;
430
431        let peer_tls_cert = tls
432            .peer_certificate()
433            .map_err(map_ioe("TLS certs"))?
434            .ok_or_else(|| Error::Internal(internal!("TLS connection with no peer certificate")))?
435            // Note: we could skip this "into_owned" if we computed any necessary digest on the
436            // certificate earlier.  That would require changing out channel negotiation APIs,
437            // though, and might not be worth it.
438            .into_owned();
439
440        {
441            event_sender
442                .lock()
443                .expect("Lock poisoned")
444                .record_tls_finished();
445        }
446
447        // Store this so we can log it in case we don't recognize it.
448        let outbound_chan_type = self.outbound_chan_type();
449        let chan = match outbound_chan_type {
450            ChannelType::ClientInitiator => {
451                self.build_client_channel(
452                    tls,
453                    peer_addr,
454                    target,
455                    &peer_tls_cert,
456                    memquota,
457                    event_sender.clone(),
458                )
459                .await?
460            }
461            #[cfg(feature = "relay")]
462            ChannelType::RelayInitiator => {
463                self.build_relay_channel(
464                    self.rate_limit(tls),
465                    peer_addr,
466                    target,
467                    &peer_tls_cert,
468                    memquota,
469                    event_sender.clone(),
470                )
471                .await?
472            }
473            _ => {
474                return Err(Error::Internal(internal!(
475                    "Unusable channel type for outbound: {outbound_chan_type}",
476                )));
477            }
478        };
479
480        event_sender
481            .lock()
482            .expect("Lock poisoned")
483            .record_handshake_done();
484
485        Ok(chan)
486    }
487
488    /// Validate the given `target` as we (a relay) are attempting to connect to another relay.
489    #[cfg(feature = "relay")]
490    fn validate_target_as_relay<CT>(&self, target: &CT) -> crate::Result<()>
491    where
492        CT: ChanTarget,
493    {
494        use tor_linkspec::HasRelayIds;
495
496        // Make sure we don't attempt to use a PT method for this relay channel.
497        if !target.chan_method().is_direct() {
498            // Return an internal error because the circuit reactor asking us to use a PT is a code
499            // flow issue, not a protocol violation.
500            return Err(Error::UnusableTarget(tor_error::bad_api_usage!(
501                "Relays don't support outbound PT channels"
502            )));
503        }
504
505        // Make sure that all addresses are allowed for an EXTEND. For instance, connecting to a
506        // local/private network for security reasons as a it could lead to network
507        // scanning by measuring latency between successful connect() and failures.
508        //
509        // If no addresses, it returns true and thus no error.
510        if !self.allow_any_addrs && !target.all_addrs_allowed_for_outgoing_channels() {
511            return Err(Error::Proto {
512                source: tor_proto::Error::ChanProto(
513                    "Target address is not allowed for outgoing channels".into(),
514                ),
515                peer: target.to_owned().into(),
516                clock_skew: None,
517            });
518        }
519
520        // Connecting to a relay as a relay without key material will fail. This should never
521        // happen hence the internal error.
522        let Some(auth_material) = &self.auth_material else {
523            return Err(Error::Internal(tor_error::bad_api_usage!(
524                "Relay initiating a channel without key auth material"
525            )));
526        };
527
528        // Any of our identities match the given target, we are connecting to ourselves, refuse.
529        if auth_material.has_any_relay_id_from(target) {
530            Err(Error::Proto {
531                source: tor_proto::Error::ChanProto("Refusing to build channel to ourself".into()),
532                peer: target.to_owned().into(),
533                clock_skew: None,
534            })
535        } else {
536            Ok(())
537        }
538    }
539
540    /// Validate the given target as in if it is fine to connect to it.
541    ///
542    ///There are several rules to follow based on the channel outbound type.
543    fn validate_target<CT>(&self, target: &CT) -> crate::Result<()>
544    where
545        CT: ChanTarget,
546    {
547        // Make sure that each address has a valid port.
548        if !target.has_all_nonzero_port() {
549            return Err(Error::Proto {
550                source: tor_proto::Error::ChanProto("Target address port is invalid".into()),
551                peer: target.to_owned().into(),
552                clock_skew: None,
553            });
554        }
555
556        // Make sure no target address is ourself including the port. A relay is allowed to connect
557        // to its IP address but on a different port. We also want to avoid a client bridge to
558        // connect back to itself.
559        #[cfg(feature = "relay")]
560        for addr in target.addrs() {
561            if self.my_addrs.contains(&addr) {
562                return Err(Error::Proto {
563                    source: tor_proto::Error::ChanProto("Target address is ours".into()),
564                    peer: target.to_owned().into(),
565                    clock_skew: None,
566                });
567            }
568        }
569
570        let chan_type = self.outbound_chan_type();
571        match chan_type {
572            // This is a client connecting to a relay.
573            ChannelType::ClientInitiator => Ok(()),
574            // This is a relay connecting to a relay.
575            #[cfg(feature = "relay")]
576            ChannelType::RelayInitiator => self.validate_target_as_relay(target),
577            // ChannelType is non_exhaustive but also we only cover outbound channels.
578            _ => Err(Error::UnusableTarget(tor_error::bad_api_usage!(
579                "Channel type can't be used as a target: {chan_type}"
580            ))),
581        }
582    }
583
584    /// Build a client channel (always initiator).
585    ///
586    /// This spawns the Reactor and return the [`tor_proto::channel::Channel`].
587    async fn build_client_channel<T>(
588        &self,
589        tls: T,
590        peer_addr: MaybeSensitive<PeerAddr>,
591        target: &OwnedChanTarget,
592        peer_tls_cert: &[u8],
593        memquota: ChannelAccount,
594        event_sender: Arc<Mutex<ChanMgrEventSender>>,
595    ) -> crate::Result<Arc<tor_proto::channel::Channel>>
596    where
597        T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
598    {
599        // Helper to map protocol level error.
600        //
601        // We are logging the `target` here as these protocol error happens during the handshake
602        // and we need to log the identities that are being tried but it will honor safe logging
603        // for the relay <-> relay case which is not ideal but a tradeoff in complexity.
604        let map_proto = |source, target: &OwnedChanTarget, clock_skew| Error::Proto {
605            source,
606            peer: target.to_logged(),
607            clock_skew,
608        };
609
610        let now = self.runtime.wallclock();
611
612        // Get the client specific channel builder.
613        let mut builder = tor_proto::ClientChannelBuilder::new();
614        builder.set_declared_method(target.chan_method());
615
616        let unverified = builder
617            .launch(
618                tls,
619                self.runtime.clone(), /* TODO provide ZST SleepProvider instead */
620                memquota,
621            )
622            .connect(|| self.runtime.wallclock())
623            .await
624            .map_err(|e| Error::from_proto_no_skew(e, target))?;
625
626        let clock_skew = unverified.clock_skew();
627        let (chan, reactor) = unverified
628            .verify(target, peer_tls_cert, Some(now))
629            .map_err(|source| match &source {
630                tor_proto::Error::HandshakeCertsExpired { .. } => {
631                    event_sender
632                        .lock()
633                        .expect("Lock poisoned")
634                        .record_handshake_done_with_skewed_clock();
635                    map_proto(source, target, Some(clock_skew))
636                }
637                _ => Error::from_proto_no_skew(source, target),
638            })?
639            .finish(peer_addr)
640            .await
641            .map_err(|e| map_proto(e, target, Some(clock_skew)))?;
642
643        // Launch a task to run the channel reactor.
644        self.runtime
645            .spawn(async {
646                let _ = reactor.run().await;
647            })
648            .map_err(|e| Error::from_spawn("client channel reactor", e))?;
649        Ok(chan)
650    }
651
652    /// Build a relay initiator channel.
653    ///
654    /// This spawns the Reactor and return the [`tor_proto::channel::Channel`].
655    #[cfg(feature = "relay")]
656    async fn build_relay_channel<T>(
657        &self,
658        tls: T,
659        peer_addr: MaybeSensitive<PeerAddr>,
660        target: &OwnedChanTarget,
661        peer_tls_cert: &[u8],
662        memquota: ChannelAccount,
663        event_sender: Arc<Mutex<ChanMgrEventSender>>,
664    ) -> crate::Result<Arc<tor_proto::channel::Channel>>
665    where
666        T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
667    {
668        let builder = tor_proto::RelayChannelBuilder::new();
669        let auth_material = self
670            .auth_material
671            .as_ref()
672            .ok_or_else(|| internal!("Unable to build relay channel without auth material"))?
673            .clone();
674
675        let create_request_handler = self.create_request_handler.as_ref().ok_or_else(|| {
676            bad_api_usage!("Can't create a relay channel without a CREATE* request handler")
677        })?;
678
679        let unverified = builder
680            .launch(
681                tls,
682                self.runtime.clone(), /* TODO provide ZST SleepProvider instead */
683                auth_material,
684                self.my_addrs.clone(),
685                target,
686                memquota,
687                Arc::clone(create_request_handler),
688            )
689            .connect(|| self.runtime.wallclock())
690            .await
691            .map_err(|e| Error::from_proto_no_skew(e, target))?;
692
693        let now = self.runtime.wallclock();
694        let clock_skew = unverified.clock_skew();
695        let (chan, reactor) = unverified
696            .verify(target, peer_tls_cert, Some(now))
697            .map_err(|source| match &source {
698                tor_proto::Error::HandshakeCertsExpired { .. } => {
699                    event_sender
700                        .lock()
701                        .expect("Lock poisoned")
702                        .record_handshake_done_with_skewed_clock();
703                    Error::Proto {
704                        source,
705                        peer: target.to_logged(),
706                        clock_skew: Some(clock_skew),
707                    }
708                }
709                _ => Error::from_proto_no_skew(source, target),
710            })?
711            // Peer address is not sensitive as this is a relay<->relay connection.
712            .finish(peer_addr.inner())
713            .await
714            .map_err(|source| Error::Proto {
715                source,
716                peer: target.to_logged(),
717                clock_skew: Some(clock_skew),
718            })?;
719
720        // Launch a task to run the channel reactor.
721        self.runtime
722            .spawn(async {
723                let _ = reactor.run().await;
724            })
725            .map_err(|e| Error::from_spawn("relay channel reactor", e))?;
726
727        Ok(chan)
728    }
729}
730
731impl crate::mgr::AbstractChannel for tor_proto::channel::Channel {
732    fn is_canonical(&self) -> bool {
733        self.is_canonical()
734    }
735    fn is_canonical_to_peer(&self) -> bool {
736        self.is_canonical_to_peer()
737    }
738    fn is_usable(&self) -> bool {
739        !self.is_closing()
740    }
741    fn duration_unused(&self) -> Option<Duration> {
742        self.duration_unused()
743    }
744    fn reparameterize(
745        &self,
746        updates: Arc<ChannelPaddingInstructionsUpdates>,
747    ) -> tor_proto::Result<()> {
748        tor_proto::channel::Channel::reparameterize(self, updates)
749    }
750    fn reparameterize_kist(&self, kist_params: KistParams) -> tor_proto::Result<()> {
751        tor_proto::channel::Channel::reparameterize_kist(self, kist_params)
752    }
753    fn engage_padding_activities(&self) {
754        tor_proto::channel::Channel::engage_padding_activities(self);
755    }
756}
757
758#[cfg(test)]
759mod test {
760    // @@ begin test lint list maintained by maint/add_warning @@
761    #![allow(clippy::bool_assert_comparison)]
762    #![allow(clippy::clone_on_copy)]
763    #![allow(clippy::dbg_macro)]
764    #![allow(clippy::mixed_attributes_style)]
765    #![allow(clippy::print_stderr)]
766    #![allow(clippy::print_stdout)]
767    #![allow(clippy::single_char_pattern)]
768    #![allow(clippy::unwrap_used)]
769    #![allow(clippy::unchecked_time_subtraction)]
770    #![allow(clippy::useless_vec)]
771    #![allow(clippy::needless_pass_by_value)]
772    #![allow(clippy::string_slice)] // See arti#2571
773    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
774    use super::*;
775    use crate::{
776        Result,
777        mgr::{AbstractChannel, AbstractChannelFactory},
778    };
779    use futures::StreamExt as _;
780    use std::net::SocketAddr;
781    use std::time::{Duration, SystemTime};
782    use tor_linkspec::{ChannelMethod, HasRelayIds, RelayIdType};
783    use tor_llcrypto::pk::ed25519::Ed25519Identity;
784    use tor_llcrypto::pk::rsa::RsaIdentity;
785    use tor_proto::channel::Channel;
786    use tor_proto::memquota::{ChannelAccount, SpecificAccount as _};
787    use tor_rtcompat::{NetStreamListener, test_with_one_runtime};
788    use tor_rtmock::{io::LocalStream, net::MockNetwork};
789
790    #[allow(deprecated)] // TODO #1885
791    use tor_rtmock::MockSleepRuntime;
792
793    // Make sure that the builder can build a real channel.  To test
794    // this out, we set up a listener that pretends to have the right
795    // IP, fake the current time, and use a canned response from
796    // [`testing::msgs`] crate.
797    #[test]
798    fn build_ok() -> Result<()> {
799        use crate::testing::msgs;
800        let orport: SocketAddr = msgs::ADDR.parse().unwrap();
801        let ed: Ed25519Identity = msgs::ED_ID.into();
802        let rsa: RsaIdentity = msgs::RSA_ID.into();
803        let client_addr = "192.0.2.17".parse().unwrap();
804        let tls_cert = msgs::X509_CERT.into();
805        let target = OwnedChanTarget::builder()
806            .addrs(vec![orport])
807            .method(ChannelMethod::Direct(vec![orport]))
808            .ed_identity(ed)
809            .rsa_identity(rsa)
810            .build()
811            .unwrap();
812        let now = SystemTime::UNIX_EPOCH + Duration::new(msgs::NOW, 0);
813
814        test_with_one_runtime!(|rt| async move {
815            // Stub out the internet so that this connection can work.
816            let network = MockNetwork::new();
817
818            // Set up a client runtime with a given IP
819            let client_rt = network
820                .builder()
821                .add_address(client_addr)
822                .runtime(rt.clone());
823            // Mock the current time too
824            #[allow(deprecated)] // TODO #1885
825            let client_rt = MockSleepRuntime::new(client_rt);
826
827            // Set up a relay runtime with a different IP
828            let relay_rt = network
829                .builder()
830                .add_address(orport.ip())
831                .runtime(rt.clone());
832
833            // open a fake TLS listener and be ready to handle a request.
834            let lis = relay_rt.mock_net().listen_tls(&orport, tls_cert).unwrap();
835
836            // Tell the client to believe in a different timestamp.
837            client_rt.jump_to(now);
838
839            // Create the channel builder that we want to test.
840            let transport = crate::transport::DefaultTransport::new(client_rt.clone(), None);
841            let builder = ChanBuilder::new_client(client_rt, transport);
842
843            let (r1, r2): (Result<Arc<Channel>>, Result<LocalStream>) = futures::join!(
844                async {
845                    // client-side: build a channel!
846                    builder
847                        .build_channel(
848                            &target,
849                            BootstrapReporter::fake(),
850                            ChannelAccount::new_noop(),
851                        )
852                        .await
853                },
854                async {
855                    // relay-side: accept the channel
856                    // (and pretend to know what we're doing).
857                    let (mut con, addr) = lis
858                        .incoming()
859                        .next()
860                        .await
861                        .expect("Closed?")
862                        .expect("accept failed");
863                    assert_eq!(client_addr, addr.ip());
864                    crate::testing::answer_channel_req(&mut con)
865                        .await
866                        .expect("answer failed");
867                    Ok(con)
868                }
869            );
870
871            let chan = r1.unwrap();
872            assert_eq!(chan.identity(RelayIdType::Ed25519), Some((&ed).into()));
873            assert!(chan.is_usable());
874            // In theory, time could pass here, so we can't just use
875            // "assert_eq!(dur_unused, dur_unused2)".
876            let dur_unused = Channel::duration_unused(&chan);
877            let dur_unused_2 = AbstractChannel::duration_unused(chan.as_ref());
878            let dur_unused_3 = Channel::duration_unused(&chan);
879            assert!(dur_unused.unwrap() <= dur_unused_2.unwrap());
880            assert!(dur_unused_2.unwrap() <= dur_unused_3.unwrap());
881
882            r2.unwrap();
883            Ok(())
884        })
885    }
886
887    // TODO: Write tests for timeout logic, once there is smarter logic.
888}