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
#![allow(clippy::cognitive_complexity)] // See arti#2556
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
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
pub mod dispatch;
53
mod err;
54
mod method;
55
mod obj;
56

            
57
use std::{collections::HashSet, convert::Infallible, sync::Arc};
58

            
59
pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
60
pub use err::{RpcError, RpcErrorKind};
61
pub use method::{
62
    DeserMethod, DynMethod, Method, NoUpdates, RpcMethod, check_method_names, is_method_name,
63
    iter_method_names,
64
};
65
pub use obj::{Object, ObjectArcExt, ObjectId};
66

            
67
#[cfg(feature = "describe-methods")]
68
pub use dispatch::description::RpcDispatchInformation;
69

            
70
#[cfg(feature = "describe-methods")]
71
#[doc(hidden)]
72
pub use dispatch::description::DelegationNote;
73

            
74
#[doc(hidden)]
75
pub use obj::cast::CastTable;
76
#[doc(hidden)]
77
pub use {
78
    derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
79
    method::MethodInfo_, paste, tor_async_utils, tor_error::internal, typetag,
80
};
81

            
82
/// Templates for use with [`derive_deftly`]
83
pub mod templates {
84
    pub use crate::method::derive_deftly_template_DynMethod;
85
    pub use crate::obj::derive_deftly_template_Object;
86
}
87

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

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

            
102
    /// The object once existed, but this is a weak reference,
103
    /// and it has expired.
104
    #[error("Weak reference {0:?} is no longer present")]
105
    Expired(ObjectId),
106
}
107

            
108
impl LookupError {
109
    /// Return the RpcErrorKind for this lookup error.
110
    fn rpc_error_kind(&self) -> RpcErrorKind {
111
        use LookupError as E;
112
        use RpcErrorKind as EK;
113

            
114
        match self {
115
            E::NoObject(_) => EK::ObjectNotFound,
116
            E::WrongType(_) => EK::InvalidRequest,
117
            E::Expired(_) => EK::WeakReferenceExpired,
118
        }
119
    }
120
}
121

            
122
impl From<LookupError> for RpcError {
123
    fn from(err: LookupError) -> Self {
124
        RpcError::new(err.to_string(), err.rpc_error_kind())
125
    }
126
}
127

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

            
133
    /// Create an owning reference to `object` within this context.
134
    ///
135
    /// Return an ObjectId for this object.
136
    fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
137

            
138
    /// Create a non-owning weak referene to `object` within this context.
139
    ///
140
    /// Return an ObjectId for this object.
141
    fn register_weak(&self, object: &Arc<dyn Object>) -> ObjectId;
142

            
143
    /// Drop a reference to the object called `object` within this context.
144
    ///
145
    /// This will return an error if `object` does not exist.
146
    fn release(&self, object: &ObjectId) -> Result<(), LookupError>;
147

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

            
152
/// An error caused while trying to send an update to a method.
153
///
154
/// These errors should be impossible in our current implementation, since they
155
/// can only happen if the `mpsc::Receiver` is closed—which can only happen
156
/// when the session loop drops it, which only happens when the session loop has
157
/// stopped polling its `FuturesUnordered` full of RPC request futures. Thus, any
158
/// `send` that would encounter this error should be in a future that is never
159
/// polled under circumstances when the error could happen.
160
///
161
/// Still, programming errors are real, so we are handling this rather than
162
/// declaring it a panic or something.
163
#[derive(Debug, Clone, thiserror::Error)]
164
#[non_exhaustive]
165
pub enum SendUpdateError {
166
    /// The request was cancelled, or the connection was closed.
167
    #[error("Unable to send on MPSC connection")]
168
    ConnectionClosed,
169
}
170

            
171
impl tor_error::HasKind for SendUpdateError {
172
    fn kind(&self) -> tor_error::ErrorKind {
173
        tor_error::ErrorKind::Internal
174
    }
175
}
176

            
177
impl From<Infallible> for SendUpdateError {
178
    fn from(_: Infallible) -> Self {
179
        unreachable!()
180
    }
181
}
182
impl From<futures::channel::mpsc::SendError> for SendUpdateError {
183
    fn from(_: futures::channel::mpsc::SendError) -> Self {
184
        SendUpdateError::ConnectionClosed
185
    }
186
}
187

            
188
/// Extension trait for [`Context`].
189
///
190
/// This is a separate trait so that `Context` can be object-safe.
191
pub trait ContextExt: Context {
192
    /// Look up an object of a given type, and downcast it.
193
    ///
194
    /// Return an error if the object can't be found, or has the wrong type.
195
    fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
196
        self.lookup_object(id)?
197
            .downcast_arc()
198
            .map_err(|_| LookupError::WrongType(id.clone()))
199
    }
200
}
201

            
202
impl<T: Context> ContextExt for T {}
203

            
204
/// Try to find an appropriate function for calling a given RPC method on a
205
/// given ObjectId.
206
///
207
/// On success, return a Future.
208
///
209
/// Differs from using `DispatchTable::invoke()` in that it drops its lock
210
/// on the dispatch table before invoking the method.
211
21
pub fn invoke_rpc_method(
212
21
    ctx: Arc<dyn Context>,
213
21
    obj_id: &ObjectId,
214
21
    method: Box<dyn DynMethod>,
215
21
    sink: dispatch::BoxedUpdateSink,
216
21
) -> Result<dispatch::RpcResultFuture, InvokeError> {
217
21
    match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
218
21
        Err(InvokeError::NoDispatchBypass) => {
219
21
            // fall through
220
21
        }
221
        other => return other,
222
    }
223

            
224
21
    let obj = ctx.lookup_object(obj_id).map_err(InvokeError::NoObject)?;
225

            
226
21
    let (obj, invocable) = ctx
227
21
        .dispatch_table()
228
21
        .read()
229
21
        .expect("poisoned lock")
230
21
        .resolve_rpc_invoker(obj, method.as_ref())?;
231

            
232
17
    invocable.invoke(obj, method, ctx, sink)
233
21
}
234

            
235
/// Invoke the given `method` on `obj` within `ctx`, and return its
236
/// actual result type.
237
///
238
/// Unlike `invoke_rpc_method`, this method does not return a type-erased result,
239
/// and does not require that the result can be serialized as an RPC object.
240
///
241
/// Differs from using `DispatchTable::invoke_special()` in that it drops its lock
242
/// on the dispatch table before invoking the method.
243
3
pub async fn invoke_special_method<M: Method>(
244
3
    ctx: Arc<dyn Context>,
245
3
    obj: Arc<dyn Object>,
246
3
    method: Box<M>,
247
3
) -> Result<Box<M::Output>, InvokeError> {
248
3
    let (obj, invocable) = ctx
249
3
        .dispatch_table()
250
3
        .read()
251
3
        .expect("poisoned lock")
252
3
        .resolve_special_invoker::<M>(obj)?;
253

            
254
3
    invocable
255
3
        .invoke_special(obj, method, ctx)?
256
3
        .await
257
3
        .downcast()
258
3
        .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
259
3
}
260

            
261
/// A serializable empty object.
262
///
263
/// Used when we need to declare that a method returns nothing.
264
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
265
#[non_exhaustive]
266
pub struct Nil {}
267
/// An instance of rpc::Nil.
268
pub const NIL: Nil = Nil {};
269

            
270
/// Common return type for RPC methods that return a single object ID
271
/// and nothing else.
272
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
273
pub struct SingleIdResponse {
274
    /// The ID of the object that we're returning.
275
    id: ObjectId,
276
}
277

            
278
/// Error representing an "invalid" RPC identifier.
279
#[derive(Clone, Debug, thiserror::Error)]
280
#[non_exhaustive]
281
#[cfg_attr(test, derive(Eq, PartialEq))]
282
pub enum InvalidRpcIdentifier {
283
    /// The method doesn't have a ':' to demarcate its namespace.
284
    #[error("Identifier has no namespace separator")]
285
    NoNamespace,
286

            
287
    /// The method's namespace is not one we recognize.
288
    #[error("Identifier has unrecognized namespace")]
289
    UnrecognizedNamespace,
290

            
291
    /// The method's name is not in snake_case.
292
    #[error("Identifier name has unexpected format")]
293
    BadIdName,
294
}
295

            
296
/// Check whether `method` is an expected and well-formed RPC identifier.
297
///
298
/// If `recognized_namespaces` is provided, only identifiers within those
299
/// namespaces are accepted; otherwise, all namespaces are accepted.
300
///
301
/// (Examples of RPC identifiers are method names.)
302
1134
pub(crate) fn is_valid_rpc_identifier(
303
1134
    recognized_namespaces: Option<&HashSet<&str>>,
304
1134
    method: &str,
305
1134
) -> Result<(), InvalidRpcIdentifier> {
306
    /// Return true if name is in acceptable format.
307
1132
    fn name_ok(n: &str) -> bool {
308
1132
        let mut chars = n.chars();
309
1132
        let Some(first) = chars.next() else {
310
1
            return false;
311
        };
312
1131
        first.is_ascii_lowercase()
313
15487
            && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
314
1132
    }
315
1134
    let (scope, name) = method
316
1134
        .split_once(':')
317
1134
        .ok_or(InvalidRpcIdentifier::NoNamespace)?;
318

            
319
1133
    if let Some(recognized_namespaces) = recognized_namespaces {
320
1132
        if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
321
1
            return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
322
1131
        }
323
1
    }
324
1132
    if !name_ok(name) {
325
4
        return Err(InvalidRpcIdentifier::BadIdName);
326
1128
    }
327

            
328
1128
    Ok(())
329
1134
}
330

            
331
#[cfg(test)]
332
mod test {
333
    // @@ begin test lint list maintained by maint/add_warning @@
334
    #![allow(clippy::bool_assert_comparison)]
335
    #![allow(clippy::clone_on_copy)]
336
    #![allow(clippy::dbg_macro)]
337
    #![allow(clippy::mixed_attributes_style)]
338
    #![allow(clippy::print_stderr)]
339
    #![allow(clippy::print_stdout)]
340
    #![allow(clippy::single_char_pattern)]
341
    #![allow(clippy::unwrap_used)]
342
    #![allow(clippy::unchecked_time_subtraction)]
343
    #![allow(clippy::useless_vec)]
344
    #![allow(clippy::needless_pass_by_value)]
345
    #![allow(clippy::string_slice)] // See arti#2571
346
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
347

            
348
    use futures::SinkExt as _;
349
    use futures_await_test::async_test;
350

            
351
    use super::*;
352
    use crate::dispatch::test::{Ctx, GetKids, Swan};
353

            
354
    #[async_test]
355
    async fn invoke() {
356
        let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
357
        let discard = || Box::pin(futures::sink::drain().sink_err_into());
358
        let id = ctx.register_owned(Arc::new(Swan));
359

            
360
        let r = invoke_rpc_method(ctx.clone(), &id, Box::new(GetKids), discard())
361
            .unwrap()
362
            .await
363
            .unwrap();
364
        assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
365

            
366
        let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
367
            .await
368
            .unwrap()
369
            .unwrap();
370
        assert_eq!(r.v, "cygnets");
371
    }
372

            
373
    #[test]
374
    fn valid_method_names() {
375
        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
376

            
377
        for name in [
378
            "arti:clone",
379
            "arti:clone7",
380
            "arti:clone_now",
381
            "wombat:knish",
382
            "x-foo:bar",
383
        ] {
384
            assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
385
        }
386
    }
387

            
388
    #[test]
389
    fn invalid_method_names() {
390
        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
391
        use InvalidRpcIdentifier as E;
392

            
393
        for (name, expect_err) in [
394
            ("arti-foo:clone", E::UnrecognizedNamespace),
395
            ("fred", E::NoNamespace),
396
            ("arti:", E::BadIdName),
397
            ("arti:7clone", E::BadIdName),
398
            ("arti:CLONE", E::BadIdName),
399
            ("arti:clone-now", E::BadIdName),
400
        ] {
401
            assert_eq!(
402
                is_valid_rpc_identifier(Some(&namespaces), name),
403
                Err(expect_err)
404
            );
405
        }
406
    }
407
}