Skip to main content

tor_rpcbase/
lib.rs

1#![cfg_attr(docsrs, feature(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_time_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#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45#![allow(clippy::collapsible_if)] // See arti#2342
46#![deny(clippy::unused_async)]
47//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
48
49pub mod dispatch;
50mod err;
51mod method;
52mod obj;
53
54use std::{collections::HashSet, convert::Infallible, sync::Arc};
55
56pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
57pub use err::{RpcError, RpcErrorKind};
58pub use method::{
59    DeserMethod, DynMethod, Method, NoUpdates, RpcMethod, check_method_names, is_method_name,
60    iter_method_names,
61};
62pub use obj::{Object, ObjectArcExt, ObjectId};
63
64#[cfg(feature = "describe-methods")]
65pub use dispatch::description::RpcDispatchInformation;
66
67#[cfg(feature = "describe-methods")]
68#[doc(hidden)]
69pub use dispatch::description::DelegationNote;
70
71#[doc(hidden)]
72pub use obj::cast::CastTable;
73#[doc(hidden)]
74pub use {
75    derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
76    method::MethodInfo_, paste, tor_async_utils, tor_error::internal, typetag,
77};
78
79/// Templates for use with [`derive_deftly`]
80pub mod templates {
81    pub use crate::method::derive_deftly_template_DynMethod;
82    pub use crate::obj::derive_deftly_template_Object;
83}
84
85/// An error returned from [`ContextExt::lookup`].
86#[derive(Debug, Clone, thiserror::Error)]
87#[non_exhaustive]
88pub enum LookupError {
89    /// The specified object does not (currently) exist,
90    /// or the user does not have permission to access it.
91    #[error("No visible object with ID {0:?}")]
92    NoObject(ObjectId),
93
94    /// The specified object exists, but does not have the
95    /// expected type.
96    #[error("Unexpected type on object with ID {0:?}")]
97    WrongType(ObjectId),
98
99    /// The object once existed, but this is a weak reference,
100    /// and it has expired.
101    #[error("Weak reference {0:?} is no longer present")]
102    Expired(ObjectId),
103}
104
105impl LookupError {
106    /// Return the RpcErrorKind for this lookup error.
107    fn rpc_error_kind(&self) -> RpcErrorKind {
108        use LookupError as E;
109        use RpcErrorKind as EK;
110
111        match self {
112            E::NoObject(_) => EK::ObjectNotFound,
113            E::WrongType(_) => EK::InvalidRequest,
114            E::Expired(_) => EK::WeakReferenceExpired,
115        }
116    }
117}
118
119impl From<LookupError> for RpcError {
120    fn from(err: LookupError) -> Self {
121        RpcError::new(err.to_string(), err.rpc_error_kind())
122    }
123}
124
125/// A trait describing the context in which an RPC method is executed.
126pub trait Context: Send + Sync {
127    /// Look up an object by identity within this context.
128    fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>;
129
130    /// Create an owning reference to `object` within this context.
131    ///
132    /// Return an ObjectId for this object.
133    fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
134
135    /// Create a non-owning weak referene to `object` within this context.
136    ///
137    /// Return an ObjectId for this object.
138    fn register_weak(&self, object: &Arc<dyn Object>) -> ObjectId;
139
140    /// Drop a reference to the object called `object` within this context.
141    ///
142    /// This will return an error if `object` does not exist.
143    fn release(&self, object: &ObjectId) -> Result<(), LookupError>;
144
145    /// Return a dispatch table that can be used to invoke other RPC methods.
146    fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>;
147}
148
149/// An error caused while trying to send an update to a method.
150///
151/// These errors should be impossible in our current implementation, since they
152/// can only happen if the `mpsc::Receiver` is closed—which can only happen
153/// when the session loop drops it, which only happens when the session loop has
154/// stopped polling its `FuturesUnordered` full of RPC request futures. Thus, any
155/// `send` that would encounter this error should be in a future that is never
156/// polled under circumstances when the error could happen.
157///
158/// Still, programming errors are real, so we are handling this rather than
159/// declaring it a panic or something.
160#[derive(Debug, Clone, thiserror::Error)]
161#[non_exhaustive]
162pub enum SendUpdateError {
163    /// The request was cancelled, or the connection was closed.
164    #[error("Unable to send on MPSC connection")]
165    ConnectionClosed,
166}
167
168impl tor_error::HasKind for SendUpdateError {
169    fn kind(&self) -> tor_error::ErrorKind {
170        tor_error::ErrorKind::Internal
171    }
172}
173
174impl From<Infallible> for SendUpdateError {
175    fn from(_: Infallible) -> Self {
176        unreachable!()
177    }
178}
179impl From<futures::channel::mpsc::SendError> for SendUpdateError {
180    fn from(_: futures::channel::mpsc::SendError) -> Self {
181        SendUpdateError::ConnectionClosed
182    }
183}
184
185/// Extension trait for [`Context`].
186///
187/// This is a separate trait so that `Context` can be object-safe.
188pub trait ContextExt: Context {
189    /// Look up an object of a given type, and downcast it.
190    ///
191    /// Return an error if the object can't be found, or has the wrong type.
192    fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
193        self.lookup_object(id)?
194            .downcast_arc()
195            .map_err(|_| LookupError::WrongType(id.clone()))
196    }
197}
198
199impl<T: Context> ContextExt for T {}
200
201/// Try to find an appropriate function for calling a given RPC method on a
202/// given ObjectId.
203///
204/// On success, return a Future.
205///
206/// Differs from using `DispatchTable::invoke()` in that it drops its lock
207/// on the dispatch table before invoking the method.
208pub fn invoke_rpc_method(
209    ctx: Arc<dyn Context>,
210    obj_id: &ObjectId,
211    method: Box<dyn DynMethod>,
212    sink: dispatch::BoxedUpdateSink,
213) -> Result<dispatch::RpcResultFuture, InvokeError> {
214    match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
215        Err(InvokeError::NoDispatchBypass) => {
216            // fall through
217        }
218        other => return other,
219    }
220
221    let obj = ctx.lookup_object(obj_id).map_err(InvokeError::NoObject)?;
222
223    let (obj, invocable) = ctx
224        .dispatch_table()
225        .read()
226        .expect("poisoned lock")
227        .resolve_rpc_invoker(obj, method.as_ref())?;
228
229    invocable.invoke(obj, method, ctx, sink)
230}
231
232/// Invoke the given `method` on `obj` within `ctx`, and return its
233/// actual result type.
234///
235/// Unlike `invoke_rpc_method`, this method does not return a type-erased result,
236/// and does not require that the result can be serialized as an RPC object.
237///
238/// Differs from using `DispatchTable::invoke_special()` in that it drops its lock
239/// on the dispatch table before invoking the method.
240pub async fn invoke_special_method<M: Method>(
241    ctx: Arc<dyn Context>,
242    obj: Arc<dyn Object>,
243    method: Box<M>,
244) -> Result<Box<M::Output>, InvokeError> {
245    let (obj, invocable) = ctx
246        .dispatch_table()
247        .read()
248        .expect("poisoned lock")
249        .resolve_special_invoker::<M>(obj)?;
250
251    invocable
252        .invoke_special(obj, method, ctx)?
253        .await
254        .downcast()
255        .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
256}
257
258/// A serializable empty object.
259///
260/// Used when we need to declare that a method returns nothing.
261#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
262#[non_exhaustive]
263pub struct Nil {}
264/// An instance of rpc::Nil.
265pub const NIL: Nil = Nil {};
266
267/// Common return type for RPC methods that return a single object ID
268/// and nothing else.
269#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
270pub struct SingleIdResponse {
271    /// The ID of the object that we're returning.
272    id: ObjectId,
273}
274
275/// Error representing an "invalid" RPC identifier.
276#[derive(Clone, Debug, thiserror::Error)]
277#[non_exhaustive]
278#[cfg_attr(test, derive(Eq, PartialEq))]
279pub enum InvalidRpcIdentifier {
280    /// The method doesn't have a ':' to demarcate its namespace.
281    #[error("Identifier has no namespace separator")]
282    NoNamespace,
283
284    /// The method's namespace is not one we recognize.
285    #[error("Identifier has unrecognized namespace")]
286    UnrecognizedNamespace,
287
288    /// The method's name is not in snake_case.
289    #[error("Identifier name has unexpected format")]
290    BadIdName,
291}
292
293/// Check whether `method` is an expected and well-formed RPC identifier.
294///
295/// If `recognized_namespaces` is provided, only identifiers within those
296/// namespaces are accepted; otherwise, all namespaces are accepted.
297///
298/// (Examples of RPC identifiers are method names.)
299pub(crate) fn is_valid_rpc_identifier(
300    recognized_namespaces: Option<&HashSet<&str>>,
301    method: &str,
302) -> Result<(), InvalidRpcIdentifier> {
303    /// Return true if name is in acceptable format.
304    fn name_ok(n: &str) -> bool {
305        let mut chars = n.chars();
306        let Some(first) = chars.next() else {
307            return false;
308        };
309        first.is_ascii_lowercase()
310            && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
311    }
312    let (scope, name) = method
313        .split_once(':')
314        .ok_or(InvalidRpcIdentifier::NoNamespace)?;
315
316    if let Some(recognized_namespaces) = recognized_namespaces {
317        if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
318            return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
319        }
320    }
321    if !name_ok(name) {
322        return Err(InvalidRpcIdentifier::BadIdName);
323    }
324
325    Ok(())
326}
327
328#[cfg(test)]
329mod test {
330    // @@ begin test lint list maintained by maint/add_warning @@
331    #![allow(clippy::bool_assert_comparison)]
332    #![allow(clippy::clone_on_copy)]
333    #![allow(clippy::dbg_macro)]
334    #![allow(clippy::mixed_attributes_style)]
335    #![allow(clippy::print_stderr)]
336    #![allow(clippy::print_stdout)]
337    #![allow(clippy::single_char_pattern)]
338    #![allow(clippy::unwrap_used)]
339    #![allow(clippy::unchecked_time_subtraction)]
340    #![allow(clippy::useless_vec)]
341    #![allow(clippy::needless_pass_by_value)]
342    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
343
344    use futures::SinkExt as _;
345    use futures_await_test::async_test;
346
347    use super::*;
348    use crate::dispatch::test::{Ctx, GetKids, Swan};
349
350    #[async_test]
351    async fn invoke() {
352        let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
353        let discard = || Box::pin(futures::sink::drain().sink_err_into());
354        let id = ctx.register_owned(Arc::new(Swan));
355
356        let r = invoke_rpc_method(ctx.clone(), &id, Box::new(GetKids), discard())
357            .unwrap()
358            .await
359            .unwrap();
360        assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
361
362        let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
363            .await
364            .unwrap()
365            .unwrap();
366        assert_eq!(r.v, "cygnets");
367    }
368
369    #[test]
370    fn valid_method_names() {
371        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
372
373        for name in [
374            "arti:clone",
375            "arti:clone7",
376            "arti:clone_now",
377            "wombat:knish",
378            "x-foo:bar",
379        ] {
380            assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
381        }
382    }
383
384    #[test]
385    fn invalid_method_names() {
386        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
387        use InvalidRpcIdentifier as E;
388
389        for (name, expect_err) in [
390            ("arti-foo:clone", E::UnrecognizedNamespace),
391            ("fred", E::NoNamespace),
392            ("arti:", E::BadIdName),
393            ("arti:7clone", E::BadIdName),
394            ("arti:CLONE", E::BadIdName),
395            ("arti:clone-now", E::BadIdName),
396        ] {
397            assert_eq!(
398                is_valid_rpc_identifier(Some(&namespaces), name),
399                Err(expect_err)
400            );
401        }
402    }
403}