1
//! Error handling logic for our ffi code.
2

            
3
use paste::paste;
4
use std::error::Error as StdError;
5
use std::ffi::{c_char, c_int, CStr};
6
use std::fmt::Display;
7
use std::io::Error as IoError;
8
use std::panic::{catch_unwind, UnwindSafe};
9

            
10
use crate::conn::ErrorResponse;
11
use crate::util::Utf8CString;
12

            
13
use super::util::{ffi_body_raw, OptOutPtrExt as _, OutPtr};
14
use super::ArtiRpcStatus;
15

            
16
/// Helper:
17
/// Given a restricted enum defining FfiStatus, also define a series of constants for its variants,
18
/// and a string conversion function.
19
//
20
// NOTE: I tried to use derive_deftly here, but ran into trouble when defining the constants.
21
// I wanted to have them be "pub const ARTI_FOO = FfiStatus::$vname",
22
// but that doesn't work with cbindgen, which won't expose a constant unless it is a public type
23
// it can recognize.
24
// There is no way to use derive_deftly to look at the explicit discriminant of an enum.
25
macro_rules! define_ffi_status {
26
    {
27
        $(#[$tm:meta])*
28
        pub(crate) enum FfiStatus {
29
            $(
30
                $(#[$m:meta])*
31
                [$s:expr]
32
                $id:ident = $e:expr,
33
            )+
34
        }
35

            
36
    } => {paste!{
37
        $(#[$tm])*
38
        pub(crate) enum FfiStatus {
39
            $(
40
                $(#[$m])*
41
                $id = $e,
42
            )+
43
        }
44

            
45
        $(
46
            $(#[$m])*
47
            pub const [<ARTI_RPC_STATUS_ $id:snake:upper >] : ArtiRpcStatus = $e;
48
        )+
49

            
50
        /// Return a string representing the meaning of a given `ArtiRpcStatus`.
51
        ///
52
        /// The result will always be non-NULL, even if the status is unrecognized.
53
        #[no_mangle]
54
        pub extern "C" fn arti_rpc_status_to_str(status: ArtiRpcStatus) -> *const c_char {
55
            match status {
56
                $(
57
                    [<ARTI_RPC_STATUS_ $id:snake:upper>] => $s,
58
                )+
59
                _ => c"(unrecognized status)",
60
            }.as_ptr()
61
        }
62
    }}
63
}
64

            
65
define_ffi_status! {
66
/// View of FFI status as rust enumeration.
67
///
68
/// Not exposed in the FFI interfaces, except via cast to ArtiStatus.
69
///
70
/// We define this as an enumeration so that we can treat it exhaustively in Rust.
71
#[derive(Copy, Clone, Debug)]
72
#[repr(u32)]
73
pub(crate) enum FfiStatus {
74
    /// The function has returned successfully.
75
    #[allow(dead_code)]
76
    [c"Success"]
77
    Success = 0,
78

            
79
    /// One or more of the inputs to a library function was invalid.
80
    ///
81
    /// (This error was generated by the library, before any request was sent.)
82
    [c"Invalid input"]
83
    InvalidInput = 1,
84

            
85
    /// Tried to use some functionality
86
    /// (for example, an authentication method or connection scheme)
87
    /// that wasn't available on this platform or build.
88
    ///
89
    /// (This error was generated by the library, before any request was sent.)
90
    [c"Not supported"]
91
    NotSupported = 2,
92

            
93
    /// Tried to connect to Arti, but an IO error occurred.
94
    ///
95
    /// This may indicate that Arti wasn't running,
96
    /// or that Arti was built without RPC support,
97
    /// or that Arti wasn't running at the specified location.
98
    ///
99
    /// (This error was generated by the library.)
100
    [c"An IO error occurred while connecting to Arti"]
101
    ConnectIo = 3,
102

            
103
    /// We tried to authenticate with Arti, but it rejected our attempt.
104
    ///
105
    /// (This error was sent by the peer.)
106
    [c"Authentication rejected"]
107
    BadAuth = 4,
108

            
109
    /// Our peer has, in some way, violated the Arti-RPC protocol.
110
    ///
111
    /// (This error was generated by the library,
112
    /// based on a response from Arti that appeared to be invalid.)
113
    [c"Peer violated the RPC protocol"]
114
    PeerProtocolViolation = 5,
115

            
116
    /// The peer has closed our connection; possibly because it is shutting down.
117
    ///
118
    /// (This error was generated by the library,
119
    /// based on the connection being closed or reset from the peer.)
120
    [c"Peer has shut down"]
121
    Shutdown = 6,
122

            
123
    /// An internal error occurred in the arti rpc client.
124
    ///
125
    /// (This error was generated by the library.
126
    /// If you see it, there is probably a bug in the library.)
127
    [c"Internal error; possible bug?"]
128
    Internal = 7,
129

            
130
    /// The peer reports that one of our requests has failed.
131
    ///
132
    /// (This error was sent by the peer, in response to one of our requests.
133
    /// No further responses to that request will be received or accepted.)
134
    [c"Request has failed"]
135
    RequestFailed = 8,
136

            
137
    /// Tried to check the status of a request and found that it was no longer running.
138
    [c"Request has already completed (or failed)"]
139
    RequestCompleted = 9,
140

            
141
    /// An IO error occurred while trying to negotiate a data stream
142
    /// using Arti as a proxy.
143
    [c"IO error while connecting to Arti as a Proxy"]
144
    ProxyIo = 10,
145

            
146
    /// An attempt to negotiate a data stream through Arti failed,
147
    /// with an error from the proxy protocol.
148
    //
149
    // TODO RPC: expose the actual error type; see #1580.
150
    [c"Data stream failed"]
151
    ProxyStreamFailed = 11,
152

            
153
    /// Some operation failed because it was attempted on an unauthenticated channel.
154
    ///
155
    /// (At present (Sep 2024) there is no way to get an unauthenticated channel from this library,
156
    /// but that may change in the future.)
157
    [c"Not authenticated"]
158
    NotAuthenticated = 12,
159

            
160
    /// All of our attempts to connect to Arti failed,
161
    /// or we reached an explicit instruction to "abort" our connection attempts.
162
    [c"All attempts to connect to Arti RPC failed"]
163
    AllConnectAttemptsFailed = 13,
164

            
165
    /// We tried to connect to Arti at a given connect point,
166
    /// but it could not be used:
167
    /// either because we don't know how,
168
    /// or because we were not able to access some necessary file or directory.
169
    [c"Connect point was not usable"]
170
    ConnectPointNotUsable = 14,
171

            
172
    /// We were unable to parse or resolve an entry
173
    /// in our connect point search path.
174
    [c"Invalid connect point search path"]
175
    BadConnectPointPath = 15,
176
}
177
}
178

            
179
/// An error as returned by the Arti FFI code.
180
#[derive(Debug, Clone)]
181
pub struct FfiError {
182
    /// The status of this error messages
183
    pub(super) status: ArtiRpcStatus,
184
    /// A human-readable message describing this error
185
    message: Utf8CString,
186
    /// If present, a Json-formatted message from our peer that we are representing with this error.
187
    error_response: Option<ErrorResponse>,
188
    /// If present, the OS error code that caused this error.
189
    //
190
    // (Actually, this should be RawOsError, but that type isn't stable.)
191
    os_error_code: Option<i32>,
192
}
193

            
194
impl FfiError {
195
    /// Helper: If this error stems from a response from our RPC peer,
196
    /// return that response.
197
    fn error_response_as_ptr(&self) -> Option<*const c_char> {
198
        self.error_response.as_ref().map(|response| {
199
            let cstr: &CStr = response.as_ref();
200
            cstr.as_ptr()
201
        })
202
    }
203
}
204

            
205
/// Convenience trait to help implement `Into<FfiError>`
206
///
207
/// Any error that implements this trait will be convertible into an [`FfiError`].
208
// additional requirements: display doesn't make NULs.
209
pub(crate) trait IntoFfiError: Display + Sized {
210
    /// Return the status
211
    fn status(&self) -> FfiStatus;
212
    /// Return this type as an Error, if it is one.
213
    fn as_error(&self) -> Option<&(dyn StdError + 'static)>;
214
    /// Return a message for this error.
215
    ///
216
    /// By default, returns the Display of this error.
217
    fn message(&self) -> String {
218
        self.to_string()
219
    }
220
    /// Return the OS error code (if any) underlying this error.
221
    ///
222
    /// On unix-like platforms, this is an `errno`; on Windows, it's a
223
    /// code from `GetLastError.`
224
    fn os_error_code(&self) -> Option<i32> {
225
        let mut err = self.as_error()?;
226

            
227
        loop {
228
            if let Some(io_error) = err.downcast_ref::<IoError>() {
229
                return io_error.raw_os_error() as Option<i32>;
230
            }
231
            err = err.source()?;
232
        }
233
    }
234
    /// Consume this error and return an [`ErrorResponse`]
235
    fn into_error_response(self) -> Option<ErrorResponse> {
236
        None
237
    }
238
}
239
impl<T: IntoFfiError> From<T> for FfiError {
240
    fn from(value: T) -> Self {
241
        let status = value.status() as u32;
242
        let message = value
243
            .message()
244
            .try_into()
245
            .expect("Error message had a NUL?");
246
        let os_error_code = value.os_error_code();
247
        let error_response = value.into_error_response();
248
        Self {
249
            status,
250
            message,
251
            error_response,
252
            os_error_code,
253
        }
254
    }
255
}
256
impl From<void::Void> for FfiError {
257
    fn from(value: void::Void) -> Self {
258
        void::unreachable(value)
259
    }
260
}
261

            
262
/// Tried to call a ffi function with a not-permitted argument.
263
#[derive(Clone, Debug, thiserror::Error)]
264
pub(super) enum InvalidInput {
265
    /// Tried to convert a NULL pointer to an FFI object.
266
    #[error("Provided argument was NULL.")]
267
    NullPointer,
268

            
269
    /// Tried to convert a non-UTF string.
270
    #[error("Provided string was not UTF-8")]
271
    BadUtf8,
272

            
273
    /// Tried to use an invalid port.
274
    #[error("Port was not in range 1..65535")]
275
    BadPort,
276

            
277
    /// Tried to use an invalid constant
278
    #[error("Provided constant was not recognized")]
279
    InvalidConstValue,
280
}
281

            
282
impl From<void::Void> for InvalidInput {
283
    fn from(value: void::Void) -> Self {
284
        void::unreachable(value)
285
    }
286
}
287

            
288
impl IntoFfiError for InvalidInput {
289
    fn status(&self) -> FfiStatus {
290
        FfiStatus::InvalidInput
291
    }
292
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
293
        Some(self)
294
    }
295
}
296

            
297
impl IntoFfiError for crate::ConnectError {
298
    fn status(&self) -> FfiStatus {
299
        use crate::ConnectError as E;
300
        use FfiStatus as F;
301
        match self {
302
            E::CannotConnect(e) => e.status(),
303
            E::AuthenticationRejected(_) => F::BadAuth,
304
            E::InvalidBanner => F::PeerProtocolViolation,
305
            E::BadMessage(_) => F::PeerProtocolViolation,
306
            E::ProtoError(e) => e.status(),
307
            E::BadEnvironment | E::RelativeConnectFile | E::CannotResolvePath(_) => {
308
                F::BadConnectPointPath
309
            }
310
            E::CannotParse(_) | E::CannotResolveConnectPoint(_) => F::ConnectPointNotUsable,
311
            E::AllAttemptsDeclined => F::AllConnectAttemptsFailed,
312
            E::AuthenticationNotSupported => F::NotSupported,
313
            E::ServerAddressMismatch { .. } => F::ConnectPointNotUsable,
314
            E::CookieMismatch => F::ConnectPointNotUsable,
315
            E::LoadCookie(_) => F::ConnectPointNotUsable,
316
        }
317
    }
318

            
319
    fn into_error_response(self) -> Option<ErrorResponse> {
320
        use crate::ConnectError as E;
321
        match self {
322
            E::AuthenticationRejected(msg) => Some(msg),
323
            _ => None,
324
        }
325
    }
326
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
327
        Some(self)
328
    }
329
}
330

            
331
impl IntoFfiError for tor_rpc_connect::ConnectError {
332
    fn status(&self) -> FfiStatus {
333
        use tor_rpc_connect::ConnectError as E;
334
        use FfiStatus as F;
335
        match self {
336
            E::Io(_) => F::ConnectIo,
337
            E::ExplicitAbort => F::AllConnectAttemptsFailed,
338
            E::LoadCookie(_)
339
            | E::UnsupportedSocketType
340
            | E::UnsupportedAuthType
341
            | E::InvalidUnixAddress
342
            | E::UnixAddressAccess(_) => F::ConnectPointNotUsable,
343
            _ => F::Internal,
344
        }
345
    }
346

            
347
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
348
        Some(self)
349
    }
350
}
351

            
352
impl IntoFfiError for crate::StreamError {
353
    fn status(&self) -> FfiStatus {
354
        use crate::StreamError as E;
355
        use FfiStatus as F;
356
        match self {
357
            E::RpcMethods(e) => e.status(),
358
            E::ProxyInfoRejected(_) => F::RequestFailed,
359
            E::NewStreamRejected(_) => F::RequestFailed,
360
            E::StreamReleaseRejected(_) => F::RequestFailed,
361
            E::NotAuthenticated => F::NotAuthenticated,
362
            E::Internal(_) => F::Internal,
363
            E::NoProxy => F::RequestFailed,
364
            E::Io(_) => F::ProxyIo,
365
            E::SocksRequest(_) => F::InvalidInput,
366
            E::SocksProtocol(_) => F::PeerProtocolViolation,
367
            E::SocksError(_status) => {
368
                // TODO RPC: We should expose the actual failure type somehow,
369
                // possibly with a different call.  See #1580.
370
                F::ProxyStreamFailed
371
            }
372
        }
373
    }
374

            
375
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
376
        Some(self)
377
    }
378
}
379

            
380
impl IntoFfiError for crate::ProtoError {
381
    fn status(&self) -> FfiStatus {
382
        use crate::ProtoError as E;
383
        use FfiStatus as F;
384
        match self {
385
            E::Shutdown(_) => F::Shutdown,
386
            E::InvalidRequest(_) => F::InvalidInput,
387
            E::RequestIdInUse => F::InvalidInput,
388
            E::RequestCompleted => F::RequestCompleted,
389
            E::DuplicateWait => F::Internal,
390
            E::CouldNotEncode(_) => F::Internal,
391
            E::InternalRequestFailed(_) => F::PeerProtocolViolation,
392
        }
393
    }
394
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
395
        Some(self)
396
    }
397
}
398

            
399
impl IntoFfiError for crate::BuilderError {
400
    fn status(&self) -> FfiStatus {
401
        use crate::BuilderError as E;
402
        use FfiStatus as F;
403
        match self {
404
            E::InvalidConnectString => F::InvalidInput,
405
        }
406
    }
407
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
408
        Some(self)
409
    }
410
}
411

            
412
impl IntoFfiError for ErrorResponse {
413
    fn status(&self) -> FfiStatus {
414
        FfiStatus::RequestFailed
415
    }
416
    fn into_error_response(self) -> Option<ErrorResponse> {
417
        Some(self)
418
    }
419
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
420
        None
421
    }
422
}
423

            
424
/// An error returned by the Arti RPC code, exposed as an object.
425
///
426
/// When a function returns an [`ArtiRpcStatus`] other than [`ARTI_RPC_STATUS_SUCCESS`],
427
/// it will also expose a newly allocated value of this type
428
/// via its `error_out` parameter.
429
pub type ArtiRpcError = FfiError;
430

            
431
/// Return the status code associated with a given error.
432
///
433
/// If `err` is NULL, return [`ARTI_RPC_STATUS_INVALID_INPUT`].
434
#[allow(clippy::missing_safety_doc)]
435
#[no_mangle]
436
pub unsafe extern "C" fn arti_rpc_err_status(err: *const ArtiRpcError) -> ArtiRpcStatus {
437
    ffi_body_raw!(
438
        {
439
            let err: Option<&ArtiRpcError> [in_ptr_opt];
440
        } in {
441
            err.map(|e| e.status)
442
               .unwrap_or(ARTI_RPC_STATUS_INVALID_INPUT)
443
            // Safety: Return value is ArtiRpcStatus; trivially safe.
444
        }
445
    )
446
}
447

            
448
/// Return the OS error code underlying `err`, if any.
449
///
450
/// This is typically an `errno` on unix-like systems , or the result of `GetLastError()`
451
/// on Windows.  It is only present when `err` was caused by the failure of some
452
/// OS library call, like a `connect()` or `read()`.
453
///
454
/// Returns 0 if `err` is NULL, or if `err` was not caused by the failure of an
455
/// OS library call.
456
#[allow(clippy::missing_safety_doc)]
457
#[no_mangle]
458
pub unsafe extern "C" fn arti_rpc_err_os_error_code(err: *const ArtiRpcError) -> c_int {
459
    ffi_body_raw!(
460
        {
461
            let err: Option<&ArtiRpcError> [in_ptr_opt];
462
        } in {
463
            err.and_then(|e| e.os_error_code)
464
               .unwrap_or(0)
465
             // Safety: Return value is c_int; trivially safe.
466
        }
467
    )
468
}
469

            
470
/// Return a human-readable error message associated with a given error.
471
///
472
/// The format of these messages may change arbitrarily between versions of this library;
473
/// it is a mistake to depend on the actual contents of this message.
474
///
475
/// Return NULL if the input `err` is NULL.
476
///
477
/// # Correctness requirements
478
///
479
/// The resulting string pointer is valid only for as long as the input `err` is not freed.
480
#[allow(clippy::missing_safety_doc)]
481
#[no_mangle]
482
pub unsafe extern "C" fn arti_rpc_err_message(err: *const ArtiRpcError) -> *const c_char {
483
    ffi_body_raw!(
484
        {
485
            let err: Option<&ArtiRpcError> [in_ptr_opt];
486
        } in {
487
            err.map(|e| e.message.as_ptr())
488
               .unwrap_or(std::ptr::null())
489
            // Safety: returned pointer is null, or semantically borrowed from `err`.
490
            // It is only null if `err` was null.
491
            // The caller is not allowed to modify it.
492
        }
493
    )
494
}
495

            
496
/// Return a Json-formatted error response associated with a given error.
497
///
498
/// These messages are full responses, including the `error` field,
499
/// and the `id` field (if present).
500
///
501
/// Return NULL if the specified error does not represent an RPC error response.
502
///
503
/// Return NULL if the input `err` is NULL.
504
///
505
/// # Correctness requirements
506
///
507
/// The resulting string pointer is valid only for as long as the input `err` is not freed.
508
#[allow(clippy::missing_safety_doc)]
509
#[no_mangle]
510
pub unsafe extern "C" fn arti_rpc_err_response(err: *const ArtiRpcError) -> *const c_char {
511
    ffi_body_raw!(
512
        {
513
            let err: Option<&ArtiRpcError> [in_ptr_opt];
514
        } in {
515
            err.and_then(ArtiRpcError::error_response_as_ptr)
516
               .unwrap_or(std::ptr::null())
517
            // Safety: returned pointer is null, or semantically borrowed from `err`.
518
            // It is only null if `err` was null, or if `err` contained no response field.
519
            // The caller is not allowed to modify it.
520
        }
521
    )
522
}
523

            
524
/// Make and return copy of a provided error.
525
///
526
/// Return NULL if the input is NULL.
527
///
528
/// # Ownership
529
///
530
/// The caller is responsible for making sure that the returned object
531
/// is eventually freed with `arti_rpc_err_free()`.
532
#[allow(clippy::missing_safety_doc)]
533
#[no_mangle]
534
pub unsafe extern "C" fn arti_rpc_err_clone(err: *const ArtiRpcError) -> *mut ArtiRpcError {
535
    ffi_body_raw!(
536
        {
537
            let err: Option<&ArtiRpcError> [in_ptr_opt];
538
        } in {
539
            err.map(|e| Box::into_raw(Box::new(e.clone())))
540
               .unwrap_or(std::ptr::null_mut())
541
            // Safety: returned pointer is null, or newly allocated via Box::new().
542
            // It is only null if the input was null.
543
        }
544
    )
545
}
546

            
547
/// Release storage held by a provided error.
548
#[allow(clippy::missing_safety_doc)]
549
#[no_mangle]
550
pub unsafe extern "C" fn arti_rpc_err_free(err: *mut ArtiRpcError) {
551
    ffi_body_raw!(
552
        {
553
            let err: Option<Box<ArtiRpcError>> [in_ptr_consume_opt];
554
        } in {
555
            drop(err);
556
            // Safety: Return value is (); trivially safe.
557
            ()
558
        }
559
    );
560
}
561

            
562
/// Run `body` and catch panics.  If one occurs, return the result of `on_err` instead.
563
///
564
/// We wrap the body of every C ffi function with this function
565
/// (or with `handle_errors`, which uses this function),
566
/// even if we do not think that the body can actually panic.
567
pub(super) fn abort_on_panic<F, T>(body: F) -> T
568
where
569
    F: FnOnce() -> T + UnwindSafe,
570
{
571
    #[allow(clippy::print_stderr)]
572
    match catch_unwind(body) {
573
        Ok(x) => x,
574
        Err(_panic_info) => {
575
            eprintln!("Internal panic in arti-rpc library: aborting!");
576
            std::process::abort();
577
        }
578
    }
579
}
580

            
581
/// Call `body`, converting any errors or panics that occur into an FfiError,
582
/// and storing that error in `error_out`.
583
pub(super) fn handle_errors<F>(error_out: Option<OutPtr<FfiError>>, body: F) -> ArtiRpcStatus
584
where
585
    F: FnOnce() -> Result<(), FfiError> + UnwindSafe,
586
{
587
    match abort_on_panic(body) {
588
        Ok(()) => ARTI_RPC_STATUS_SUCCESS,
589
        Err(e) => {
590
            // "body" returned an error.
591
            let status = e.status;
592
            error_out.write_boxed_value_if_ptr_set(e);
593
            status
594
        }
595
    }
596
}