1
//! Declare the RPC session object as exposed from the RPC server run by the `arti` crate.
2

            
3
use arti_client::TorClient;
4
use arti_rpcserver::RpcAuthentication;
5
use derive_deftly::Deftly;
6
use futures::stream::StreamExt as _;
7
use std::{net::SocketAddr, sync::Arc};
8
use tor_async_utils::{DropNotifyEofSignallable, DropNotifyWatchSender};
9
use tor_rpcbase::{self as rpc};
10
use tor_rtcompat::Runtime;
11

            
12
use super::proxyinfo::{self, ProxyInfo};
13

            
14
/// A top-level RPC session object.
15
///
16
/// This is the first object that an RPC user receives upon authenticating;
17
/// It is returned by `auth:authenticate`.
18
///
19
/// Other objects (`TorClient`,`RpcDataStream`, etc)
20
/// are available using methods on this object.
21
/// (See the list of available methods.)
22
///
23
/// This type wraps and delegates to [`arti_rpcserver::RpcSession`],
24
/// but exposes additional functionality not available at the
25
/// level of [`arti_rpcserver`], including information about configured proxies.
26
///
27
/// This ObjectID for this object can be used as the target of a SOCKS stream.
28
#[derive(Deftly)]
29
#[derive_deftly(rpc::Object)]
30
#[deftly(rpc(
31
    delegate_with = "|this: &Self| Some(this.session.clone())",
32
    delegate_type = "arti_rpcserver::RpcSession"
33
))]
34
#[deftly(rpc(expose_outside_of_session))]
35
pub(super) struct ArtiRpcSession {
36
    /// State about the `arti` server, as seen by the Rpc system.
37
    pub(super) arti_state: Arc<RpcVisibleArtiState>,
38
    /// The underlying RpcSession object that we delegate to.
39
    session: Arc<arti_rpcserver::RpcSession>,
40
}
41

            
42
/// Information about the current global top-level Arti state,
43
/// as exposed to an Rpc Session.
44
//
45
// TODO: This type is dangerously close to being a collection of globals.
46
// We should refactor it aggressively when we refactor the `arti` crate.
47
//
48
// TODO: Right now this is constructed in the same form that it's used in
49
// ArtiRpcSession.  Later on, we could split it into one type that
50
// the rest of this crate constructs, and another type that the
51
// ArtiRpcSession actually uses. We should do that if the needs seem to diverge.
52
pub(crate) struct RpcVisibleArtiState {
53
    /// A `ProxyInfo` that we hand out when asked to list our proxy ports.
54
    ///
55
    /// Right now it only lists Socks; in the future it may list more.
56
    proxy_info: postage::watch::Receiver<ProxyInfoState>,
57
}
58

            
59
/// Handle to set RPC state across RPC sessions.  (See `RpcVisibleArtiState`.)
60
#[derive(Debug)]
61
#[cfg_attr(feature = "experimental-api", visibility::make(pub))]
62
pub(crate) struct RpcStateSender {
63
    /// Sender for setting our list of proxy ports.
64
    proxy_info_sender: DropNotifyWatchSender<ProxyInfoState>,
65
}
66

            
67
impl ArtiRpcSession {
68
    /// Construct a new `ArtiRpcSession`.
69
    ///
70
    /// Privileges on the session (if any) are derived from `auth`, which describes
71
    /// how the user authenticated.
72
    ///
73
    /// The session receives a new isolated TorClient, based on `client_root`.
74
    pub(super) fn new<R: Runtime>(
75
        auth: &RpcAuthentication,
76
        client_root: &TorClient<R>,
77
        arti_state: &Arc<RpcVisibleArtiState>,
78
    ) -> Arc<Self> {
79
        let _ = auth; // This is currently unused; any authentication gives the same result.
80
        let client = client_root.isolated_client();
81
        let session = arti_rpcserver::RpcSession::new_with_client(Arc::new(client));
82
        let arti_state = Arc::clone(arti_state);
83
        Arc::new(ArtiRpcSession {
84
            session,
85
            arti_state,
86
        })
87
    }
88
}
89

            
90
/// Possible state for a watched proxy_info.
91
#[derive(Debug, Clone)]
92
enum ProxyInfoState {
93
    /// We haven't set it yet.
94
    Unset,
95
    /// We've set it to a given value.
96
    Set(Arc<ProxyInfo>),
97
    /// The sender has been dropped.
98
    Eof,
99
}
100

            
101
impl DropNotifyEofSignallable for ProxyInfoState {
102
4
    fn eof() -> Self {
103
4
        Self::Eof
104
4
    }
105
}
106

            
107
impl RpcVisibleArtiState {
108
    /// Construct a new `RpcVisibleArtiState`.
109
4
    pub(crate) fn new() -> (Arc<Self>, RpcStateSender) {
110
4
        let (proxy_info_sender, proxy_info) = postage::watch::channel_with(ProxyInfoState::Unset);
111
4
        let proxy_info_sender = DropNotifyWatchSender::new(proxy_info_sender);
112
4
        (
113
4
            Arc::new(Self { proxy_info }),
114
4
            RpcStateSender { proxy_info_sender },
115
4
        )
116
4
    }
117

            
118
    /// Return the latest proxy info, waiting until it is set.
119
    ///
120
    /// Return an error if the sender has been closed.
121
12
    pub(super) async fn get_proxy_info(&self) -> Result<Arc<ProxyInfo>, ()> {
122
8
        let mut proxy_info = self.proxy_info.clone();
123
12
        while let Some(v) = proxy_info.next().await {
124
12
            match v {
125
4
                ProxyInfoState::Unset => {
126
4
                    // Not yet set, try again.
127
4
                }
128
8
                ProxyInfoState::Set(proxyinfo) => return Ok(Arc::clone(&proxyinfo)),
129
                ProxyInfoState::Eof => return Err(()),
130
            }
131
        }
132
        Err(())
133
8
    }
134
}
135

            
136
impl RpcStateSender {
137
    /// Set the list of socks listener addresses on this state.
138
    ///
139
    /// This method may only be called once per state.
140
4
    pub(crate) fn set_socks_listeners(&mut self, addrs: &[SocketAddr]) {
141
4
        let info = ProxyInfo {
142
4
            proxies: addrs
143
4
                .iter()
144
6
                .map(|a| proxyinfo::Proxy {
145
4
                    listener: proxyinfo::ProxyListener::Socks5 {
146
4
                        tcp_address: Some(*a),
147
4
                    },
148
6
                })
149
4
                .collect(),
150
4
        };
151
4
        *self.proxy_info_sender.borrow_mut() = ProxyInfoState::Set(Arc::new(info));
152
4
    }
153
}
154

            
155
#[cfg(test)]
156
mod test {
157
    // @@ begin test lint list maintained by maint/add_warning @@
158
    #![allow(clippy::bool_assert_comparison)]
159
    #![allow(clippy::clone_on_copy)]
160
    #![allow(clippy::dbg_macro)]
161
    #![allow(clippy::mixed_attributes_style)]
162
    #![allow(clippy::print_stderr)]
163
    #![allow(clippy::print_stdout)]
164
    #![allow(clippy::single_char_pattern)]
165
    #![allow(clippy::unwrap_used)]
166
    #![allow(clippy::unchecked_duration_subtraction)]
167
    #![allow(clippy::useless_vec)]
168
    #![allow(clippy::needless_pass_by_value)]
169
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
170

            
171
    use futures::task::SpawnExt as _;
172
    use tor_rtmock::MockRuntime;
173

            
174
    use super::*;
175

            
176
    #[test]
177
    fn set_proxy_info() {
178
        MockRuntime::test_with_various(|rt| async move {
179
            let (state, mut sender) = RpcVisibleArtiState::new();
180
            let _task = rt.clone().spawn_with_handle(async move {
181
                sender.set_socks_listeners(&["8.8.4.4:99".parse().unwrap()]);
182
                sender // keep sender alive
183
            });
184

            
185
            let value = state.get_proxy_info().await;
186

            
187
            // At this point, we've returned once, so this will test that we get a fresh answer even
188
            // if we already set the inner value.
189
            let value_again = state.get_proxy_info().await;
190
            assert_eq!(value.unwrap(), value_again.unwrap());
191
        });
192
    }
193
}