1
//! Administrative RPC functionality.
2
//!
3
//! In general, RPC function is "administrative", and requires superuser access,
4
//! whenever it can affect other applications.
5
//!
6
//! This is not a perfect sandbox: applications can _always_ interfere with one another's traffic by
7
//! consuming resources (like bandwidth or CPU) in a way that introduces side channels.
8

            
9
use arti_client::{TorClient, rpc::ClientStatusInfo};
10
use derive_deftly::Deftly;
11
use futures::{FutureExt as _, SinkExt as _, StreamExt as _, select_biased};
12
use std::sync::Arc;
13
use tor_rpcbase::{self as rpc};
14
use tor_rtcompat::Runtime;
15

            
16
use crate::reload_cfg::{CfgMgr, LaunchableTorClient};
17

            
18
/// An object representing superuser access to Arti over an RPC session.
19
///
20
/// In general, RPC function is "administrative", and requires superuser access,
21
/// whenever it can affect other applications.
22
#[derive(Deftly)]
23
#[derive_deftly(rpc::Object)]
24
pub(super) struct RpcSuperuser<R: Runtime> {
25
    /// A view of the underlying TorClient managed by this RpcSuperuser object.
26
    tor_client: Arc<TorClient<R>>,
27

            
28
    /// A wrapper around `tor_client` with the ability to launch a deferred-bootstrap client.
29
    launchable: Arc<LaunchableTorClient<R>>,
30

            
31
    /// A handle to the manager for configuration information.
32
    #[allow(unused)] // TODO(rpc) remove
33
    cfg_mgr: Arc<CfgMgr<R>>,
34
}
35

            
36
impl<R: Runtime> RpcSuperuser<R> {
37
    /// Construct a new RpcSuperuser object.
38
    pub(super) fn new(
39
        tor_client: Arc<TorClient<R>>,
40
        launchable: Arc<LaunchableTorClient<R>>,
41
        cfg_mgr: Arc<CfgMgr<R>>,
42
    ) -> Self {
43
        RpcSuperuser {
44
            tor_client,
45
            launchable,
46
            cfg_mgr,
47
        }
48
    }
49

            
50
    /// Ensure that every RPC method is registered for this instantiation of TorClient.
51
    ///
52
    /// We can't use [`rpc::static_rpc_invoke_fn`] for these, since TorClient is
53
    /// parameterized.
54
    pub(super) fn rpc_methods() -> Vec<rpc::dispatch::InvokerEnt> {
55
        rpc::invoker_ent_list![
56
            enter_dormant_mode_on_rpcsuperuser::<R>,
57
            bootstrap_client_on_rpcsuperuser::<R>,
58
        ]
59
    }
60
}
61

            
62
/// Enter "dormant mode".
63
///
64
/// Currently, the only available dormant mode is "soft dormant mode",
65
/// which suspends most background operations until any client request
66
/// is received.
67
///
68
/// Since this method affects all applications using the Arti process,
69
/// it requires administrative permissions.
70
///
71
/// ## Limitations
72
///
73
/// As of 2026 March, this functionality is not perfectly implemented,
74
/// and likely does not interact well with onion services.
75
/// Additionally, there are likely background operations that
76
/// this operation doesn't cover.
77
///
78
/// This method returns a reply immediately, but it may take a little
79
/// while before all of the background tasks finish their work and stop.
80
#[derive(Debug, serde::Deserialize, serde::Serialize, Deftly)]
81
#[derive_deftly(rpc::DynMethod)]
82
#[deftly(rpc(method_name = "arti:enter_dormant_mode"))]
83
struct EnterDormantMode {}
84

            
85
impl rpc::RpcMethod for EnterDormantMode {
86
    type Output = rpc::Nil;
87
    type Update = rpc::NoUpdates;
88
}
89

            
90
/// Implementation for [`EnterDormantMode`] on [`RpcSuperuser`].
91
async fn enter_dormant_mode_on_rpcsuperuser<R: Runtime>(
92
    session: Arc<RpcSuperuser<R>>,
93
    _method: Box<EnterDormantMode>,
94
    _ctx: Arc<dyn rpc::Context>,
95
) -> Result<rpc::Nil, rpc::RpcError> {
96
    use arti_client::DormantMode;
97
    session.tor_client.set_dormant(DormantMode::Soft);
98
    Ok(rpc::Nil::default())
99
}
100

            
101
/// Tell a client to connect to the network and bootstrap itself.
102
///
103
/// There is no need to invoke this method unless
104
/// was started with the `application.defer_bootstrap` option set to true.
105
/// By default, clients will automatically connect to the network and bootstrap
106
/// themselves.
107
///
108
/// Since this method affects all applications using the Arti process,
109
/// it requires administrative permissions.  We may someday relax this
110
/// property.
111
#[derive(Debug, serde::Deserialize, serde::Serialize, Deftly)]
112
#[derive_deftly(rpc::DynMethod)]
113
#[deftly(rpc(method_name = "arti:bootstrap_client"))]
114
struct BootstrapClient {}
115

            
116
impl rpc::RpcMethod for BootstrapClient {
117
    type Output = rpc::Nil;
118
    type Update = ClientStatusInfo;
119
}
120

            
121
/// Implementation for [`BootstrapClient`] on [`RpcSuperuser`].
122
async fn bootstrap_client_on_rpcsuperuser<R: Runtime>(
123
    session: Arc<RpcSuperuser<R>>,
124
    _method: Box<BootstrapClient>,
125
    _ctx: Arc<dyn rpc::Context>,
126
    mut updates: rpc::UpdateSink<ClientStatusInfo>,
127
) -> Result<rpc::Nil, rpc::RpcError> {
128
    let mut events = session.tor_client.bootstrap_events().fuse();
129
    // Send the initial status unconditionally.
130
    updates
131
        .send(session.tor_client.bootstrap_status().into())
132
        .await?;
133

            
134
    let mut bootstrap = Box::pin(session.launchable.bootstrap()).fuse();
135

            
136
    loop {
137
        select_biased! {
138
            outcome = bootstrap => {
139
                 let () = outcome?;
140
                 return Ok(rpc::Nil::default());
141
            }
142
            e = events.next() => {
143
                // (If this returns None, then the `outcome` is about to fail.)
144
                if let Some(e) = e {
145
                    let status = e.into();
146
                    let _ignore_failure = updates.send(status).await;
147
                }
148
            }
149
        };
150
    }
151
}