1
//! Middle-level API for RPC connections
2
//!
3
//! This module focuses around the `RpcConn` type, which supports sending RPC requests
4
//! and matching them with their responses.
5

            
6
use std::{
7
    io::{self},
8
    sync::{Arc, Mutex},
9
};
10

            
11
use crate::msgs::{
12
    AnyRequestId, ObjectId,
13
    request::InvalidRequestError,
14
    response::{ResponseKind, RpcError, ValidatedResponse},
15
};
16

            
17
mod auth;
18
mod builder;
19
mod connimpl;
20
mod stream;
21

            
22
use crate::util::Utf8CString;
23
pub use builder::{BuilderError, ConnPtDescription, RpcConnBuilder};
24
pub use connimpl::{RpcConn, RpcPoll, WouldBlock};
25
use serde::{Deserialize, de::DeserializeOwned};
26
pub use stream::StreamError;
27
use tor_rpc_connect::{HasClientErrorAction, auth::cookie::CookieAccessError};
28

            
29
/// A user-provided tag used to identify requests provided to
30
/// [`RpcConn::submit`].
31
///
32
/// Most users will want to crate tags that are unique
33
/// for the lifetime of their associated requests.
34
/// This is not enforced: the only drawback of duplicating tags
35
/// is that you will not be able to use them to distinguish
36
/// which reply is which.
37
///
38
/// This is distinct from the request ID type (represented by [`AnyRequestId`])
39
/// that is sent to the RPC server with each request
40
/// and returned along with each corresponding response.
41
/// By contrast, a `UserTag` is never sent to the RPC server,
42
/// and therefore is safe to use with information
43
/// (like callback and data pointers)
44
/// which it would not be safe to take from an untrusted source.
45
//
46
// Note: The tag is chosen to be two pointers in size,
47
// to accommodate C implementations that want to
48
// stuff a `void fn(void*), void*` inside of one of these.
49
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
50
#[allow(clippy::exhaustive_structs)]
51
pub struct UserTag(pub usize, pub usize);
52

            
53
/// A handle to an open request.
54
///
55
/// These handles are created with [`RpcConn::execute_with_handle`].
56
///
57
/// Note that dropping a RequestHandle does not cancel the associated request:
58
/// it will continue running, but you won't have a way to receive updates from it.
59
/// To cancel a request, use [`RpcConn::cancel`].
60
#[derive(educe::Educe)]
61
#[educe(Debug)]
62
pub struct RequestHandle {
63
    /// The underlying `Receiver` that we'll use to get updates for this request
64
    ///
65
    /// It's wrapped in a `Mutex` to prevent concurrent calls to `Receiver::wait_on_message_for`.
66
    //
67
    // NOTE: As an alternative to using a Mutex here, we _could_ remove
68
    // the restriction from `wait_on_message_for` that says that only one thread
69
    // may be waiting on a given request ID at once.  But that would introduce
70
    // complexity to the implementation,
71
    // and it's not clear that the benefit would be worth it.
72
    #[educe(Debug(ignore))]
73
    conn: Mutex<Arc<connimpl::Receiver>>,
74
    /// The ID of this request.
75
    id: AnyRequestId,
76
}
77

            
78
// TODO RPC: Possibly abolish these types.
79
//
80
// I am keeping this for now because it makes it more clear that we can never reinterpret
81
// a success as an update or similar.
82
//
83
// I am not at all pleased with these types; we should revise them.
84
//
85
// TODO RPC: Possibly, all of these should be reconstructed
86
// from their serde_json::Values rather than forwarded verbatim.
87
// (But why would we our json to be more canonical than arti's? See #1491.)
88
//
89
// DODGY TYPES BEGIN: TODO RPC
90

            
91
/// A Success Response from Arti, indicating that a request was successful.
92
///
93
/// This is the complete message, including `id` and `result` fields.
94
//
95
// Invariant: it is valid JSON and contains no NUL bytes or newlines.
96
// TODO RPC: check that the newline invariant is enforced in constructors.
97
#[derive(Clone, Debug, derive_more::AsRef, derive_more::Into)]
98
#[as_ref(forward)]
99
pub struct SuccessResponse(Utf8CString);
100

            
101
impl SuccessResponse {
102
    /// Decode the `result` field of this response as an instance of D.
103
    ///
104
    /// The parameter `D` should be deserializable from a json Object (a.k.a, a map).
105
1010
    pub fn decode<D: DeserializeOwned>(&self) -> Result<D, serde_json::Error> {
106
        /// Helper object for decoding the "result" field.
107
        #[derive(Deserialize)]
108
        struct Response<R> {
109
            /// The decoded value.
110
            result: R,
111
        }
112
1010
        let response: Response<D> = serde_json::from_str(self.as_ref())?;
113
1010
        Ok(response.result)
114
1010
    }
115
}
116

            
117
/// An Update Response from Arti, with information about the progress of a request.
118
///
119
/// This is the complete message, including `id` and `update` fields.
120
//
121
// Invariant: it is valid JSON and contains no NUL bytes or newlines.
122
// TODO RPC: check that the newline invariant is enforced in constructors.
123
// TODO RPC consider changing this to CString.
124
#[derive(Clone, Debug, derive_more::AsRef, derive_more::Into)]
125
#[as_ref(forward)]
126
pub struct UpdateResponse(Utf8CString);
127

            
128
impl UpdateResponse {
129
    /// Decode the `result` field of this response as an instance of D.
130
    ///
131
    /// The parameter `D` should be deserializable from a json Object (a.k.a, a map).
132
    pub fn decode<D: DeserializeOwned>(&self) -> Result<D, serde_json::Error> {
133
        /// Helper object for decoding the "update" field.
134
        #[derive(Deserialize)]
135
        struct Update<R> {
136
            /// The decoded value.
137
            update: R,
138
        }
139
        let response: Update<D> = serde_json::from_str(self.as_ref())?;
140
        Ok(response.update)
141
    }
142
}
143

            
144
/// A Error Response from Arti, indicating that an error occurred.
145
///
146
/// (This is the complete message, including the `error` field.
147
/// It also an `id` if it
148
/// is in response to a request; but not if it is a fatal protocol error.)
149
//
150
// Invariant: Does not contain a NUL. (Safe to convert to CString.)
151
//
152
// Invariant: This field MUST encode a response whose body is an RPC error.
153
//
154
// Otherwise the `decode` method may panic.
155
//
156
// TODO RPC: check that the newline invariant is enforced in constructors.
157
#[derive(Clone, Debug, derive_more::AsRef, derive_more::Into)]
158
#[as_ref(forward)]
159
// TODO: If we keep this, it should implement Error.
160
pub struct ErrorResponse(Utf8CString);
161
impl ErrorResponse {
162
    /// Construct an ErrorResponse from the Error reply.
163
    ///
164
    /// This not a From impl because we want it to be crate-internal.
165
1041
    pub(crate) fn from_validated_string(s: Utf8CString) -> Self {
166
1041
        ErrorResponse(s)
167
1041
    }
168

            
169
    /// Convert this response into an internal error in response to `cmd`.
170
    ///
171
    /// This is only appropriate when the error cannot be caused because of user behavior.
172
    pub(crate) fn internal_error(&self, cmd: &str) -> ProtoError {
173
        ProtoError::InternalRequestFailed(UnexpectedReply {
174
            request: cmd.to_string(),
175
            reply: self.to_string(),
176
            problem: UnexpectedReplyProblem::ErrorNotExpected,
177
        })
178
    }
179

            
180
    /// Try to interpret this response as an [`RpcError`].
181
1039
    pub fn decode(&self) -> RpcError {
182
1039
        crate::msgs::response::try_decode_response_as_err(self.0.as_ref())
183
1039
            .expect("Could not decode response that was already decoded as an error?")
184
1039
            .expect("Could not extract error from response that was already decoded as an error?")
185
1039
    }
186
}
187

            
188
impl std::fmt::Display for ErrorResponse {
189
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190
        let e = self.decode();
191
        write!(f, "Peer said {:?}", e.message())
192
    }
193
}
194

            
195
/// A final response -- that is, the last one that we expect to receive for a request.
196
///
197
type FinalResponse = Result<SuccessResponse, ErrorResponse>;
198

            
199
/// Any of the three types of Arti responses.
200
#[derive(Clone, Debug)]
201
#[allow(clippy::exhaustive_enums)]
202
pub enum AnyResponse {
203
    /// The request has succeeded; no more response will be given.
204
    Success(SuccessResponse),
205
    /// The request has failed; no more response will be given.
206
    Error(ErrorResponse),
207
    /// An incremental update; more messages may arrive.
208
    Update(UpdateResponse),
209
}
210
// TODO RPC: DODGY TYPES END.
211

            
212
impl AnyResponse {
213
    /// Convert `v` into `AnyResponse`.
214
4087
    fn from_validated(v: ValidatedResponse) -> Self {
215
        // TODO RPC, Perhaps unify AnyResponse with ValidatedResponse, once we are sure what
216
        // AnyResponse should look like.
217
4087
        match v.meta.kind {
218
1039
            ResponseKind::Error => AnyResponse::Error(ErrorResponse::from_validated_string(v.msg)),
219
1010
            ResponseKind::Success => AnyResponse::Success(SuccessResponse(v.msg)),
220
2038
            ResponseKind::Update => AnyResponse::Update(UpdateResponse(v.msg)),
221
        }
222
4087
    }
223

            
224
    /// Consume this `AnyResponse`, and return its internal string.
225
    #[cfg(feature = "ffi")]
226
    pub(crate) fn into_string(self) -> Utf8CString {
227
        match self {
228
            AnyResponse::Success(m) => m.into(),
229
            AnyResponse::Error(m) => m.into(),
230
            AnyResponse::Update(m) => m.into(),
231
        }
232
    }
233

            
234
    /// Try to deserialize this response into either a known success type,
235
    /// or a known update type.
236
    ///
237
    /// If the response does not actually conform to those types,
238
    /// return a [serde_json::Error].
239
    ///
240
    /// If no updates are allowable, set the parameter U to NoneExpected.
241
    /// If no (final) successes are allowable, set the parameter S to NoneExpected.
242
    ///
243
    /// This will cause disallowed updates/successes to cause an error.
244
    pub fn decode<S, U>(&self) -> Result<Result<DecodedResponse<S, U>, RpcError>, serde_json::Error>
245
    where
246
        S: serde::de::DeserializeOwned,
247
        U: serde::de::DeserializeOwned,
248
    {
249
        Ok(match self {
250
            AnyResponse::Success(r) => Ok(DecodedResponse::Success(r.decode()?)),
251
            AnyResponse::Update(r) => Ok(DecodedResponse::Update(r.decode()?)),
252
            AnyResponse::Error(r) => Err(r.decode()),
253
        })
254
    }
255
}
256

            
257
impl AsRef<str> for AnyResponse {
258
    fn as_ref(&self) -> &str {
259
        match self {
260
            AnyResponse::Success(r) => r.as_ref(),
261
            AnyResponse::Error(r) => r.as_ref(),
262
            AnyResponse::Update(r) => r.as_ref(),
263
        }
264
    }
265
}
266

            
267
/// A decoded, non-error response to an RPC command.
268
///
269
/// The parameter S represents the success type;
270
/// the parameter U represents the update type.
271
/// Both should be decodable from json Objects (a.k.a maps).
272
#[derive(Clone, Debug)]
273
#[allow(clippy::exhaustive_enums)]
274
pub enum DecodedResponse<S, U = NoneExpected> {
275
    /// A decoded successful response from Arti
276
    Success(S),
277

            
278
    /// A decoded non-final response from Arti.
279
    Update(U),
280
}
281

            
282
/// An uninhabited structure representing a situation where the success or update case
283
/// of a [`DecodedResponse`] is not expected to be present.
284
///
285
/// Attempting to deserialize one of these will produce an error.
286
//
287
// We can't use !, because it isn't available at our MSRV.
288
// We can't use void::Void directly, because it doesn't implement Deserialize.
289
#[derive(Clone, Debug)]
290
pub struct NoneExpected(void::Void);
291

            
292
impl<'de> serde::Deserialize<'de> for NoneExpected {
293
    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
294
    where
295
        D: serde::Deserializer<'de>,
296
    {
297
        use serde::de::Error as _;
298
        Err(D::Error::custom(
299
            "Encountered an update (or reply) where none was expected",
300
        ))
301
    }
302
}
303

            
304
impl<S> DecodedResponse<S, NoneExpected> {
305
    /// Consume this [`DecodedResponse`], and return its successful response.
306
    ///
307
    /// (Note the type requirement on `Self`: this method requires
308
    /// that the update parameter `U` is [`NoneExpected`])
309
    pub fn unwrap(self) -> S {
310
        match self {
311
            DecodedResponse::Success(s) => s,
312
            DecodedResponse::Update(NoneExpected(void)) => void::unreachable(void),
313
        }
314
    }
315
}
316

            
317
impl<U> DecodedResponse<NoneExpected, U> {
318
    /// Consume this [`DecodedResponse`], and return its update response.
319
    ///
320
    /// (Note the type requirement on `Self`: this method requires
321
    /// that the successful-response parameter `S` is [`NoneExpected`])
322
    pub fn unwrap_update(self) -> U {
323
        match self {
324
            DecodedResponse::Success(NoneExpected(void)) => void::unreachable(void),
325
            DecodedResponse::Update(u) => u,
326
        }
327
    }
328
}
329

            
330
impl RpcConn {
331
    /// Return the ObjectId for the negotiated Session.
332
    ///
333
    /// Nearly all RPC methods require a Session, or some other object
334
    /// accessed via the session.
335
    ///
336
    /// (This function will only return None if no authentication has been performed.
337
    /// TODO RPC: It is not currently possible to make an unauthenticated connection.)
338
    pub fn session(&self) -> Option<&ObjectId> {
339
        self.session.as_ref()
340
    }
341

            
342
    /// Run a command, and wait for success or failure.
343
    ///
344
    /// Note that this function will return `Err(.)` only if sending the command or getting a
345
    /// response failed.
346
    /// If the command was sent successfully, and Arti reported an error in response,
347
    /// this function returns `Ok(Err(.))`.
348
    ///
349
    /// Note that the command does not need to include an `id` field.  If you omit it,
350
    /// one will be generated.
351
49
    pub fn execute(&self, cmd: &str) -> Result<FinalResponse, ProtoError> {
352
49
        let hnd = self.execute_with_handle(cmd)?;
353
44
        hnd.wait()
354
49
    }
355

            
356
    /// Helper for executing internally-generated requests and decoding their results.
357
    ///
358
    /// Behaves like `execute`, except on success, where it tries to decode the `result` field
359
    /// of the response as a `T`.
360
    ///
361
    /// Use this method in cases where it's reasonable for Arti to sometimes return an RPC error:
362
    /// in other words, where it's not necessarily a programming error or version mismatch.
363
    ///
364
    /// Don't use this for user-generated requests: it will misreport unexpected replies
365
    /// as internal errors.
366
1
    pub(crate) fn execute_internal<T: DeserializeOwned>(
367
1
        &self,
368
1
        cmd: &str,
369
1
    ) -> Result<Result<T, ErrorResponse>, ProtoError> {
370
1
        match self.execute(cmd)? {
371
1
            Ok(success) => match success.decode::<T>() {
372
1
                Ok(result) => Ok(Ok(result)),
373
                Err(json_error) => Err(ProtoError::InternalRequestFailed(UnexpectedReply {
374
                    request: cmd.to_string(),
375
                    reply: Utf8CString::from(success).to_string(),
376
                    problem: UnexpectedReplyProblem::CannotDecode(Arc::new(json_error)),
377
                })),
378
            },
379
            Err(error) => Ok(Err(error)),
380
        }
381
1
    }
382

            
383
    /// Helper for executing internally-generated requests and decoding their results.
384
    ///
385
    /// Behaves like `execute_internal`, except that it treats any RPC error reply
386
    /// as an internal error or version mismatch.
387
    ///
388
    /// Don't use this for user-generated requests, or for requests that can fail because of
389
    /// incorrect user inputs: it will misreport failures in those requests as internal errors.
390
1
    pub(crate) fn execute_internal_ok<T: DeserializeOwned>(
391
1
        &self,
392
1
        cmd: &str,
393
1
    ) -> Result<T, ProtoError> {
394
1
        match self.execute_internal(cmd)? {
395
1
            Ok(v) => Ok(v),
396
            Err(err_response) => Err(err_response.internal_error(cmd)),
397
        }
398
1
    }
399

            
400
    /// Cancel a request by ID.
401
    pub fn cancel(&self, request_id: &AnyRequestId) -> Result<(), ProtoError> {
402
        /// Arguments to an `rpc::cancel` request.
403
        #[derive(serde::Serialize, Debug)]
404
        struct CancelParams<'a> {
405
            /// The request to cancel.
406
            request_id: &'a AnyRequestId,
407
        }
408

            
409
        let request = crate::msgs::request::Request::new(
410
            ObjectId::connection_id(),
411
            "rpc:cancel",
412
            CancelParams { request_id },
413
        );
414
        match self.execute_internal::<EmptyReply>(&request.encode()?)? {
415
            Ok(EmptyReply {}) => Ok(()),
416
            Err(_) => Err(ProtoError::RequestCompleted),
417
        }
418
    }
419

            
420
    /// Like `execute`, but don't wait.  This lets the caller see the
421
    /// request ID and  maybe cancel it.
422
2097
    pub fn execute_with_handle(&self, cmd: &str) -> Result<RequestHandle, ProtoError> {
423
2097
        self.send_waitable_request(cmd)
424
2097
    }
425
    /// As execute(), but run update_cb for every update we receive.
426
2048
    pub fn execute_with_updates<F>(
427
2048
        &self,
428
2048
        cmd: &str,
429
2048
        mut update_cb: F,
430
2048
    ) -> Result<FinalResponse, ProtoError>
431
2048
    where
432
2048
        F: FnMut(UpdateResponse) + Send + Sync,
433
    {
434
2048
        let hnd = self.execute_with_handle(cmd)?;
435
        loop {
436
4086
            match hnd.wait_with_updates()? {
437
1009
                AnyResponse::Success(s) => return Ok(Ok(s)),
438
1039
                AnyResponse::Error(e) => return Ok(Err(e)),
439
2038
                AnyResponse::Update(u) => update_cb(u),
440
            }
441
        }
442
2048
    }
443

            
444
    /// As execute(), but do not wait for a response.
445
    ///
446
    /// Instead, the caller must provide a [`UserTag`] to identify a particular request,
447
    /// and must make sure that responses are being processed via [`wait()`](Self::wait).
448
    ///
449
    /// (If nobody is running `wait()`, then responses will never be handled,
450
    /// and can potentially fill up memory.)
451
    pub fn submit(&self, tag: UserTag, cmd: &str) -> Result<(), ProtoError> {
452
        self.send_pollable_request(tag, cmd)
453
    }
454

            
455
    /// Helper: Tell Arti to release `obj`.
456
    ///
457
    /// Do not use this method for a user-provided object ID:
458
    /// It gives an internal error if the object does not exist.
459
    pub(crate) fn release_obj(&self, obj: ObjectId) -> Result<(), ProtoError> {
460
        let release_request = crate::msgs::request::Request::new(obj, "rpc:release", NoParams {});
461
        let _empty_response: EmptyReply = self.execute_internal_ok(&release_request.encode()?)?;
462
        Ok(())
463
    }
464

            
465
    /// Wait for a response to arrive for a request that was sent via [`submit()`](Self::submit).
466
    ///
467
    /// Return that response,
468
    /// along with the [`UserTag`] that was associated with its request.
469
    ///
470
    /// This method will never return responses
471
    /// to any requests made with one of the `execute` methods;
472
    /// only to requests submitted with `submit()`.
473
    ///
474
    /// It is safe, but generally pointless, to call this method from multiple threads.
475
    pub fn wait(&self) -> Result<(UserTag, AnyResponse), ProtoError> {
476
        let (tag, r) = self.receiver.wait_on_pollable_response()?;
477
        Ok((tag, AnyResponse::from_validated(r)))
478
    }
479

            
480
    /// Shut down this connection and stop sending or receiving data.
481
    ///
482
    /// The precise behavior is controlled by `how`.
483
    pub fn shutdown(&self, how: ShutdownKind) -> Result<(), ProtoError> {
484
        match how {
485
            ShutdownKind::Immediate => {
486
                self.begin_closing()?;
487
                Ok(())
488
            }
489
        }
490
    }
491

            
492
    // TODO RPC: shutdown() on the socket on Drop.
493
}
494

            
495
/// A description of how to shut down an [`RpcConn`].
496
///
497
/// Used as an argument to [`RpcConn::shutdown()`].
498
#[derive(Debug, Clone, Copy)]
499
#[non_exhaustive]
500
pub enum ShutdownKind {
501
    /// Stop writing requests or accepting responses.
502
    ///
503
    /// If a request has been queued but a reply has not yet been received for that request,
504
    /// it is indeterminate whether that request will actually be sent,
505
    /// or whether it will be dropped from the outgoing queue.
506
    /// If you require a request to be executed, wait until a reply has been received
507
    /// before you shut down the RPC connection.
508
    ///
509
    /// It is unspecified whether the underlying socket is closed immediately,
510
    /// or whether it will only close when the [`RpcConn`] is dropped.
511
    Immediate,
512
}
513

            
514
impl RequestHandle {
515
    /// Return the ID of this request, to help cancelling it.
516
    pub fn id(&self) -> &AnyRequestId {
517
        &self.id
518
    }
519
    /// Wait for success or failure, and return what happened.
520
    ///
521
    /// (Ignores any update messages that are received.)
522
    ///
523
    /// Note that this function will return `Err(.)` only if sending the command or getting a
524
    /// response failed.
525
    /// If the command was sent successfully, and Arti reported an error in response,
526
    /// this function returns `Ok(Err(.))`.
527
44
    pub fn wait(self) -> Result<FinalResponse, ProtoError> {
528
        loop {
529
44
            match self.wait_with_updates()? {
530
1
                AnyResponse::Success(s) => return Ok(Ok(s)),
531
                AnyResponse::Error(e) => return Ok(Err(e)),
532
                AnyResponse::Update(_) => {}
533
            }
534
        }
535
44
    }
536
    /// Wait for the next success, failure, or update from this handle.
537
    ///
538
    /// Note that this function will return `Err(.)` only if sending the command or getting a
539
    /// response failed.
540
    /// If the command was sent successfully, and Arti reported an error in response,
541
    /// this function returns `Ok(AnyResponse::Error(.))`.
542
    ///
543
    /// You may call this method on the same `RequestHandle` from multiple threads.
544
    /// If you do so, those calls will receive responses (or errors) in an unspecified order.
545
    ///
546
    /// If this function returns Success or Error, then you shouldn't call it again.
547
    /// All future calls to this function will fail with `CmdError::RequestCancelled`.
548
    /// (TODO RPC: Maybe rename that error.)
549
4130
    pub fn wait_with_updates(&self) -> Result<AnyResponse, ProtoError> {
550
4130
        let conn = self.conn.lock().expect("Poisoned lock");
551
4130
        let validated = conn.wait_on_message_for(&self.id)?;
552
4087
        Ok(AnyResponse::from_validated(validated))
553
4130
    }
554

            
555
    // TODO RPC: Sketch out how we would want to do this in an async world,
556
    // or with poll
557
}
558

            
559
/// An error (or other condition) that has caused an RPC connection to shut down.
560
#[derive(Clone, Debug, thiserror::Error)]
561
#[non_exhaustive]
562
pub enum ShutdownError {
563
    // TODO nb: Read/Write are no longer well separated in the API.
564
    //
565
    /// Io error occurred while reading.
566
    #[error("Unable to read response")]
567
    Read(#[source] Arc<io::Error>),
568
    /// Io error occurred while writing.
569
    #[error("Unable to write request")]
570
    Write(#[source] Arc<io::Error>),
571
    /// Something was wrong with Arti's responses; this is a protocol violation.
572
    #[error("Arti sent a message that didn't conform to the RPC protocol: {0:?}")]
573
    ProtocolViolated(String),
574
    /// Arti has told us that we violated the protocol somehow.
575
    #[error("Arti reported a fatal error: {0:?}")]
576
    ProtocolViolationReport(ErrorResponse),
577
    /// The underlying connection closed.
578
    ///
579
    /// This probably means that Arti has shut down.
580
    #[error("Connection closed")]
581
    ConnectionClosed,
582
    /// The [`RpcConn::shutdown`] method was called, and either interrupted this
583
    /// operation, or prevented it from beginning.
584
    #[error("User-initiated shutdown")]
585
    UserShutdown,
586
}
587

            
588
impl From<crate::msgs::response::DecodeResponseError> for ShutdownError {
589
2
    fn from(value: crate::msgs::response::DecodeResponseError) -> Self {
590
        use crate::msgs::response::DecodeResponseError::*;
591
        use ShutdownError as E;
592
2
        match value {
593
1
            JsonProtocolViolation(e) => E::ProtocolViolated(e.to_string()),
594
            ProtocolViolation(s) => E::ProtocolViolated(s.to_string()),
595
1
            Fatal(rpc_err) => E::ProtocolViolationReport(rpc_err),
596
        }
597
2
    }
598
}
599

            
600
/// An error that has occurred while launching an RPC command.
601
#[derive(Clone, Debug, thiserror::Error)]
602
#[non_exhaustive]
603
pub enum ProtoError {
604
    /// The RPC connection failed, was closed by the other side,
605
    /// or was closed by an API call.
606
    #[error("RPC connection is shut down")]
607
    Shutdown(#[from] ShutdownError),
608

            
609
    /// There was a problem in the request we tried to send.
610
    #[error("Invalid request")]
611
    InvalidRequest(#[from] InvalidRequestError),
612

            
613
    /// We tried to send a request with an ID that was already pending.
614
    #[error("Request ID already in use.")]
615
    RequestIdInUse,
616

            
617
    /// We tried to wait for or inspect a request that had already succeeded or failed.
618
    #[error("Request has already completed (or failed)")]
619
    RequestCompleted,
620

            
621
    /// We tried to wait for the same request more than once.
622
    ///
623
    /// (This should be impossible.)
624
    #[error("Internal error: waiting on the same request more than once at a time.")]
625
    DuplicateWait,
626

            
627
    /// We got an internal error while trying to encode an RPC request.
628
    ///
629
    /// (This should be impossible.)
630
    #[error("Internal error while encoding request")]
631
    CouldNotEncode(#[source] Arc<serde_json::Error>),
632

            
633
    /// We tried to wait on a request that was not created with a queue.
634
    ///
635
    /// (This should be impossible).
636
    #[error("Internal error: waiting on a request created for polling.")]
637
    RequestNotWaitable,
638

            
639
    /// We got a response to some internally generated request that wasn't what we expected.
640
    #[error("{0}")]
641
    InternalRequestFailed(#[source] UnexpectedReply),
642
}
643

            
644
/// A set of errors encountered while trying to connect to the Arti process
645
#[derive(Clone, Debug, thiserror::Error)]
646
pub struct ConnectFailure {
647
    /// A list of all the declined connect points we encountered, and how they failed.
648
    declined: Vec<(builder::ConnPtDescription, ConnectError)>,
649
    /// A description of where we found the final error (if it's an abort.)
650
    final_desc: Option<builder::ConnPtDescription>,
651
    /// The final error explaining why we couldn't connect.
652
    ///
653
    /// This is either an abort, an AllAttemptsDeclined, or an error that prevented the
654
    /// search process from even beginning.
655
    #[source]
656
    pub(crate) final_error: ConnectError,
657
}
658

            
659
impl std::fmt::Display for ConnectFailure {
660
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
661
        write!(f, "Unable to connect")?;
662
        if !self.declined.is_empty() {
663
            write!(
664
                f,
665
                " ({} attempts failed{})",
666
                self.declined.len(),
667
                if matches!(self.final_error, ConnectError::AllAttemptsDeclined) {
668
                    ""
669
                } else {
670
                    " before fatal error"
671
                }
672
            )?;
673
        }
674
        Ok(())
675
    }
676
}
677

            
678
impl ConnectFailure {
679
    /// If this attempt failed because of a fatal error that made a connect point attempt abort,
680
    /// return a description of the origin of that connect point.
681
    pub fn fatal_error_origin(&self) -> Option<&builder::ConnPtDescription> {
682
        self.final_desc.as_ref()
683
    }
684

            
685
    /// For each connect attempt that failed nonfatally, return a description of the
686
    /// origin of that connect point, and the error that caused it to fail.
687
    pub fn declined_attempt_outcomes(
688
        &self,
689
    ) -> impl Iterator<Item = (&builder::ConnPtDescription, &ConnectError)> {
690
        // Note: this map looks like a no-op, but isn't.
691
        self.declined.iter().map(|(a, b)| (a, b))
692
    }
693

            
694
    /// Return a helper type to format this error, and all of its internal errors recursively.
695
    ///
696
    /// Unlike [`tor_error::Report`], this method includes not only fatal errors, but also
697
    /// information about connect attempts that failed nonfatally.
698
    pub fn display_verbose(&self) -> ConnectFailureVerboseFmt<'_> {
699
        ConnectFailureVerboseFmt(self)
700
    }
701
}
702

            
703
/// Helper type to format a ConnectFailure along with all of its internal errors,
704
/// including non-fatal errors.
705
#[derive(Debug, Clone)]
706
pub struct ConnectFailureVerboseFmt<'a>(&'a ConnectFailure);
707

            
708
impl<'a> std::fmt::Display for ConnectFailureVerboseFmt<'a> {
709
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
710
        use tor_error::ErrorReport as _;
711
        writeln!(f, "{}:", self.0)?;
712
        for (idx, (origin, error)) in self.0.declined_attempt_outcomes().enumerate() {
713
            writeln!(f, "  {}. {}: {}", idx + 1, origin, error.report())?;
714
        }
715
        if let Some(origin) = self.0.fatal_error_origin() {
716
            writeln!(
717
                f,
718
                "  {}. [FATAL] {}: {}",
719
                self.0.declined.len() + 1,
720
                origin,
721
                self.0.final_error.report()
722
            )?;
723
        } else {
724
            writeln!(f, "  - {}", self.0.final_error.report())?;
725
        }
726
        Ok(())
727
    }
728
}
729

            
730
/// An error while trying to connect to the Arti process.
731
#[derive(Clone, Debug, thiserror::Error)]
732
#[non_exhaustive]
733
pub enum ConnectError {
734
    /// Unable to parse connect points from an environment variable.
735
    #[error("Cannot parse connect points from environment variable")]
736
    BadEnvironment,
737
    /// We were unable to load and/or parse a given connect point.
738
    #[error("Unable to load and parse connect point")]
739
    CannotParse(#[from] tor_rpc_connect::load::LoadError),
740
    /// The path used to specify a connect file couldn't be resolved.
741
    #[error("Unable to resolve connect point path")]
742
    CannotResolvePath(#[source] tor_config_path::CfgPathError),
743
    /// A parsed connect point couldn't be resolved.
744
    #[error("Unable to resolve connect point")]
745
    CannotResolveConnectPoint(#[from] tor_rpc_connect::ResolveError),
746
    /// IO error while connecting to Arti.
747
    #[error("Unable to make a connection")]
748
    CannotConnect(#[from] tor_rpc_connect::ConnectError),
749
    /// The connect point told us to connect via a type of stream we don't know how to support.
750
    #[error("Connect point stream type was unsupported")]
751
    StreamTypeUnsupported,
752
    /// Opened a connection, but didn't get a banner message.
753
    ///
754
    /// (This isn't a `BadMessage`, since it is likelier to represent something that isn't
755
    /// pretending to be Arti at all than it is to be a malfunctioning Arti.)
756
    #[error("Did not receive expected banner message upon connecting")]
757
    InvalidBanner,
758
    /// All attempted connect points were declined, and none were aborted.
759
    #[error("All connect points were declined (or there were none)")]
760
    AllAttemptsDeclined,
761
    /// A connect file or directory was given as a relative path.
762
    /// (Only absolute paths are supported).
763
    #[error("Connect file was given as a relative path.")]
764
    RelativeConnectFile,
765
    /// One of our authentication messages received an error.
766
    #[error("Received an error while trying to authenticate: {0}")]
767
    AuthenticationFailed(ErrorResponse),
768
    /// The connect point uses an RPC authentication type we don't support.
769
    #[error("Authentication type is not supported")]
770
    AuthenticationNotSupported,
771
    /// We couldn't decode one of the responses we got.
772
    #[error("Message not in expected format")]
773
    BadMessage(#[source] Arc<serde_json::Error>),
774
    /// A protocol error occurred during negotiations.
775
    #[error("Error while negotiating with Arti")]
776
    ProtoError(#[from] ProtoError),
777
    /// The server thinks it is listening on an address where we don't expect to find it.
778
    /// This can be misconfiguration or an attempted MITM attack.
779
    #[error("We connected to the server at {ours}, but it thinks it's listening at {theirs}")]
780
    ServerAddressMismatch {
781
        /// The address we think the server has
782
        ours: String,
783
        /// The address that the server says it has.
784
        theirs: String,
785
    },
786
    /// The server tried to prove knowledge of a cookie file, but its proof was incorrect.
787
    #[error("Server's cookie MAC was not as expected.")]
788
    CookieMismatch,
789
    /// We were unable to access the configured cookie file.
790
    #[error("Unable to load secret cookie value")]
791
    LoadCookie(#[from] CookieAccessError),
792
    /// We want superuser permission, and this connect point does not grant it.
793
    #[error("Connect point does not provide superuser permission.")]
794
    NoSuperuserPermission,
795
}
796

            
797
impl HasClientErrorAction for ConnectError {
798
    fn client_action(&self) -> tor_rpc_connect::ClientErrorAction {
799
        use ConnectError as E;
800
        use tor_rpc_connect::ClientErrorAction as A;
801
        match self {
802
            E::BadEnvironment => A::Abort,
803
            E::CannotParse(e) => e.client_action(),
804
            E::CannotResolvePath(_) => A::Abort,
805
            E::CannotResolveConnectPoint(e) => e.client_action(),
806
            E::CannotConnect(e) => e.client_action(),
807
            E::StreamTypeUnsupported => A::Decline,
808
            E::InvalidBanner => A::Decline,
809
            E::RelativeConnectFile => A::Abort,
810
            E::AuthenticationFailed(_) => A::Decline,
811
            // TODO RPC: Is this correct?  This error can also occur when
812
            // we are talking to something other than an RPC server.
813
            E::BadMessage(_) => A::Abort,
814
            E::ProtoError(e) => e.client_action(),
815
            E::AllAttemptsDeclined => A::Abort,
816
            E::AuthenticationNotSupported => A::Decline,
817
            E::ServerAddressMismatch { .. } => A::Abort,
818
            E::CookieMismatch => A::Abort,
819
            E::LoadCookie(e) => e.client_action(),
820
            E::NoSuperuserPermission => A::Decline,
821
        }
822
    }
823
}
824

            
825
impl HasClientErrorAction for ProtoError {
826
    fn client_action(&self) -> tor_rpc_connect::ClientErrorAction {
827
        use ProtoError as E;
828
        use tor_rpc_connect::ClientErrorAction as A;
829
        match self {
830
            E::Shutdown(_) => A::Decline,
831
            E::InternalRequestFailed(_) => A::Decline,
832
            // These are always internal errors if they occur
833
            // while negotiating a connection to RPC,
834
            // which is the context we care about for `HasClientErrorAction`.
835
            E::InvalidRequest(_)
836
            | E::RequestIdInUse
837
            | E::RequestCompleted
838
            | E::DuplicateWait
839
            | E::RequestNotWaitable
840
            | E::CouldNotEncode(_) => A::Abort,
841
        }
842
    }
843
}
844

            
845
/// In response to a request that we generated internally,
846
/// Arti gave a reply that we did not understand.
847
///
848
/// This could be due to a bug in this library, a bug in Arti,
849
/// or a compatibility issue between the two.
850
#[derive(Clone, Debug, thiserror::Error)]
851
#[error("In response to our request {request:?}, Arti gave the unexpected reply {reply:?}")]
852
pub struct UnexpectedReply {
853
    /// The request we sent.
854
    request: String,
855
    /// The response we got.
856
    reply: String,
857
    /// What was wrong with the response.
858
    #[source]
859
    problem: UnexpectedReplyProblem,
860
}
861

            
862
/// Underlying reason for an UnexpectedReply
863
#[derive(Clone, Debug, thiserror::Error)]
864
enum UnexpectedReplyProblem {
865
    /// There was a json failure while trying to decode the response:
866
    /// the result type was not what we expected.
867
    #[error("Cannot decode as correct JSON type")]
868
    CannotDecode(Arc<serde_json::Error>),
869
    /// Arti replied with an RPC error in a context no error should have been possible.
870
    #[error("Unexpected error")]
871
    ErrorNotExpected,
872
}
873

            
874
/// Arguments to a request that takes no parameters.
875
#[derive(serde::Serialize, Debug)]
876
struct NoParams {}
877

            
878
/// A reply with no data.
879
#[derive(serde::Deserialize, Debug)]
880
struct EmptyReply {}
881

            
882
#[cfg(test)]
883
mod test {
884
    // @@ begin test lint list maintained by maint/add_warning @@
885
    #![allow(clippy::bool_assert_comparison)]
886
    #![allow(clippy::clone_on_copy)]
887
    #![allow(clippy::dbg_macro)]
888
    #![allow(clippy::mixed_attributes_style)]
889
    #![allow(clippy::print_stderr)]
890
    #![allow(clippy::print_stdout)]
891
    #![allow(clippy::single_char_pattern)]
892
    #![allow(clippy::unwrap_used)]
893
    #![allow(clippy::unchecked_time_subtraction)]
894
    #![allow(clippy::useless_vec)]
895
    #![allow(clippy::needless_pass_by_value)]
896
    #![allow(clippy::string_slice)] // See arti#2571
897
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
898

            
899
    use std::{sync::atomic::AtomicUsize, thread, time::Duration};
900

            
901
    use io::{BufRead as _, BufReader, Write as _};
902
    use rand::{RngExt as _, SeedableRng as _, seq::SliceRandom as _};
903
    use tor_basic_utils::{RngExt as _, test_rng::testing_rng};
904

            
905
    use crate::{
906
        ll_conn::BlockingConnection,
907
        msgs::request::{JsonMap, Request, ValidatedRequest},
908
    };
909

            
910
    use super::*;
911

            
912
    /// helper: Return a dummy RpcConn, along with a socketpair for it to talk to.
913
    fn dummy_connected() -> (RpcConn, crate::testing::SocketpairStream) {
914
        let (s1, s2) = crate::testing::construct_socketpair().unwrap();
915
        let conn = RpcConn::new(BlockingConnection::new(s1).unwrap());
916

            
917
        (conn, s2)
918
    }
919

            
920
    fn write_val(w: &mut impl io::Write, v: &serde_json::Value) {
921
        let mut enc = serde_json::to_string(v).unwrap();
922
        enc.push('\n');
923
        w.write_all(enc.as_bytes()).unwrap();
924
    }
925

            
926
    #[test]
927
    fn simple() {
928
        let (conn, sock) = dummy_connected();
929

            
930
        let user_thread = thread::spawn(move || {
931
            let response1 = conn
932
                .execute_internal_ok::<JsonMap>(
933
                    r#"{"obj":"fred","method":"arti:x-frob","params":{}}"#,
934
                )
935
                .unwrap();
936
            (response1, conn)
937
        });
938

            
939
        let fake_arti_thread = thread::spawn(move || {
940
            let mut sock = BufReader::new(sock);
941
            let mut s = String::new();
942
            let _len = sock.read_line(&mut s).unwrap();
943
            let request = ValidatedRequest::from_string_strict(s.as_ref()).unwrap();
944
            let response = serde_json::json!({
945
                "id": request.id().clone(),
946
                "result": { "xyz" : 3 }
947
            });
948
            write_val(sock.get_mut(), &response);
949
            sock // prevent close
950
        });
951

            
952
        let _sock = fake_arti_thread.join().unwrap();
953
        let (map, _conn) = user_thread.join().unwrap();
954
        assert_eq!(map.get("xyz"), Some(&serde_json::Value::Number(3.into())));
955
    }
956

            
957
    #[test]
958
    fn complex() {
959
        use std::sync::atomic::Ordering::SeqCst;
960
        let n_threads = 16;
961
        let n_commands_per_thread = 128;
962
        let n_commands_total = n_threads * n_commands_per_thread;
963
        let n_completed = Arc::new(AtomicUsize::new(0));
964

            
965
        let (conn, sock) = dummy_connected();
966
        let conn = Arc::new(conn);
967
        let mut user_threads = Vec::new();
968
        let mut rng = testing_rng();
969

            
970
        // -------
971
        // User threads: Make a bunch of requests.
972
        for th_idx in 0..n_threads {
973
            let conn = Arc::clone(&conn);
974
            let n_completed = Arc::clone(&n_completed);
975
            let mut rng = rand_chacha::ChaCha12Rng::from_seed(rng.random());
976
            let th = thread::spawn(move || {
977
                for cmd_idx in 0..n_commands_per_thread {
978
                    // We are spawning a bunch of worker threads,
979
                    // each of which will run a number of
980
                    // commands in sequence.  Each command will be a request that gets optional
981
                    // updates, and an error or a success.
982
                    // We will double-check that each request gets the response it asked for.
983
                    let s = format!("{}:{}", th_idx, cmd_idx);
984
                    let want_updates: bool = rng.random();
985
                    let want_failure: bool = rng.random();
986
                    let req = serde_json::json!({
987
                        "obj":"fred",
988
                        "method":"arti:x-echo",
989
                        "meta": {
990
                            "updates": want_updates,
991
                        },
992
                        "params": {
993
                            "val": &s,
994
                            "fail": want_failure,
995
                        },
996
                    });
997
                    let req = serde_json::to_string(&req).unwrap();
998

            
999
                    // Wait for a final response, processing updates if we asked for them.
                    let mut n_updates = 0;
                    let outcome = conn
                        .execute_with_updates(&req, |_update| {
                            n_updates += 1;
                        })
                        .unwrap();
                    assert_eq!(n_updates > 0, want_updates);
                    // See if we liked the final response.
                    if want_failure {
                        let e = outcome.unwrap_err().decode();
                        assert_eq!(e.message(), "You asked me to fail");
                        assert_eq!(i32::from(e.code()), 33);
                        assert_eq!(
                            e.kinds_iter().collect::<Vec<_>>(),
                            vec!["Example".to_string()]
                        );
                    } else {
                        let success = outcome.unwrap();
                        let map = success.decode::<JsonMap>().unwrap();
                        assert_eq!(map.get("echo"), Some(&serde_json::Value::String(s)));
                    }
                    n_completed.fetch_add(1, SeqCst);
                    if rng.random::<f32>() < 0.02 {
                        thread::sleep(Duration::from_millis(3));
                    }
                }
            });
            user_threads.push(th);
        }
        #[derive(serde::Deserialize, Debug)]
        struct Echo {
            val: String,
            fail: bool,
        }
        // -----
        // Worker thread: handles user requests.
        let worker_rng = rand_chacha::ChaCha12Rng::from_seed(rng.random());
        let worker_thread = thread::spawn(move || {
            let mut rng = worker_rng;
            let mut sock = BufReader::new(sock);
            let mut pending: Vec<Request<Echo>> = Vec::new();
            let mut n_received = 0;
            // How many requests do we buffer before we shuffle them and answer them out-of-order?
            let scramble_factor = 7;
            // After receiving how many requests do we stop shuffling requests?
            //
            // (Our shuffling algorithm can deadlock us otherwise.)
            let scramble_threshold =
                n_commands_total - (n_commands_per_thread + 1) * scramble_factor;
            'outer: loop {
                let flush_pending_at = if n_received >= scramble_threshold {
                    1
                } else {
                    scramble_factor
                };
                // Queue a handful of requests in "pending"
                while pending.len() < flush_pending_at {
                    let mut buf = String::new();
                    if sock.read_line(&mut buf).unwrap() == 0 {
                        break 'outer;
                    }
                    n_received += 1;
                    let req: Request<Echo> = serde_json::from_str(&buf).unwrap();
                    pending.push(req);
                }
                // Handle the requests in "pending" in random order.
                let mut handling = std::mem::take(&mut pending);
                handling.shuffle(&mut rng);
                for req in handling {
                    if req.meta.unwrap_or_default().updates {
                        let n_updates = rng.gen_range_checked(1..4).unwrap();
                        for _ in 0..n_updates {
                            let up = serde_json::json!({
                                "id": req.id.clone(),
                                "update": {
                                    "hello": req.params.val.clone(),
                                }
                            });
                            write_val(sock.get_mut(), &up);
                        }
                    }
                    let response = if req.params.fail {
                        serde_json::json!({
                            "id": req.id.clone(),
                            "error": {
                                "message": "You asked me to fail",
                                "code": 33,
                                "kinds": ["Example"],
                                "data": req.params.val,
                            },
                        })
                    } else {
                        serde_json::json!({
                            "id": req.id.clone(),
                            "result": {
                                "echo": req.params.val
                            }
                        })
                    };
                    write_val(sock.get_mut(), &response);
                }
            }
        });
        drop(conn);
        for t in user_threads {
            t.join().unwrap();
        }
        worker_thread.join().unwrap();
        assert_eq!(n_completed.load(SeqCst), n_commands_total);
    }
    #[test]
    fn arti_socket_closed() {
        // Here we send a bunch of requests and then close the socket without answering them.
        //
        // Every request should get a ProtoError::Shutdown.
        let n_threads = 16;
        let (conn, sock) = dummy_connected();
        let conn = Arc::new(conn);
        let mut user_threads = Vec::new();
        for _ in 0..n_threads {
            let conn = Arc::clone(&conn);
            let th = thread::spawn(move || {
                // We are spawning a bunch of worker threads, each of which will run a number of
                // We will double-check that each request gets the response it asked for.
                let req = serde_json::json!({
                    "obj":"fred",
                    "method":"arti:x-echo",
                    "params":{}
                });
                let req = serde_json::to_string(&req).unwrap();
                let outcome = conn.execute(&req);
                if !matches!(
                    &outcome,
                    Err(ProtoError::Shutdown(ShutdownError::Write(_)))
                        | Err(ProtoError::Shutdown(ShutdownError::Read(_))),
                ) {
                    dbg!(&outcome);
                }
                assert!(matches!(
                    outcome,
                    Err(ProtoError::Shutdown(ShutdownError::Write(_)))
                        | Err(ProtoError::Shutdown(ShutdownError::Read(_)))
                        | Err(ProtoError::Shutdown(ShutdownError::ConnectionClosed))
                ));
            });
            user_threads.push(th);
        }
        drop(sock);
        for t in user_threads {
            t.join().unwrap();
        }
    }
    /// Send a bunch of requests and then send back a single reply.
    ///
    /// That reply should cause every request to get closed.
    fn proto_err_with_msg<F>(msg: &str, outcome_ok: F)
    where
        F: Fn(ProtoError) -> bool,
    {
        let n_threads = 16;
        let (conn, mut sock) = dummy_connected();
        let conn = Arc::new(conn);
        let mut user_threads = Vec::new();
        for _ in 0..n_threads {
            let conn = Arc::clone(&conn);
            let th = thread::spawn(move || {
                // We are spawning a bunch of worker threads, each of which will run a number of
                // We will double-check that each request gets the response it asked for.
                let req = serde_json::json!({
                    "obj":"fred",
                    "method":"arti:x-echo",
                    "params":{}
                });
                let req = serde_json::to_string(&req).unwrap();
                conn.execute(&req)
            });
            user_threads.push(th);
        }
        sock.write_all(msg.as_bytes()).unwrap();
        for t in user_threads {
            let outcome = t.join().unwrap();
            assert!(outcome_ok(outcome.unwrap_err()));
        }
    }
    #[test]
    fn syntax_error() {
        proto_err_with_msg("this is not json\n", |outcome| {
            matches!(
                outcome,
                ProtoError::Shutdown(ShutdownError::ProtocolViolated(_))
            )
        });
    }
    #[test]
    fn fatal_error() {
        let j = serde_json::json!({
            "error": {
                "message":
                "This test is doomed",
                "code": 413,
                "kinds": ["Example"],
                "data": {},
            },
        });
        let mut s = serde_json::to_string(&j).unwrap();
        s.push('\n');
        proto_err_with_msg(&s, |outcome| {
            matches!(
                outcome,
                ProtoError::Shutdown(ShutdownError::ProtocolViolationReport(_))
            )
        });
    }
}