1
//! This module provides the [`PathBuilder`] helper for building vanguard [`TorPath`]s.
2

            
3
use std::result::Result as StdResult;
4

            
5
use rand::Rng;
6

            
7
use tor_error::{internal, Bug};
8
use tor_guardmgr::vanguards::{Layer, VanguardMgr};
9
use tor_linkspec::HasRelayIds;
10
use tor_netdir::{NetDir, Relay};
11
use tor_relay_selection::{RelayExclusion, RelaySelector};
12
use tor_rtcompat::Runtime;
13

            
14
use crate::path::{MaybeOwnedRelay, TorPath};
15
use crate::{Error, Result};
16

            
17
/// A vanguard path builder.
18
///
19
/// A `PathBuilder` is a state machine whose current state is the [`HopKind`] of its last hop.
20
/// Not all state transitions are valid. For the permissible state transitions, see
21
/// [update_last_hop_kind](PathBuilder::update_last_hop_kind).
22
///
23
/// This type is an implementation detail that should remain private.
24
/// Used by [`VanguardHsPathBuilder`](super::VanguardHsPathBuilder).
25
pub(super) struct PathBuilder<'n, 'a, RT: Runtime, R: Rng> {
26
    /// The relays in the path.
27
    hops: Vec<MaybeOwnedRelay<'n>>,
28
    /// The network directory.
29
    netdir: &'n NetDir,
30
    /// The vanguard manager.
31
    vanguards: &'a VanguardMgr<RT>,
32
    /// An RNG for selecting vanguards and middle relays.
33
    rng: &'a mut R,
34
    /// The `HopKind` of the last hop in the path.
35
    last_hop_kind: HopKind,
36
}
37

            
38
/// The type of a `PathBuilder` hop.
39
#[derive(Copy, Clone, Debug, PartialEq, derive_more::Display)]
40
enum HopKind {
41
    /// The L1 guard.
42
    Guard,
43
    /// A vanguard from the specified [`Layer`].
44
    Vanguard(Layer),
45
    /// A middle relay.
46
    Middle,
47
}
48

            
49
impl<'n, 'a, RT: Runtime, R: Rng> PathBuilder<'n, 'a, RT, R> {
50
    /// Create a new `PathBuilder`.
51
56
    pub(super) fn new(
52
56
        rng: &'a mut R,
53
56
        netdir: &'n NetDir,
54
56
        vanguards: &'a VanguardMgr<RT>,
55
56
        l1_guard: MaybeOwnedRelay<'n>,
56
56
    ) -> Self {
57
56
        Self {
58
56
            hops: vec![l1_guard],
59
56
            netdir,
60
56
            vanguards,
61
56
            rng,
62
56
            last_hop_kind: HopKind::Guard,
63
56
        }
64
56
    }
65

            
66
    /// Extend the path with a vanguard.
67
88
    pub(super) fn add_vanguard(
68
88
        mut self,
69
88
        selector: &RelaySelector<'n>,
70
88
        layer: Layer,
71
88
    ) -> Result<Self> {
72
88
        let selector = selector_excluding_neighbors(selector, &self.hops);
73

            
74
88
        let vanguard: MaybeOwnedRelay = self
75
88
            .vanguards
76
88
            .select_vanguard(&mut self.rng, self.netdir, layer, &selector)?
77
80
            .into();
78
80
        let () = self.add_hop(vanguard, HopKind::Vanguard(layer))?;
79
80
        Ok(self)
80
88
    }
81

            
82
    /// Extend the path with a middle relay.
83
36
    pub(super) fn add_middle(mut self, selector: &RelaySelector<'n>) -> Result<Self> {
84
28
        let middle =
85
36
            select_middle_for_vanguard_circ(&self.hops, self.netdir, selector, self.rng)?.into();
86
28
        let () = self.add_hop(middle, HopKind::Middle)?;
87
28
        Ok(self)
88
36
    }
89

            
90
    /// Return a [`TorPath`] built using the hops from this `PathBuilder`.
91
40
    pub(super) fn build(self) -> Result<TorPath<'n>> {
92
        use HopKind::*;
93
        use Layer::*;
94

            
95
12
        match self.last_hop_kind {
96
40
            Vanguard(Layer3) | Middle => Ok(TorPath::new_multihop_from_maybe_owned(self.hops)),
97
            _ => Err(internal!(
98
                "tried to build TorPath from incomplete PathBuilder (last_hop_kind={})",
99
                self.last_hop_kind
100
            )
101
            .into()),
102
        }
103
40
    }
104

            
105
    /// Try to append `hop` to the end of the path.
106
    ///
107
    /// This also causes the `PathBuilder` to transition to the state represented by `hop_kind`,
108
    /// if the transition is valid.
109
    ///
110
    /// Returns an error if the `hop_kind` is incompatible with the `HopKind` of the last hop.
111
108
    fn add_hop(&mut self, hop: MaybeOwnedRelay<'n>, hop_kind: HopKind) -> StdResult<(), Bug> {
112
108
        self.update_last_hop_kind(hop_kind)?;
113
108
        self.hops.push(hop);
114
108
        Ok(())
115
108
    }
116

            
117
    /// Transition to the state specified by `kind`.
118
    ///
119
    /// The state of the `PathBuilder` is represented by the [`HopKind`] of its last hop.
120
    /// This function should be called whenever a new hop is added
121
    /// (e.g. in [`add_hop`](PathBuilder::add_hop)), to set the current state to the
122
    /// [`HopKind`] of the new hop.
123
    ///
124
    /// Not all transitions are valid. The permissible state transitions are:
125
    ///   * `G  -> L2`
126
    ///   * `L2 -> L3`
127
    ///   * `L2 -> M`
128
    ///   * `L3 -> M`
129
108
    fn update_last_hop_kind(&mut self, kind: HopKind) -> StdResult<(), Bug> {
130
        use HopKind::*;
131
        use Layer::*;
132

            
133
108
        match (self.last_hop_kind, kind) {
134
            (Guard, Vanguard(Layer2))
135
            | (Vanguard(Layer2), Vanguard(Layer3))
136
            | (Vanguard(Layer2), Middle)
137
108
            | (Vanguard(Layer3), Middle) => {
138
108
                self.last_hop_kind = kind;
139
108
            }
140
            (_, _) => {
141
                return Err(internal!(
142
                    "tried to build an invalid vanguard path: cannot add a {kind} hop after {}",
143
                    self.last_hop_kind
144
                ))
145
            }
146
        }
147

            
148
108
        Ok(())
149
108
    }
150
}
151

            
152
/// Build a [`RelayExclusion`] that excludes the specified relays.
153
124
fn exclude_identities<'a, T: HasRelayIds + 'a>(exclude_ids: &[&T]) -> RelayExclusion<'a> {
154
124
    RelayExclusion::exclude_identities(
155
124
        exclude_ids
156
124
            .iter()
157
192
            .flat_map(|relay| relay.identities())
158
384
            .map(|id| id.to_owned())
159
124
            .collect(),
160
124
    )
161
124
}
162

            
163
/// Create a `RelayExclusion` suitable for selecting the next hop to add to `hops`.
164
124
fn exclude_neighbors<'n, T: HasRelayIds + 'n>(hops: &[T]) -> RelayExclusion<'n> {
165
124
    // We must exclude the last 2 hops in the path,
166
124
    // because a relay can't extend to itself or to its predecessor.
167
124
    let skip_n = 2;
168
124
    let neighbors = hops.iter().rev().take(skip_n).collect::<Vec<&T>>();
169
124
    exclude_identities(&neighbors[..])
170
124
}
171

            
172
/// Select a middle relay that can be appended to a vanguard circuit.
173
///
174
/// Used by [`PathBuilder`] to build [`TorPath`]s of the form
175
///
176
///   G - L2 - M
177
///   G - L2 - L3 - M
178
///
179
/// If full vanguards are enabled, this is also used by [`HsCircPool`](crate::hspool::HsCircPool),
180
/// for extending NAIVE circuits to become GUARDED circuits.
181
36
pub(crate) fn select_middle_for_vanguard_circ<'n, R: Rng, T: HasRelayIds + 'n>(
182
36
    hops: &[T],
183
36
    netdir: &'n NetDir,
184
36
    selector: &RelaySelector<'n>,
185
36
    rng: &mut R,
186
36
) -> Result<Relay<'n>> {
187
36
    let selector = selector_excluding_neighbors(selector, hops);
188
36
    let (extra_hop, info) = selector.select_relay(rng, netdir);
189
36
    extra_hop.ok_or_else(|| Error::NoRelay {
190
8
        path_kind: "onion-service vanguard circuit",
191
8
        role: "extra hop",
192
8
        problem: info.to_string(),
193
36
    })
194
36
}
195

            
196
/// Extend the selector T to also exclude neighbors, based on `hops`.
197
124
fn selector_excluding_neighbors<'n, T: HasRelayIds + 'n>(
198
124
    selector: &RelaySelector<'n>,
199
124
    hops: &[T],
200
124
) -> RelaySelector<'n> {
201
124
    let mut selector = selector.clone();
202
124
    let neighbor_exclusion = exclude_neighbors(hops);
203
124
    selector.push_restriction(neighbor_exclusion.into());
204
124
    selector
205
124
}