1
//! Client-specific types and implementation.
2

            
3
pub mod channel;
4
pub mod circuit;
5
pub mod stream;
6

            
7
#[cfg(feature = "rpc")]
8
pub mod rpc;
9

            
10
#[cfg(feature = "send-control-msg")]
11
pub(crate) mod msghandler;
12
pub(crate) mod reactor;
13

            
14
use derive_deftly::Deftly;
15
use oneshot_fused_workaround as oneshot;
16
use std::net::IpAddr;
17
use std::num::NonZero;
18
use std::sync::Arc;
19
use tracing::instrument;
20

            
21
use crate::circuit::UniqId;
22
use crate::circuit::circhop::ReactorStreamComponents;
23
#[cfg(feature = "circ-padding-manual")]
24
pub use crate::client::circuit::padding::{
25
    CircuitPadder, CircuitPadderConfig, CircuitPadderConfigError,
26
};
27
use crate::client::stream::{
28
    DataStream, OutboundDataCmdChecker, ResolveCmdChecker, ResolveStream, StreamParameters,
29
};
30
use crate::congestion::sendme::StreamRecvWindow;
31
use crate::crypto::cell::HopNum;
32
use crate::memquota::{SpecificAccount as _, StreamAccount};
33
use crate::stream::STREAM_READER_BUFFER;
34
use crate::stream::cmdcheck::AnyCmdChecker;
35
use crate::stream::flow_ctrl::xon_xoff::reader::XonXoffReaderCtrl;
36
use crate::stream::{RECV_WINDOW_INIT, StreamComponents, StreamReceiver, StreamTarget, Tunnel};
37
use crate::{Error, ResolveError, Result};
38
use circuit::{ClientCirc, Path};
39
use reactor::{CtrlCmd, CtrlMsg, FlowCtrlMsg, MetaCellHandler};
40

            
41
use tor_cell::relaycell::StreamId;
42
use tor_cell::relaycell::flow_ctrl::XonKBpsEwma;
43
use tor_cell::relaycell::msg::{
44
    AnyRelayMsg, Begin, BeginAddr, BeginHostname, Resolve, Resolved, ResolvedVal,
45
};
46
use tor_error::bad_api_usage;
47
use tor_linkspec::OwnedChanTarget;
48
use tor_memquota::derive_deftly_template_HasMemoryCost;
49
use tor_memquota::mq_queue::{ChannelSpec as _, MpscSpec};
50

            
51
#[cfg(feature = "hs-service")]
52
use crate::stream::{IncomingCmdChecker, IncomingStream, StreamReqInfo};
53

            
54
#[cfg(feature = "send-control-msg")]
55
use msghandler::{MsgHandler, UserMsgHandler};
56

            
57
/// Handle to use during an ongoing protocol exchange with a circuit's last hop
58
///
59
/// This is obtained from [`ClientTunnel::start_conversation`],
60
/// and used to send messages to the last hop relay.
61
//
62
// TODO(conflux): this should use ClientTunnel, and it should be moved into
63
// the tunnel module.
64
#[cfg(feature = "send-control-msg")]
65
pub struct Conversation<'r>(&'r ClientTunnel);
66

            
67
#[cfg(feature = "send-control-msg")]
68
impl Conversation<'_> {
69
    /// Send a protocol message as part of an ad-hoc exchange
70
    ///
71
    /// Responses are handled by the `UserMsgHandler` set up
72
    /// when the `Conversation` was created.
73
    pub async fn send_message(&self, msg: tor_cell::relaycell::msg::AnyRelayMsg) -> Result<()> {
74
        self.send_internal(Some(msg), None).await
75
    }
76

            
77
    /// Send a `SendMsgAndInstallHandler` to the reactor and wait for the outcome
78
    ///
79
    /// The guts of `start_conversation` and `Conversation::send_msg`
80
    pub(crate) async fn send_internal(
81
        &self,
82
        msg: Option<tor_cell::relaycell::msg::AnyRelayMsg>,
83
        handler: Option<Box<dyn MetaCellHandler + Send + 'static>>,
84
    ) -> Result<()> {
85
        let msg = msg.map(|msg| tor_cell::relaycell::AnyRelayMsgOuter::new(None, msg));
86
        let (sender, receiver) = oneshot::channel();
87

            
88
        let ctrl_msg = CtrlMsg::SendMsgAndInstallHandler {
89
            msg,
90
            handler,
91
            sender,
92
        };
93
        self.0
94
            .circ
95
            .control
96
            .unbounded_send(ctrl_msg)
97
            .map_err(|_| Error::CircuitClosed)?;
98

            
99
        receiver.await.map_err(|_| Error::CircuitClosed)?
100
    }
101
}
102

            
103
/// A low-level client tunnel API.
104
///
105
/// This is a communication channel to the tunnel reactor, which manages 1 or more circuits.
106
///
107
/// Note: the tor-circmgr crates wrap this type in specialized *Tunnel types exposing only the
108
/// desired subset of functionality depending on purpose and path size.
109
///
110
/// Some API calls are for single path and some for multi path. A check with the underlying reactor
111
/// is done preventing for instance multi path calls to be used on a single path. Top level types
112
/// should prevent this and thus this object should never be used directly.
113
#[derive(Debug)]
114
#[cfg_attr(
115
    feature = "rpc",
116
    derive(derive_deftly::Deftly),
117
    derive_deftly(tor_rpcbase::templates::Object)
118
)]
119
#[allow(dead_code)] // TODO(conflux)
120
pub struct ClientTunnel {
121
    /// The underlying handle to the reactor.
122
    circ: ClientCirc,
123
}
124

            
125
impl ClientTunnel {
126
    /// Return a handle to the `ClientCirc` of this `ClientTunnel`, if the tunnel is a single
127
    /// circuit tunnel.
128
    ///
129
    /// Returns an error if the tunnel has more than one circuit.
130
218
    pub fn as_single_circ(&self) -> Result<&ClientCirc> {
131
218
        if self.circ.is_multi_path {
132
2
            Err(bad_api_usage!("Single circuit getter on multi path tunnel"))?;
133
216
        }
134
216
        Ok(&self.circ)
135
218
    }
136

            
137
    /// Return the channel target of the first hop.
138
    ///
139
    /// Can only be used for single path tunnel.
140
    pub fn first_hop(&self) -> Result<OwnedChanTarget> {
141
        self.as_single_circ()?.first_hop()
142
    }
143

            
144
    /// Return true if the circuit reactor is closed meaning the circuit is unusable for both
145
    /// receiving or sending.
146
64
    pub fn is_closed(&self) -> bool {
147
64
        self.circ.is_closing()
148
64
    }
149

            
150
    /// Return a [`TargetHop`] representing precisely the last hop of the circuit as in set as a
151
    /// HopLocation with its id and hop number.
152
    ///
153
    /// Return an error if there is no last hop.
154
    pub fn last_hop(&self) -> Result<TargetHop> {
155
        let uniq_id = self.unique_id();
156
        let hop_num = self
157
            .circ
158
            .mutable
159
            .last_hop_num(uniq_id)?
160
            .ok_or_else(|| bad_api_usage!("no last hop"))?;
161
        Ok((uniq_id, hop_num).into())
162
    }
163

            
164
    /// Return a description of the last hop of the tunnel.
165
    ///
166
    /// Return None if the last hop is virtual; return an error
167
    /// if the tunnel has no circuits, or all of its circuits are zero length.
168
    ///
169
    ///
170
    /// # Panics
171
    ///
172
    /// Panics if there is no last hop.  (This should be impossible outside of
173
    /// the tor-proto crate, but within the crate it's possible to have a
174
    /// circuit with no hops.)
175
    pub fn last_hop_info(&self) -> Result<Option<OwnedChanTarget>> {
176
        self.circ.last_hop_info()
177
    }
178

            
179
    /// Return the number of hops this tunnel as. Fail for a multi path.
180
48
    pub fn n_hops(&self) -> Result<usize> {
181
48
        self.as_single_circ()?.n_hops()
182
48
    }
183

            
184
    /// Return the [`Path`] objects describing all the hops
185
    /// of all the circuits in this tunnel.
186
    pub fn all_paths(&self) -> Vec<Arc<Path>> {
187
        self.circ.all_paths()
188
    }
189

            
190
    /// Return a representation of the Paths for all the circuits in this tunnel,
191
    /// as a map from each circuits' UniqId to its path.
192
    ///
193
    /// This is only exposed for the RPC subsystem, where it is documented that the
194
    /// format of `UniqId` is not stable.
195
    #[cfg(feature = "rpc")]
196
    pub(crate) fn tagged_paths(&self) -> std::collections::HashMap<UniqId, Arc<Path>> {
197
        self.circ.mutable.tagged_paths()
198
    }
199

            
200
    /// Return a process-unique identifier for this tunnel.
201
    ///
202
    /// Returns the reactor unique ID of the main reactor.
203
64
    pub fn unique_id(&self) -> UniqId {
204
64
        self.circ.unique_id()
205
64
    }
206

            
207
    /// Return the time at which this tunnel last had any open streams.
208
    ///
209
    /// Returns `None` if this tunnel has never had any open streams,
210
    /// or if it currently has open streams.
211
    ///
212
    /// NOTE that the Instant returned by this method is not affected by
213
    /// any runtime mocking; it is the output of an ordinary call to
214
    /// `Instant::now()`.
215
    pub async fn disused_since(&self) -> Result<Option<web_time_compat::Instant>> {
216
        self.circ.disused_since().await
217
    }
218

            
219
    /// Return a future that will resolve once the underlying circuit reactor has closed.
220
    ///
221
    /// Note that this method does not itself cause the tunnel to shut down.
222
    pub fn wait_for_close(
223
        self: &Arc<Self>,
224
    ) -> impl futures::Future<Output = ()> + Send + Sync + 'static + use<> {
225
        self.circ.wait_for_close()
226
    }
227

            
228
    /// Single-path tunnel only. Multi path onion service is not supported yet.
229
    ///
230
    /// Tell this tunnel to begin allowing the final hop of the tunnel to try
231
    /// to create new Tor streams, and to return those pending requests in an
232
    /// asynchronous stream.
233
    ///
234
    /// Ordinarily, these requests are rejected.
235
    ///
236
    /// There can only be one [`Stream`](futures::Stream) of this type created on a given tunnel.
237
    /// If a such a [`Stream`](futures::Stream) already exists, this method will return
238
    /// an error.
239
    ///
240
    /// After this method has been called on a tunnel, the tunnel is expected
241
    /// to receive requests of this type indefinitely, until it is finally closed.
242
    /// If the `Stream` is dropped, the next request on this tunnel will cause it to close.
243
    ///
244
    /// Only onion services (and eventually) exit relays should call this
245
    /// method.
246
    //
247
    // TODO: Someday, we might want to allow a stream request handler to be
248
    // un-registered.  However, nothing in the Tor protocol requires it.
249
    //
250
    // Any incoming request handlers installed on the other circuits
251
    // (which are shutdown using CtrlCmd::ShutdownAndReturnCircuit)
252
    // will be discarded (along with the reactor of that circuit)
253
    #[cfg(feature = "hs-service")]
254
    #[allow(unreachable_code, unused_variables)] // TODO(conflux)
255
32
    pub async fn allow_stream_requests<'a, FILT>(
256
32
        self: &Arc<Self>,
257
32
        allow_commands: &'a [tor_cell::relaycell::RelayCmd],
258
32
        hop: TargetHop,
259
32
        filter: FILT,
260
32
    ) -> Result<impl futures::Stream<Item = IncomingStream> + use<'a, FILT>>
261
32
    where
262
32
        FILT: crate::stream::IncomingStreamRequestFilter + 'a,
263
32
    {
264
        use futures::stream::StreamExt;
265

            
266
        /// The size of the channel receiving IncomingStreamRequestContexts.
267
        const INCOMING_BUFFER: usize = STREAM_READER_BUFFER;
268

            
269
        // TODO(#2002): support onion service conflux
270
32
        let circ = self.as_single_circ().map_err(tor_error::into_internal!(
271
32
            "Cannot allow stream requests on a multi-path tunnel"
272
32
        ))?;
273

            
274
30
        let time_prov = circ.time_provider.clone();
275
30
        let cmd_checker = IncomingCmdChecker::new_any(allow_commands);
276
30
        let (incoming_sender, incoming_receiver) = MpscSpec::new(INCOMING_BUFFER)
277
30
            .new_mq(time_prov.clone(), circ.memquota.as_raw_account())?;
278
30
        let (tx, rx) = oneshot::channel();
279

            
280
30
        circ.command
281
30
            .unbounded_send(CtrlCmd::AwaitStreamRequest {
282
30
                cmd_checker,
283
30
                incoming_sender,
284
30
                hop,
285
30
                done: tx,
286
30
                filter: Box::new(filter),
287
30
            })
288
            .map_err(|_| Error::CircuitClosed)?;
289

            
290
        // Check whether the AwaitStreamRequest was processed successfully.
291
30
        rx.await.map_err(|_| Error::CircuitClosed)??;
292

            
293
24
        let allowed_hop_loc: HopLocation = match hop {
294
24
            TargetHop::Hop(loc) => Some(loc),
295
            _ => None,
296
        }
297
        .ok_or_else(|| bad_api_usage!("Expected TargetHop with HopLocation"))?;
298

            
299
24
        let tunnel = self.clone();
300
24
        Ok(incoming_receiver.map(move |req_ctx| {
301
            let StreamReqInfo {
302
                req,
303
                stream_id,
304
                hop,
305
                stream_components:
306
                    ReactorStreamComponents {
307
                        stream_inbound_rx,
308
                        stream_outbound_tx,
309
                        rate_limit_rx,
310
                        drain_rate_request_rx,
311
                    },
312
                memquota,
313
                relay_cell_format,
314
18
            } = req_ctx;
315

            
316
            // We already enforce this in handle_incoming_stream_request; this
317
            // assertion is just here to make sure that we don't ever
318
            // accidentally remove or fail to enforce that check, since it is
319
            // security-critical.
320
18
            assert_eq!(Some(allowed_hop_loc), hop);
321

            
322
            // TODO(#2002): figure out what this is going to look like
323
            // for onion services (perhaps we should forbid this function
324
            // from being called on a multipath circuit?)
325
            //
326
            // See also:
327
            // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/3002#note_3200937
328
18
            let target = StreamTarget {
329
18
                tunnel: Tunnel::Client(Arc::clone(&tunnel)),
330
18
                tx: stream_outbound_tx,
331
18
                hop: Some(allowed_hop_loc),
332
18
                stream_id,
333
18
                relay_cell_format,
334
18
                rate_limit_stream: rate_limit_rx,
335
18
            };
336

            
337
            // can be used to build a reader that supports XON/XOFF flow control
338
            let xon_xoff_reader_ctrl =
339
18
                XonXoffReaderCtrl::new(drain_rate_request_rx, target.clone());
340

            
341
18
            let reader = StreamReceiver {
342
18
                target: target.clone(),
343
18
                receiver: stream_inbound_rx,
344
18
                recv_window: StreamRecvWindow::new(RECV_WINDOW_INIT),
345
18
                ended: false,
346
18
            };
347

            
348
18
            let components = StreamComponents {
349
18
                stream_receiver: reader,
350
18
                target,
351
18
                memquota,
352
18
                xon_xoff_reader_ctrl,
353
18
            };
354

            
355
18
            IncomingStream::new(time_prov.clone(), req, components)
356
18
        }))
357
32
    }
358

            
359
    /// Single and Multi path helper, used to begin a stream.
360
    ///
361
    /// This function allocates a stream ID, and sends the message
362
    /// (like a BEGIN or RESOLVE), but doesn't wait for a response.
363
    ///
364
    /// The caller will typically want to see the first cell in response,
365
    /// to see whether it is e.g. an END or a CONNECTED.
366
48
    async fn begin_stream_impl(
367
48
        self: &Arc<Self>,
368
48
        begin_msg: AnyRelayMsg,
369
48
        cmd_checker: AnyCmdChecker,
370
48
    ) -> Result<StreamComponents> {
371
        // TODO: Possibly this should take a hop, rather than just
372
        // assuming it's the last hop.
373
48
        let hop = TargetHop::LastHop;
374

            
375
48
        let memquota = StreamAccount::new(self.circ.mq_account())?;
376
48
        let (tx, rx) = oneshot::channel();
377

            
378
48
        self.circ
379
48
            .control
380
48
            .unbounded_send(CtrlMsg::BeginStream {
381
48
                hop,
382
48
                message: begin_msg,
383
48
                memquota: memquota.clone(),
384
48
                done: tx,
385
48
                cmd_checker,
386
48
            })
387
            .map_err(|_| Error::CircuitClosed)?;
388

            
389
        let (stream_id, hop, relay_cell_format, stream_components) =
390
48
            rx.await.map_err(|_| Error::CircuitClosed)??;
391

            
392
        // Destructure so that we don't forget to use any fields.
393
        let ReactorStreamComponents {
394
            stream_inbound_rx,
395
            stream_outbound_tx,
396
            rate_limit_rx,
397
            drain_rate_request_rx,
398
48
        } = stream_components;
399

            
400
48
        let target = StreamTarget {
401
48
            tunnel: Tunnel::Client(self.clone()),
402
48
            tx: stream_outbound_tx,
403
48
            hop: Some(hop),
404
48
            stream_id,
405
48
            relay_cell_format,
406
48
            rate_limit_stream: rate_limit_rx,
407
48
        };
408

            
409
        // can be used to build a reader that supports XON/XOFF flow control
410
48
        let xon_xoff_reader_ctrl = XonXoffReaderCtrl::new(drain_rate_request_rx, target.clone());
411

            
412
48
        let stream_receiver = StreamReceiver {
413
48
            target: target.clone(),
414
48
            receiver: stream_inbound_rx,
415
48
            recv_window: StreamRecvWindow::new(RECV_WINDOW_INIT),
416
48
            ended: false,
417
48
        };
418

            
419
48
        let components = StreamComponents {
420
48
            stream_receiver,
421
48
            target,
422
48
            memquota,
423
48
            xon_xoff_reader_ctrl,
424
48
        };
425

            
426
48
        Ok(components)
427
48
    }
428

            
429
    /// Install a [`CircuitPadder`] at the listed `hop`.
430
    ///
431
    /// Replaces any previous padder installed at that hop.
432
    #[cfg(feature = "circ-padding-manual")]
433
    pub async fn start_padding_at_hop(
434
        self: &Arc<Self>,
435
        hop: HopLocation,
436
        padder: CircuitPadder,
437
    ) -> Result<()> {
438
        self.circ.set_padder_impl(hop, Some(padder)).await
439
    }
440

            
441
    /// Remove any [`CircuitPadder`] at the listed `hop`.
442
    ///
443
    /// Does nothing if there was not a padder installed there.
444
    #[cfg(feature = "circ-padding-manual")]
445
    pub async fn stop_padding_at_hop(self: &Arc<Self>, hop: HopLocation) -> Result<()> {
446
        self.circ.set_padder_impl(hop, None).await
447
    }
448

            
449
    /// Start a DataStream (anonymized connection) to the given
450
    /// address and port, using a BEGIN cell.
451
48
    async fn begin_data_stream(
452
48
        self: &Arc<Self>,
453
48
        msg: AnyRelayMsg,
454
48
        optimistic: bool,
455
48
    ) -> Result<DataStream> {
456
48
        let components = self
457
48
            .begin_stream_impl(msg, OutboundDataCmdChecker::new_any())
458
48
            .await?;
459

            
460
        let StreamComponents {
461
            stream_receiver,
462
            target,
463
            memquota,
464
            xon_xoff_reader_ctrl,
465
48
        } = components;
466

            
467
48
        let mut stream = DataStream::new(
468
48
            self.circ.time_provider.clone(),
469
48
            stream_receiver,
470
48
            xon_xoff_reader_ctrl,
471
48
            target,
472
48
            memquota,
473
48
        );
474
48
        if !optimistic {
475
42
            stream.wait_for_connection().await?;
476
6
        }
477
48
        Ok(stream)
478
48
    }
479

            
480
    /// Single and multi path helper.
481
    ///
482
    /// Start a stream to the given address and port, using a BEGIN
483
    /// cell.
484
    ///
485
    /// The use of a string for the address is intentional: you should let
486
    /// the remote Tor relay do the hostname lookup for you.
487
    #[instrument(level = "trace", skip_all)]
488
42
    pub async fn begin_stream(
489
42
        self: &Arc<Self>,
490
42
        target: &str,
491
42
        port: u16,
492
42
        parameters: Option<StreamParameters>,
493
42
    ) -> Result<DataStream> {
494
        let parameters = parameters.unwrap_or_default();
495
        let begin_flags = parameters.begin_flags();
496
        let optimistic = parameters.is_optimistic();
497
        let target = if parameters.suppressing_hostname() {
498
            BeginAddr::empty()
499
        } else {
500
            // We try to interpret what's in the string.
501
            if let Ok(ip) = target.parse() {
502
                BeginAddr::Ip(ip)
503
            } else {
504
                let hostname = BeginHostname::new(target)
505
                    .map_err(|e| Error::from_cell_enc(e, "begin hostname"))?;
506
                BeginAddr::Hostname(hostname)
507
            }
508
        };
509

            
510
        // It would be nice to make this method take a `NonZero<u16>`,
511
        // but this is exposed to users in arti-client,
512
        // and I don't think it's worth making this breaking change at this time.
513
        let port = NonZero::new(port).ok_or(Error::BadStreamAddress)?;
514

            
515
        let beginmsg = Begin::new(target.encode(), port, begin_flags);
516
        self.begin_data_stream(beginmsg.into(), optimistic).await
517
42
    }
518

            
519
    /// Start a new stream to the last relay in the tunnel, using
520
    /// a BEGIN_DIR cell.
521
6
    pub async fn begin_dir_stream(self: Arc<Self>) -> Result<DataStream> {
522
        // Note that we always open begindir connections optimistically.
523
        // Since they are local to a relay that we've already authenticated
524
        // with and built a tunnel to, there should be no additional checks
525
        // we need to perform to see whether the BEGINDIR will succeed.
526
6
        self.begin_data_stream(AnyRelayMsg::BeginDir(Default::default()), true)
527
6
            .await
528
6
    }
529

            
530
    /// Perform a DNS lookup, using a RESOLVE cell with the last relay
531
    /// in this tunnel.
532
    ///
533
    /// Returns all the addresses from the RESOLVED response,
534
    /// without performing any filtering.
535
    /// Most callers will want filter out the local and non-routable addresses
536
    /// before using the result.
537
    ///
538
    /// Note that this function does not check for timeouts; that's
539
    /// the caller's responsibility.
540
    pub async fn resolve(self: &Arc<Self>, hostname: &str) -> Result<Vec<IpAddr>> {
541
        let resolve_msg = Resolve::new(hostname);
542

            
543
        let resolved_msg = self.try_resolve(resolve_msg).await?;
544

            
545
        resolved_msg
546
            .into_answers()
547
            .into_iter()
548
            .filter_map(|(val, _)| match resolvedval_to_result(val) {
549
                Ok(ResolvedVal::Ip(ip)) => Some(Ok(ip)),
550
                Ok(_) => None,
551
                Err(e) => Some(Err(e)),
552
            })
553
            .collect()
554
    }
555

            
556
    /// Perform a reverse DNS lookup, by sending a RESOLVE cell with
557
    /// the last relay on this tunnel.
558
    ///
559
    /// Does not perform any validation on `addr`.
560
    /// Most callers will want to avoid calling this function
561
    /// with a local or non-routable `addr`.
562
    ///
563
    /// Note that this function does not check for timeouts; that's
564
    /// the caller's responsibility.
565
    pub async fn resolve_ptr(self: &Arc<Self>, addr: IpAddr) -> Result<Vec<String>> {
566
        let resolve_ptr_msg = Resolve::new_reverse(&addr);
567

            
568
        let resolved_msg = self.try_resolve(resolve_ptr_msg).await?;
569

            
570
        resolved_msg
571
            .into_answers()
572
            .into_iter()
573
            .filter_map(|(val, _)| match resolvedval_to_result(val) {
574
                Ok(ResolvedVal::Hostname(v)) => Some(
575
                    String::from_utf8(v)
576
                        .map_err(|_| Error::StreamProto("Resolved Hostname was not utf-8".into())),
577
                ),
578
                Ok(_) => None,
579
                Err(e) => Some(Err(e)),
580
            })
581
            .collect()
582
    }
583

            
584
    /// Send an ad-hoc message to a given hop on the circuit, without expecting
585
    /// a reply.
586
    ///
587
    /// (If you want to handle one or more possible replies, see
588
    /// [`ClientTunnel::start_conversation`].)
589
    // TODO(conflux): Change this to use the ReactorHandle for the control commands.
590
    #[cfg(feature = "send-control-msg")]
591
    pub async fn send_raw_msg(
592
        &self,
593
        msg: tor_cell::relaycell::msg::AnyRelayMsg,
594
        hop: TargetHop,
595
    ) -> Result<()> {
596
        let (sender, receiver) = oneshot::channel();
597
        let ctrl_msg = CtrlMsg::SendMsg { hop, msg, sender };
598
        self.circ
599
            .control
600
            .unbounded_send(ctrl_msg)
601
            .map_err(|_| Error::CircuitClosed)?;
602

            
603
        receiver.await.map_err(|_| Error::CircuitClosed)?
604
    }
605

            
606
    /// Start an ad-hoc protocol exchange to the specified hop on this tunnel.
607
    ///
608
    /// To use this:
609
    ///
610
    ///  0. Create an inter-task channel you'll use to receive
611
    ///     the outcome of your conversation,
612
    ///     and bundle it into a [`UserMsgHandler`].
613
    ///
614
    ///  1. Call `start_conversation`.
615
    ///     This will install a your handler, for incoming messages,
616
    ///     and send the outgoing message (if you provided one).
617
    ///     After that, each message on the circuit
618
    ///     that isn't handled by the core machinery
619
    ///     is passed to your provided `reply_handler`.
620
    ///
621
    ///  2. Possibly call `send_msg` on the [`Conversation`],
622
    ///     from the call site of `start_conversation`,
623
    ///     possibly multiple times, from time to time,
624
    ///     to send further desired messages to the peer.
625
    ///
626
    ///  3. In your [`UserMsgHandler`], process the incoming messages.
627
    ///     You may respond by
628
    ///     sending additional messages
629
    ///     When the protocol exchange is finished,
630
    ///     `UserMsgHandler::handle_msg` should return
631
    ///     [`ConversationFinished`](reactor::MetaCellDisposition::ConversationFinished).
632
    ///
633
    /// If you don't need the `Conversation` to send followup messages,
634
    /// you may simply drop it,
635
    /// and rely on the responses you get from your handler,
636
    /// on the channel from step 0 above.
637
    /// Your handler will remain installed and able to process incoming messages
638
    /// until it returns `ConversationFinished`.
639
    ///
640
    /// (If you don't want to accept any replies at all, it may be
641
    /// simpler to use [`ClientTunnel::send_raw_msg`].)
642
    ///
643
    /// Note that it is quite possible to use this function to violate the tor
644
    /// protocol; most users of this API will not need to call it.  It is used
645
    /// to implement most of the onion service handshake.
646
    ///
647
    /// # Limitations
648
    ///
649
    /// Only one conversation may be active at any one time,
650
    /// for any one circuit.
651
    /// This generally means that this function should not be called
652
    /// on a tunnel which might be shared with anyone else.
653
    ///
654
    /// Likewise, it is forbidden to try to extend the tunnel,
655
    /// while the conversation is in progress.
656
    ///
657
    /// After the conversation has finished, the tunnel may be extended.
658
    /// Or, `start_conversation` may be called again;
659
    /// but, in that case there will be a gap between the two conversations,
660
    /// during which no `UserMsgHandler` is installed,
661
    /// and unexpected incoming messages would close the tunnel.
662
    ///
663
    /// If these restrictions are violated, the tunnel will be closed with an error.
664
    ///
665
    /// ## Precise definition of the lifetime of a conversation
666
    ///
667
    /// A conversation is in progress from entry to `start_conversation`,
668
    /// until entry to the body of the [`UserMsgHandler::handle_msg`](MsgHandler::handle_msg)
669
    /// call which returns [`ConversationFinished`](reactor::MetaCellDisposition::ConversationFinished).
670
    /// (*Entry* since `handle_msg` is synchronously embedded
671
    /// into the incoming message processing.)
672
    /// So you may start a new conversation as soon as you have the final response
673
    /// via your inter-task channel from (0) above.
674
    ///
675
    /// The lifetime relationship of the [`Conversation`],
676
    /// vs the handler returning `ConversationFinished`
677
    /// is not enforced by the type system.
678
    // Doing so without still leaving plenty of scope for runtime errors doesn't seem possible,
679
    // at least while allowing sending followup messages from outside the handler.
680
    #[cfg(feature = "send-control-msg")]
681
    pub async fn start_conversation(
682
        &self,
683
        msg: Option<tor_cell::relaycell::msg::AnyRelayMsg>,
684
        reply_handler: impl MsgHandler + Send + 'static,
685
        hop: TargetHop,
686
    ) -> Result<Conversation<'_>> {
687
        // We need to resolve the TargetHop into a precise HopLocation so our msg handler can match
688
        // the right Leg/Hop with inbound cell.
689
        let (sender, receiver) = oneshot::channel();
690
        self.circ
691
            .command
692
            .unbounded_send(CtrlCmd::ResolveTargetHop { hop, done: sender })
693
            .map_err(|_| Error::CircuitClosed)?;
694
        let hop_location = receiver.await.map_err(|_| Error::CircuitClosed)??;
695
        let handler = Box::new(UserMsgHandler::new(hop_location, reply_handler));
696
        let conversation = Conversation(self);
697
        conversation.send_internal(msg, Some(handler)).await?;
698
        Ok(conversation)
699
    }
700

            
701
    /// Shut down this tunnel, along with all streams that are using it. Happens asynchronously
702
    /// (i.e. the tunnel won't necessarily be done shutting down immediately after this function
703
    /// returns!).
704
    ///
705
    /// Note that other references to this tunnel may exist. If they do, they will stop working
706
    /// after you call this function.
707
    ///
708
    /// It's not necessary to call this method if you're just done with a tunnel: the tunnel should
709
    /// close on its own once nothing is using it any more.
710
    // TODO(conflux): This should use the ReactorHandle instead.
711
    pub fn terminate(&self) {
712
        let _ = self.circ.command.unbounded_send(CtrlCmd::Shutdown);
713
    }
714

            
715
    /// Helper: Send the resolve message, and read resolved message from
716
    /// resolve stream.
717
    async fn try_resolve(self: &Arc<Self>, msg: Resolve) -> Result<Resolved> {
718
        let components = self
719
            .begin_stream_impl(msg.into(), ResolveCmdChecker::new_any())
720
            .await?;
721

            
722
        let StreamComponents {
723
            stream_receiver,
724
            target: _,
725
            memquota,
726
            xon_xoff_reader_ctrl: _,
727
        } = components;
728

            
729
        let mut resolve_stream = ResolveStream::new(stream_receiver, memquota);
730
        resolve_stream.read_msg().await
731
    }
732

            
733
    // TODO(conflux)
734
}
735

            
736
// TODO(conflux): We will likely need to enforce some invariants here, for example that the `circ`
737
// has the expected (non-zero) number of hops.
738
impl TryFrom<ClientCirc> for ClientTunnel {
739
    type Error = Error;
740

            
741
189
    fn try_from(circ: ClientCirc) -> std::result::Result<Self, Self::Error> {
742
189
        Ok(Self { circ })
743
189
    }
744
}
745

            
746
/// Convert a [`ResolvedVal`] into a Result, based on whether or not
747
/// it represents an error.
748
fn resolvedval_to_result(val: ResolvedVal) -> Result<ResolvedVal> {
749
    match val {
750
        ResolvedVal::TransientError => Err(Error::ResolveError(ResolveError::Transient)),
751
        ResolvedVal::NontransientError => Err(Error::ResolveError(ResolveError::Nontransient)),
752
        ResolvedVal::Unrecognized(_, _) => Err(Error::ResolveError(ResolveError::Unrecognized)),
753
        _ => Ok(val),
754
    }
755
}
756

            
757
/// A precise position in a tunnel.
758
#[derive(Debug, Deftly, Copy, Clone, PartialEq, Eq)]
759
#[derive_deftly(HasMemoryCost)]
760
#[non_exhaustive]
761
pub enum HopLocation {
762
    /// A specific position in a tunnel.
763
    Hop((UniqId, HopNum)),
764
    /// The join point of a multi-path tunnel.
765
    JoinPoint,
766
}
767

            
768
/// A position in a tunnel.
769
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
770
#[non_exhaustive]
771
pub enum TargetHop {
772
    /// A specific position in a tunnel.
773
    Hop(HopLocation),
774
    /// The last hop of a tunnel.
775
    ///
776
    /// This should be used only when you don't care about what specific hop is used.
777
    /// Some tunnels may be extended or truncated,
778
    /// which means that the "last hop" may change at any time.
779
    LastHop,
780
}
781

            
782
impl From<(UniqId, HopNum)> for HopLocation {
783
86
    fn from(v: (UniqId, HopNum)) -> Self {
784
86
        HopLocation::Hop(v)
785
86
    }
786
}
787

            
788
impl From<(UniqId, HopNum)> for TargetHop {
789
8
    fn from(v: (UniqId, HopNum)) -> Self {
790
8
        TargetHop::Hop(v.into())
791
8
    }
792
}
793

            
794
impl HopLocation {
795
    /// Return the hop number if not a JointPoint.
796
    pub fn hop_num(&self) -> Option<HopNum> {
797
        match self {
798
            Self::Hop((_, hop_num)) => Some(*hop_num),
799
            Self::JoinPoint => None,
800
        }
801
    }
802
}
803

            
804
impl ClientTunnel {
805
    /// Close the pending stream that owns this StreamTarget, delivering the specified
806
    /// END message (if any)
807
    ///
808
    /// See [`StreamTarget::close_pending`].
809
    #[cfg(feature = "hs-service")]
810
6
    pub(crate) fn close_pending(
811
6
        &self,
812
6
        stream_id: StreamId,
813
6
        hop: Option<HopLocation>,
814
6
        message: crate::stream::CloseStreamBehavior,
815
6
    ) -> Result<oneshot::Receiver<Result<()>>> {
816
6
        let (tx, rx) = oneshot::channel();
817

            
818
6
        self.circ
819
6
            .control
820
6
            .unbounded_send(CtrlMsg::ClosePendingStream {
821
6
                stream_id,
822
6
                hop: hop.expect("missing stream hop for client tunnel"),
823
6
                message,
824
6
                done: tx,
825
6
            })
826
            .map_err(|_| Error::CircuitClosed)?;
827

            
828
6
        Ok(rx)
829
6
    }
830

            
831
    /// Request to send a SENDME cell for this stream.
832
    ///
833
    /// See [`StreamTarget::send_sendme`].
834
    pub(crate) fn send_sendme(&self, stream_id: StreamId, hop: Option<HopLocation>) -> Result<()> {
835
        self.circ
836
            .control
837
            .unbounded_send(CtrlMsg::FlowCtrlUpdate {
838
                msg: FlowCtrlMsg::Sendme,
839
                stream_id,
840
                hop: hop.expect("missing stream hop for client tunnel"),
841
            })
842
            .map_err(|_| Error::CircuitClosed)
843
    }
844

            
845
    /// Inform the circuit reactor that there has been a change in the drain rate for this stream.
846
    ///
847
    /// See [`StreamTarget::drain_rate_update`].
848
    pub(crate) fn drain_rate_update(
849
        &self,
850
        stream_id: StreamId,
851
        hop: Option<HopLocation>,
852
        rate: XonKBpsEwma,
853
    ) -> Result<()> {
854
        self.circ
855
            .control
856
            .unbounded_send(CtrlMsg::FlowCtrlUpdate {
857
                msg: FlowCtrlMsg::Xon(rate),
858
                stream_id,
859
                hop: hop.expect("missing stream hop for client tunnel"),
860
            })
861
            .map_err(|_| Error::CircuitClosed)
862
    }
863
}