1
//! Handler for EXTEND2 cells.
2

            
3
use super::{CircEvent, ExtendResult, Outbound};
4

            
5
use crate::Error;
6
use crate::circuit::UniqId;
7
use crate::circuit::create::{Create2Wrap, CreateHandshakeWrap};
8
use crate::peer::PeerInfo;
9
use crate::relay::channel_provider::{ChannelProvider, ChannelResult, OutboundChanSender};
10
use crate::relay::reactor::CircuitAccount;
11
use crate::util::err::ReactorError;
12
use tor_cell::chancell::{AnyChanCell, CircId};
13
use tor_cell::relaycell::UnparsedRelayMsg;
14
use tor_cell::relaycell::msg::{Extend2, Extended2};
15
use tor_error::{internal, into_internal, warn_report};
16
use tor_linkspec::decode::Strictness;
17
use tor_linkspec::{HasRelayIds, OwnedChanTarget, OwnedChanTargetBuilder};
18
use tor_rtcompat::{Runtime, SpawnExt as _};
19

            
20
use futures::channel::mpsc;
21
use futures::{SinkExt as _, StreamExt as _};
22
use tracing::{debug, trace};
23

            
24
use std::result::Result as StdResult;
25
use std::sync::Arc;
26

            
27
/// Helper for handling EXTEND2 cells.
28
pub(super) struct ExtendRequestHandler {
29
    /// An identifier for logging about this handler.
30
    unique_id: UniqId,
31
    /// The circuit identifier on the inbound Tor channel.
32
    circ_id: CircId,
33
    /// A handle to a [`ChannelProvider`], used for initiating outgoing Tor channels.
34
    ///
35
    /// Note: all circuit reactors of a relay need to be initialized
36
    /// with the *same* underlying Tor channel provider (`ChanMgr`),
37
    /// to enable the reuse of existing Tor channels where possible.
38
    chan_provider: Arc<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
39
    /// The identity of the inbound relay (the previous hop).
40
    inbound_peer: Arc<PeerInfo>,
41
    /// A stream of events to be read from the main loop of the reactor.
42
    event_tx: mpsc::Sender<CircEvent>,
43
    /// Memory quota account
44
    memquota: CircuitAccount,
45
}
46

            
47
impl ExtendRequestHandler {
48
    /// Create a new [`ExtendRequestHandler`].
49
32
    pub(super) fn new(
50
32
        unique_id: UniqId,
51
32
        circ_id: CircId,
52
32
        chan_provider: Arc<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
53
32
        inbound_peer: Arc<PeerInfo>,
54
32
        event_tx: mpsc::Sender<CircEvent>,
55
32
        memquota: CircuitAccount,
56
32
    ) -> Self {
57
32
        Self {
58
32
            unique_id,
59
32
            circ_id,
60
32
            chan_provider,
61
32
            inbound_peer,
62
32
            event_tx,
63
32
            memquota,
64
32
        }
65
32
    }
66

            
67
    /// Handle an EXTEND2 cell.
68
    ///
69
    /// This spawns a background task for dealing with the circuit extension,
70
    /// which then reports back the result via the [`Self::event_tx`] MPSC stream.
71
    /// Note that this MPSC stream is polled from the `DecryptingReactor` main loop,
72
    /// and each `CircEvent` is passed back to [`Forward`](super::Forward)'s
73
    /// [`DecryptingReactorInner::handle_event`](crate::circuit::reactor::decrypt::DecryptingReactorInner::handle_event)
74
    /// implementation for handling.
75
10
    pub(super) fn handle_extend2<R: Runtime>(
76
10
        self,
77
10
        runtime: &R,
78
10
        early: bool,
79
10
        msg: UnparsedRelayMsg,
80
10
    ) -> StdResult<(), ReactorError> {
81
        // TODO(relay): this should be allowed if the AllowNonearlyExtend consensus
82
        // param is set (arti#2349)
83
10
        if !early {
84
2
            return Err(Error::CircProto("got EXTEND2 in a RELAY cell?!".into()).into());
85
8
        }
86

            
87
        let to_bytes_err = |e| Error::from_bytes_err(e, "EXTEND2 message");
88

            
89
8
        let extend2 = msg.decode::<Extend2>().map_err(to_bytes_err)?.into_msg();
90

            
91
8
        let chan_target = OwnedChanTargetBuilder::from_encoded_linkspecs(
92
8
            Strictness::Standard,
93
8
            extend2.linkspecs(),
94
8
        )
95
        .map_err(|err| Error::LinkspecDecodeErr {
96
            object: "EXTEND2",
97
            err,
98
        })?
99
        .build()
100
        .map_err(|_| {
101
            // TODO: should we include the error in the circ proto error context?
102
            Error::CircProto("Invalid channel target".into())
103
        })?;
104

            
105
8
        if chan_target.has_any_relay_id_from(&*self.inbound_peer) {
106
2
            return Err(Error::CircProto("Cannot extend circuit to previous hop".into()).into());
107
6
        }
108

            
109
        // Note: we don't do any further validation on the EXTEND2 here,
110
        // under the assumption it will be handled by the ChannelProvider.
111

            
112
6
        let (chan_tx, chan_rx) = mpsc::unbounded();
113

            
114
6
        let chan_tx = OutboundChanSender(chan_tx);
115
6
        Arc::clone(&self.chan_provider).get_or_launch(self.unique_id, chan_target, chan_tx)?;
116

            
117
6
        let mut result_tx = self.event_tx.clone();
118
6
        let rt = runtime.clone();
119
6
        let unique_id = self.unique_id;
120
6
        let circ_id = self.circ_id;
121
6
        let memquota = self.memquota.clone();
122

            
123
        // TODO(relay): because we dispatch this the entire EXTEND2 handling to a background task,
124
        // we don't really need the channel provider to send us the outcome via an MPSC channel,
125
        // because get_or_launch() could simply be async (it wouldn't block the reactor,
126
        // because it runs in another task). Maybe we need to rethink the ChannelProvider API?
127
6
        runtime
128
6
            .spawn(async move {
129
                let res =
130
6
                    Self::extend_circuit(rt, unique_id, circ_id, extend2, chan_rx, memquota).await;
131

            
132
                // Discard the error if the reactor shut down before we had
133
                // a chance to complete the extend handshake
134
6
                let _ = result_tx.send(CircEvent::ExtendResult(res)).await;
135
6
            })
136
6
            .map_err(into_internal!("failed to spawn extend task?!"))?;
137

            
138
6
        Ok(())
139
10
    }
140

            
141
    /// Extend this circuit on the channel received on `chan_rx`.
142
    ///
143
    /// Note: this gets spawned in a background task from
144
    /// [`Self::handle_extend2`] so as not to block the reactor main loop.
145
6
    async fn extend_circuit<R: Runtime>(
146
6
        _runtime: R,
147
6
        unique_id: UniqId,
148
6
        inbound_circ_id: CircId,
149
6
        extend2: Extend2,
150
6
        mut chan_rx: mpsc::UnboundedReceiver<ChannelResult>,
151
6
        memquota: CircuitAccount,
152
6
    ) -> StdResult<ExtendResult, ReactorError> {
153
        // We expect the channel build timeout to be enforced by the ChannelProvider
154
6
        let chan_res = chan_rx
155
6
            .next()
156
6
            .await
157
            .ok_or_else(|| internal!("channel provider task exited"))?;
158

            
159
6
        let channel = match chan_res {
160
6
            Ok(c) => c,
161
            Err(e) => {
162
                warn_report!(e, "Failed to launch outgoing channel");
163
                // Note: retries are handled within
164
                // get_or_launch(), so if we receive an
165
                // error at this point, we need to bail
166
                return Err(ReactorError::Shutdown);
167
            }
168
        };
169

            
170
6
        debug!(
171
            circ_uniq_id = %unique_id,
172
            backward_circ_id = %inbound_circ_id,
173
            "Launched channel to the next hop"
174
        );
175

            
176
        // Now that we finally have a forward Tor channel,
177
        // it's time to forward the onion skin and extend the circuit...
178
        //
179
        // Note: the only reason we need to await here is because internally
180
        // new_outbound_circ() sends a control message to the channel reactor handles,
181
        // which is handled asynchronously. In practice, we're not actually waiting on
182
        // the network here, so in theory we shouldn't need a timeout for this operation.
183
        let (circ_id, outbound_chan_rx, createdreceiver) =
184
6
            channel.new_outbound_circ(memquota).await?;
185

            
186
        // We have allocated a circuit in the channel's circmap,
187
        // now it's time to send the CREATE2 and wait for the response.
188
6
        let create2_wrap = Create2Wrap {
189
6
            handshake_type: extend2.handshake_type(),
190
6
        };
191
6
        let create2 = create2_wrap.to_chanmsg(extend2.handshake().into());
192

            
193
        // Time to write the CREATE2 to the outbound channel...
194
6
        let mut outbound_chan_tx = channel.sender();
195
6
        let cell = AnyChanCell::new(Some(circ_id), create2);
196

            
197
6
        trace!(
198
            circ_uniq_id = %unique_id,
199
            forward_circ_id = %circ_id,
200
            "Sending CREATE2 to the next hop"
201
        );
202

            
203
6
        outbound_chan_tx.send((cell, None)).await?;
204

            
205
        // TODO(relay): we need a timeout here, otherwise we might end up waiting forever
206
        // for the CREATED2 to arrive.
207
        //
208
        // There is some complexity here, see
209
        // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/3648#note_3340125
210
6
        let response = createdreceiver.await.map_err(|_| {
211
            // This can happen under "normal" circumstances,
212
            // if the outbound channel reactor shuts down abruptly
213
            // (for example, if the peer closes the connection).
214
            ReactorError::Shutdown
215
        })?;
216

            
217
6
        trace!(
218
            circ_uniq_id = %unique_id,
219
            forward_circ_id = %circ_id,
220
            "Got CREATED2 response from next hop"
221
        );
222

            
223
6
        let outbound = Outbound {
224
6
            circ_id,
225
6
            channel: Arc::clone(&channel),
226
6
            outbound_chan_tx,
227
6
        };
228

            
229
        // If we reach this point, it means we have extended
230
        // the circuit by one hop, so we need to take the contents
231
        // of the CREATE/CREATED2 cell, and package an EXTEND/EXTENDED2
232
        // to send back to the client.
233
6
        let created2_body = create2_wrap.decode_chanmsg(response)?;
234
6
        let extended2 = Extended2::new(created2_body);
235

            
236
6
        Ok(ExtendResult {
237
6
            extended2,
238
6
            outbound,
239
6
            outbound_chan_rx,
240
6
        })
241
6
    }
242
}