1
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![warn(clippy::cognitive_complexity)]
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_duration_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
45

            
46
pub mod dispatch;
47
mod err;
48
mod method;
49
mod obj;
50

            
51
use std::{collections::HashSet, convert::Infallible, sync::Arc};
52

            
53
pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
54
pub use err::{RpcError, RpcErrorKind};
55
pub use method::{
56
    check_method_names, is_method_name, iter_method_names, DeserMethod, DynMethod, Method,
57
    NoUpdates, RpcMethod,
58
};
59
pub use obj::{Object, ObjectArcExt, ObjectId};
60

            
61
#[cfg(feature = "describe-methods")]
62
#[cfg_attr(docsrs, doc(cfg(feature = "describe-methods")))]
63
pub use dispatch::description::RpcDispatchInformation;
64

            
65
#[cfg(feature = "describe-methods")]
66
#[cfg_attr(docsrs, doc(cfg(feature = "describe-methods")))]
67
#[doc(hidden)]
68
pub use dispatch::description::DelegationNote;
69

            
70
#[doc(hidden)]
71
pub use obj::cast::CastTable;
72
#[doc(hidden)]
73
pub use {
74
    derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
75
    method::MethodInfo_, once_cell, paste, tor_async_utils, tor_error::internal, typetag,
76
};
77

            
78
/// Templates for use with [`derive_deftly`]
79
pub mod templates {
80
    pub use crate::method::derive_deftly_template_DynMethod;
81
    pub use crate::obj::derive_deftly_template_Object;
82
}
83

            
84
/// An error returned from [`ContextExt::lookup`].
85
#[derive(Debug, Clone, thiserror::Error)]
86
#[non_exhaustive]
87
pub enum LookupError {
88
    /// The specified object does not (currently) exist,
89
    /// or the user does not have permission to access it.
90
    #[error("No visible object with ID {0:?}")]
91
    NoObject(ObjectId),
92

            
93
    /// The specified object exists, but does not have the
94
    /// expected type.
95
    #[error("Unexpected type on object with ID {0:?}")]
96
    WrongType(ObjectId),
97
}
98

            
99
impl From<LookupError> for RpcError {
100
    fn from(err: LookupError) -> Self {
101
        use LookupError as E;
102
        use RpcErrorKind as EK;
103
        let kind = match &err {
104
            E::NoObject(_) => EK::ObjectNotFound,
105
            E::WrongType(_) => EK::InvalidRequest,
106
        };
107
        RpcError::new(err.to_string(), kind)
108
    }
109
}
110

            
111
/// A trait describing the context in which an RPC method is executed.
112
pub trait Context: Send + Sync {
113
    /// Look up an object by identity within this context.
114
    fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>;
115

            
116
    /// Create an owning reference to `object` within this context.
117
    ///
118
    /// Return an ObjectId for this object.
119
    fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
120

            
121
    // TODO: If we add weak references again, we may need a register_weak method here.
122

            
123
    /// Drop an owning reference to the object called `object` within this context.
124
    ///
125
    /// This will return an error if `object` is not an owning reference,
126
    /// or does not exist.
127
    fn release_owned(&self, object: &ObjectId) -> Result<(), LookupError>;
128

            
129
    /// Return a dispatch table that can be used to invoke other RPC methods.
130
    fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>;
131
}
132

            
133
/// An error caused while trying to send an update to a method.
134
///
135
/// These errors should be impossible in our current implementation, since they
136
/// can only happen if the `mpsc::Receiver` is closed—which can only happen
137
/// when the session loop drops it, which only happens when the session loop has
138
/// stopped polling its `FuturesUnordered` full of RPC request futures. Thus, any
139
/// `send` that would encounter this error should be in a future that is never
140
/// polled under circumstances when the error could happen.
141
///
142
/// Still, programming errors are real, so we are handling this rather than
143
/// declaring it a panic or something.
144
#[derive(Debug, Clone, thiserror::Error)]
145
#[non_exhaustive]
146
pub enum SendUpdateError {
147
    /// The request was cancelled, or the connection was closed.
148
    #[error("Unable to send on MPSC connection")]
149
    ConnectionClosed,
150
}
151

            
152
impl tor_error::HasKind for SendUpdateError {
153
    fn kind(&self) -> tor_error::ErrorKind {
154
        tor_error::ErrorKind::Internal
155
    }
156
}
157

            
158
impl From<Infallible> for SendUpdateError {
159
    fn from(_: Infallible) -> Self {
160
        unreachable!()
161
    }
162
}
163
impl From<futures::channel::mpsc::SendError> for SendUpdateError {
164
    fn from(_: futures::channel::mpsc::SendError) -> Self {
165
        SendUpdateError::ConnectionClosed
166
    }
167
}
168

            
169
/// Extension trait for [`Context`].
170
///
171
/// This is a separate trait so that `Context` can be object-safe.
172
pub trait ContextExt: Context {
173
    /// Look up an object of a given type, and downcast it.
174
    ///
175
    /// Return an error if the object can't be found, or has the wrong type.
176
    fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
177
        self.lookup_object(id)?
178
            .downcast_arc()
179
            .map_err(|_| LookupError::WrongType(id.clone()))
180
    }
181
}
182

            
183
impl<T: Context> ContextExt for T {}
184

            
185
/// Try to find an appropriate function for calling a given RPC method on a
186
/// given RPC-visible object.
187
///
188
/// On success, return a Future.
189
///
190
/// Differs from using `DispatchTable::invoke()` in that it drops its lock
191
/// on the dispatch table before invoking the method.
192
42
pub fn invoke_rpc_method(
193
42
    ctx: Arc<dyn Context>,
194
42
    obj_id: &ObjectId,
195
42
    obj: Arc<dyn Object>,
196
42
    method: Box<dyn DynMethod>,
197
42
    sink: dispatch::BoxedUpdateSink,
198
42
) -> Result<dispatch::RpcResultFuture, InvokeError> {
199
42
    match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
200
42
        Err(InvokeError::NoDispatchBypass) => {
201
42
            // fall through
202
42
        }
203
        other => return other,
204
    }
205

            
206
42
    let (obj, invocable) = ctx
207
42
        .dispatch_table()
208
42
        .read()
209
42
        .expect("poisoned lock")
210
42
        .resolve_rpc_invoker(obj, method.as_ref())?;
211

            
212
34
    invocable.invoke(obj, method, ctx, sink)
213
42
}
214

            
215
/// Invoke the given `method` on `obj` within `ctx`, and return its
216
/// actual result type.
217
///
218
/// Unlike `invoke_rpc_method`, this method does not return a type-erased result,
219
/// and does not require that the result can be serialized as an RPC object.
220
///
221
/// Differs from using `DispatchTable::invoke_special()` in that it drops its lock
222
/// on the dispatch table before invoking the method.
223
6
pub async fn invoke_special_method<M: Method>(
224
6
    ctx: Arc<dyn Context>,
225
6
    obj: Arc<dyn Object>,
226
6
    method: Box<M>,
227
6
) -> Result<Box<M::Output>, InvokeError> {
228
6
    let (obj, invocable) = ctx
229
6
        .dispatch_table()
230
6
        .read()
231
6
        .expect("poisoned lock")
232
6
        .resolve_special_invoker::<M>(obj)?;
233

            
234
6
    invocable
235
6
        .invoke_special(obj, method, ctx)?
236
6
        .await
237
6
        .downcast()
238
6
        .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
239
6
}
240

            
241
/// A serializable empty object.
242
///
243
/// Used when we need to declare that a method returns nothing.
244
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
245
#[non_exhaustive]
246
pub struct Nil {}
247
/// An instance of rpc::Nil.
248
pub const NIL: Nil = Nil {};
249

            
250
/// Common return type for RPC methods that return a single object ID
251
/// and nothing else.
252
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
253
pub struct SingleIdResponse {
254
    /// The ID of the object that we're returning.
255
    id: ObjectId,
256
}
257

            
258
/// Error representing an "invalid" RPC identifier.
259
#[derive(Clone, Debug, thiserror::Error)]
260
#[non_exhaustive]
261
#[cfg_attr(test, derive(Eq, PartialEq))]
262
pub enum InvalidRpcIdentifier {
263
    /// The method doesn't have a ':' to demarcate its namespace.
264
    #[error("Identifier has no namespace separator")]
265
    NoNamespace,
266

            
267
    /// The method's namespace is not one we recognize.
268
    #[error("Identifier has unrecognized namespace")]
269
    UnrecognizedNamespace,
270

            
271
    /// The method's name is not in snake_case.
272
    #[error("Identifier name has unexpected format")]
273
    BadIdName,
274
}
275

            
276
/// Check whether `method` is an expected and well-formed RPC identifier.
277
///
278
/// If `recognized_namespaces` is provided, only identifiers within those
279
/// namespaces are accepted; otherwise, all namespaces are accepted.
280
///
281
/// (Examples of RPC identifiers are method names.)
282
479
pub(crate) fn is_valid_rpc_identifier(
283
479
    recognized_namespaces: Option<&HashSet<&str>>,
284
479
    method: &str,
285
479
) -> Result<(), InvalidRpcIdentifier> {
286
    /// Return true if name is in acceptable format.
287
475
    fn name_ok(n: &str) -> bool {
288
475
        let mut chars = n.chars();
289
475
        let Some(first) = chars.next() else {
290
2
            return false;
291
        };
292
473
        first.is_ascii_lowercase()
293
6248
            && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
294
475
    }
295
479
    let (scope, name) = method
296
479
        .split_once(':')
297
479
        .ok_or(InvalidRpcIdentifier::NoNamespace)?;
298

            
299
477
    if let Some(recognized_namespaces) = recognized_namespaces {
300
475
        if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
301
2
            return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
302
473
        }
303
2
    }
304
475
    if !name_ok(name) {
305
8
        return Err(InvalidRpcIdentifier::BadIdName);
306
467
    }
307
467

            
308
467
    Ok(())
309
479
}
310

            
311
#[cfg(test)]
312
mod test {
313
    // @@ begin test lint list maintained by maint/add_warning @@
314
    #![allow(clippy::bool_assert_comparison)]
315
    #![allow(clippy::clone_on_copy)]
316
    #![allow(clippy::dbg_macro)]
317
    #![allow(clippy::mixed_attributes_style)]
318
    #![allow(clippy::print_stderr)]
319
    #![allow(clippy::print_stdout)]
320
    #![allow(clippy::single_char_pattern)]
321
    #![allow(clippy::unwrap_used)]
322
    #![allow(clippy::unchecked_duration_subtraction)]
323
    #![allow(clippy::useless_vec)]
324
    #![allow(clippy::needless_pass_by_value)]
325
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
326

            
327
    use futures::SinkExt as _;
328
    use futures_await_test::async_test;
329

            
330
    use super::*;
331
    use crate::dispatch::test::{Ctx, GetKids, Swan};
332

            
333
    #[async_test]
334
    async fn invoke() {
335
        let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
336
        let discard = || Box::pin(futures::sink::drain().sink_err_into());
337
        let r = invoke_rpc_method(
338
            ctx.clone(),
339
            &ObjectId::from("Odile"),
340
            Arc::new(Swan),
341
            Box::new(GetKids),
342
            discard(),
343
        )
344
        .unwrap()
345
        .await
346
        .unwrap();
347
        assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
348

            
349
        let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
350
            .await
351
            .unwrap()
352
            .unwrap();
353
        assert_eq!(r.v, "cygnets");
354
    }
355

            
356
    #[test]
357
    fn valid_method_names() {
358
        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
359

            
360
        for name in [
361
            "arti:clone",
362
            "arti:clone7",
363
            "arti:clone_now",
364
            "wombat:knish",
365
            "x-foo:bar",
366
        ] {
367
            assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
368
        }
369
    }
370

            
371
    #[test]
372
    fn invalid_method_names() {
373
        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
374
        use InvalidRpcIdentifier as E;
375

            
376
        for (name, expect_err) in [
377
            ("arti-foo:clone", E::UnrecognizedNamespace),
378
            ("fred", E::NoNamespace),
379
            ("arti:", E::BadIdName),
380
            ("arti:7clone", E::BadIdName),
381
            ("arti:CLONE", E::BadIdName),
382
            ("arti:clone-now", E::BadIdName),
383
        ] {
384
            assert_eq!(
385
                is_valid_rpc_identifier(Some(&namespaces), name),
386
                Err(expect_err)
387
            );
388
        }
389
    }
390
}