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

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

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

            
13
use super::ArtiRpcStatus;
14
use super::util::{OptOutPtrExt as _, OutBoxedPtr, ffi_body_raw};
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
        #[unsafe(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 connection is closed; possibly because the peer 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
    /// or shut down by an API call.)
121
    [c"RPC connection has shut down"]
122
    Shutdown = 6,
123

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

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

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

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

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

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

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

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

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

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

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

            
207
/// Convenience trait to help implement `Into<FfiError>`
208
///
209
/// Any error that implements this trait will be convertible into an [`FfiError`].
210
// additional requirements: display doesn't make NULs.
211
pub(crate) trait IntoFfiError: Display + Sized {
212
    /// Return the status
213
    fn status(&self) -> FfiStatus;
214
    /// Return this type as an Error, if it is one.
215
    fn as_error(&self) -> Option<&(dyn StdError + 'static)>;
216
    /// Return a message for this error.
217
    ///
218
    /// By default, uses the Display of this error, and of its sources, to build a string.
219
    /// The format and content of this string is not specified, and is not guaranteed
220
    /// to remain stable.
221
    fn message(&self) -> String {
222
        use tor_error::ErrorReport as _;
223
        match self.as_error() {
224
            Some(e) => {
225
                let msg = e.report().to_string();
226
                // Note: Having to strip the prefix here is somewhat annoying.
227
                msg.strip_prefix("error: ")
228
                    .map(str::to_string)
229
                    .unwrap_or_else(|| msg)
230
            }
231
            None => self.to_string(),
232
        }
233
    }
234
    /// Return the OS error code (if any) underlying this error.
235
    ///
236
    /// On unix-like platforms, this is an `errno`; on Windows, it's a
237
    /// code from `GetLastError.`
238
    fn os_error_code(&self) -> Option<i32> {
239
        let mut err = self.as_error()?;
240

            
241
        // Note that we aren't using tor_basic_utils::ErrorSources here:
242
        // it exists to work around the case where an error is nested inside an IoError.
243
        // But in this code, we are only looking for the outermost IoError, so it isn't
244
        // necessary.
245
        loop {
246
            if let Some(io_error) = err.downcast_ref::<IoError>() {
247
                return io_error.raw_os_error() as Option<i32>;
248
            }
249
            err = err.source()?;
250
        }
251
    }
252
    /// Consume this error and return an [`ErrorResponse`]
253
    fn into_error_response(self) -> Option<ErrorResponse> {
254
        None
255
    }
256
}
257
impl<T: IntoFfiError> From<T> for FfiError {
258
    fn from(value: T) -> Self {
259
        let status = value.status() as u32;
260
        let message = value
261
            .message()
262
            .try_into()
263
            .expect("Error message had a NUL?");
264
        let os_error_code = value.os_error_code();
265
        let error_response = value.into_error_response();
266
        Self {
267
            status,
268
            message,
269
            error_response,
270
            os_error_code,
271
        }
272
    }
273
}
274
impl From<void::Void> for FfiError {
275
    fn from(value: void::Void) -> Self {
276
        void::unreachable(value)
277
    }
278
}
279

            
280
/// Tried to call a ffi function with a not-permitted argument.
281
#[derive(Clone, Debug, thiserror::Error)]
282
pub(super) enum InvalidInput {
283
    /// Tried to convert a NULL pointer to an FFI object.
284
    #[error("Provided argument was NULL.")]
285
    NullPointer,
286

            
287
    /// Tried to convert a non-UTF string.
288
    #[error("Provided string was not UTF-8")]
289
    BadUtf8,
290

            
291
    /// Tried to use an invalid port.
292
    #[error("Port was not in range 1..65535")]
293
    BadPort,
294

            
295
    /// Tried to use an invalid constant
296
    #[error("Provided constant was not recognized")]
297
    InvalidConstValue,
298
}
299

            
300
impl From<void::Void> for InvalidInput {
301
    fn from(value: void::Void) -> Self {
302
        void::unreachable(value)
303
    }
304
}
305

            
306
impl IntoFfiError for InvalidInput {
307
    fn status(&self) -> FfiStatus {
308
        FfiStatus::InvalidInput
309
    }
310
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
311
        Some(self)
312
    }
313
}
314

            
315
impl IntoFfiError for crate::ConnectError {
316
    fn status(&self) -> FfiStatus {
317
        use crate::ConnectError as E;
318
        use FfiStatus as F;
319
        match self {
320
            E::CannotConnect(e) => e.status(),
321
            E::AuthenticationFailed(_) => F::BadAuth,
322
            E::InvalidBanner => F::PeerProtocolViolation,
323
            E::BadMessage(_) => F::PeerProtocolViolation,
324
            E::ProtoError(e) => e.status(),
325
            E::BadEnvironment | E::RelativeConnectFile | E::CannotResolvePath(_) => {
326
                F::BadConnectPointPath
327
            }
328
            E::CannotParse(_) | E::CannotResolveConnectPoint(_) => F::ConnectPointNotUsable,
329
            E::AllAttemptsDeclined => F::AllConnectAttemptsFailed,
330
            E::AuthenticationNotSupported => F::NotSupported,
331
            E::ServerAddressMismatch { .. } => F::ConnectPointNotUsable,
332
            E::CookieMismatch => F::ConnectPointNotUsable,
333
            E::LoadCookie(_) => F::ConnectPointNotUsable,
334
            E::StreamTypeUnsupported => F::ConnectPointNotUsable,
335
            E::NoSuperuserPermission => F::ConnectPointNotUsable,
336
        }
337
    }
338

            
339
    fn into_error_response(self) -> Option<ErrorResponse> {
340
        use crate::ConnectError as E;
341
        match self {
342
            E::AuthenticationFailed(msg) => Some(msg),
343
            _ => None,
344
        }
345
    }
346
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
347
        Some(self)
348
    }
349
}
350

            
351
impl IntoFfiError for tor_rpc_connect::ConnectError {
352
    fn status(&self) -> FfiStatus {
353
        use FfiStatus as F;
354
        use tor_rpc_connect::ConnectError as E;
355
        match self {
356
            E::Io(_) => F::ConnectIo,
357
            E::ExplicitAbort => F::AllConnectAttemptsFailed,
358
            E::LoadCookie(_)
359
            | E::UnsupportedSocketType
360
            | E::UnsupportedAuthType
361
            | E::AfUnixSocketPathAccess(_) => F::ConnectPointNotUsable,
362
            _ => F::Internal,
363
        }
364
    }
365

            
366
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
367
        Some(self)
368
    }
369
}
370

            
371
impl IntoFfiError for crate::conn::ConnectFailure {
372
    fn status(&self) -> FfiStatus {
373
        self.final_error.status()
374
    }
375

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

            
380
    fn message(&self) -> String {
381
        self.display_verbose().to_string()
382
    }
383
}
384

            
385
impl IntoFfiError for crate::StreamError {
386
    fn status(&self) -> FfiStatus {
387
        use crate::StreamError as E;
388
        use FfiStatus as F;
389
        match self {
390
            E::RpcMethods(e) => e.status(),
391
            E::ProxyInfoRejected(_) => F::RequestFailed,
392
            E::NewStreamRejected(_) => F::RequestFailed,
393
            E::StreamReleaseRejected(_) => F::RequestFailed,
394
            E::NotAuthenticated => F::NotAuthenticated,
395
            E::NoSession => F::NotSupported,
396
            E::Internal(_) => F::Internal,
397
            E::NoProxy => F::RequestFailed,
398
            E::Io(_) => F::ProxyIo,
399
            E::SocksRequest(_) => F::InvalidInput,
400
            E::SocksProtocol(_) => F::PeerProtocolViolation,
401
            E::SocksError(_status) => {
402
                // TODO RPC: We should expose the actual failure type somehow,
403
                // possibly with a different call.  See #1580.
404
                F::ProxyStreamFailed
405
            }
406
        }
407
    }
408

            
409
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
410
        Some(self)
411
    }
412
}
413

            
414
impl IntoFfiError for crate::ProtoError {
415
    fn status(&self) -> FfiStatus {
416
        use crate::ProtoError as E;
417
        use FfiStatus as F;
418
        match self {
419
            E::Shutdown(_) => F::Shutdown,
420
            E::InvalidRequest(_) => F::InvalidInput,
421
            E::RequestIdInUse => F::InvalidInput,
422
            E::RequestCompleted => F::RequestCompleted,
423
            E::DuplicateWait => F::Internal,
424
            E::RequestNotWaitable => F::Internal,
425
            E::CouldNotEncode(_) => F::Internal,
426
            E::InternalRequestFailed(_) => F::PeerProtocolViolation,
427
        }
428
    }
429
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
430
        Some(self)
431
    }
432
}
433

            
434
impl IntoFfiError for crate::BuilderError {
435
    fn status(&self) -> FfiStatus {
436
        use crate::BuilderError as E;
437
        use FfiStatus as F;
438
        match self {
439
            E::InvalidConnectString => F::InvalidInput,
440
        }
441
    }
442
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
443
        Some(self)
444
    }
445
}
446

            
447
impl IntoFfiError for ErrorResponse {
448
    fn status(&self) -> FfiStatus {
449
        FfiStatus::RequestFailed
450
    }
451
    fn into_error_response(self) -> Option<ErrorResponse> {
452
        Some(self)
453
    }
454
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
455
        None
456
    }
457
}
458

            
459
/// An error returned by the Arti RPC code, exposed as an object.
460
///
461
/// When a function returns an [`ArtiRpcStatus`] other than [`ARTI_RPC_STATUS_SUCCESS`],
462
/// it will also expose a newly allocated value of this type
463
/// via its `error_out` parameter.
464
pub type ArtiRpcError = FfiError;
465

            
466
/// Return the status code associated with a given error.
467
///
468
/// If `err` is NULL, return [`ARTI_RPC_STATUS_INVALID_INPUT`].
469
#[allow(clippy::missing_safety_doc)]
470
#[unsafe(no_mangle)]
471
pub unsafe extern "C" fn arti_rpc_err_status(err: *const ArtiRpcError) -> ArtiRpcStatus {
472
    ffi_body_raw!(
473
        {
474
            let err: Option<&ArtiRpcError> [in_ptr_opt];
475
        } in {
476
            err.map(|e| e.status)
477
               .unwrap_or(ARTI_RPC_STATUS_INVALID_INPUT)
478
            // Safety: Return value is ArtiRpcStatus; trivially safe.
479
        }
480
    )
481
}
482

            
483
/// Return the OS error code underlying `err`, if any.
484
///
485
/// This is typically an `errno` on unix-like systems , or the result of `GetLastError()`
486
/// on Windows.  It is only present when `err` was caused by the failure of some
487
/// OS library call, like a `connect()` or `read()`.
488
///
489
/// Returns 0 if `err` is NULL, or if `err` was not caused by the failure of an
490
/// OS library call.
491
#[allow(clippy::missing_safety_doc)]
492
#[unsafe(no_mangle)]
493
pub unsafe extern "C" fn arti_rpc_err_os_error_code(err: *const ArtiRpcError) -> c_int {
494
    ffi_body_raw!(
495
        {
496
            let err: Option<&ArtiRpcError> [in_ptr_opt];
497
        } in {
498
            err.and_then(|e| e.os_error_code)
499
               .unwrap_or(0)
500
             // Safety: Return value is c_int; trivially safe.
501
        }
502
    )
503
}
504

            
505
/// Return a human-readable error message associated with a given error.
506
///
507
/// The format of these messages may change arbitrarily between versions of this library;
508
/// it is a mistake to depend on the actual contents of this message.
509
///
510
/// Return NULL if the input `err` is NULL.
511
///
512
/// # Correctness requirements
513
///
514
/// The resulting string pointer is valid only for as long as the input `err` is not freed.
515
#[allow(clippy::missing_safety_doc)]
516
#[unsafe(no_mangle)]
517
pub unsafe extern "C" fn arti_rpc_err_message(err: *const ArtiRpcError) -> *const c_char {
518
    ffi_body_raw!(
519
        {
520
            let err: Option<&ArtiRpcError> [in_ptr_opt];
521
        } in {
522
            err.map(|e| e.message.as_ptr())
523
               .unwrap_or(std::ptr::null())
524
            // Safety: returned pointer is null, or semantically borrowed from `err`.
525
            // It is only null if `err` was null.
526
            // The caller is not allowed to modify it.
527
        }
528
    )
529
}
530

            
531
/// Return a Json-formatted error response associated with a given error.
532
///
533
/// These messages are full responses, including the `error` field,
534
/// and the `id` field (if present).
535
///
536
/// Return NULL if the specified error does not represent an RPC error response.
537
///
538
/// Return NULL if the input `err` is NULL.
539
///
540
/// # Correctness requirements
541
///
542
/// The resulting string pointer is valid only for as long as the input `err` is not freed.
543
#[allow(clippy::missing_safety_doc)]
544
#[unsafe(no_mangle)]
545
pub unsafe extern "C" fn arti_rpc_err_response(err: *const ArtiRpcError) -> *const c_char {
546
    ffi_body_raw!(
547
        {
548
            let err: Option<&ArtiRpcError> [in_ptr_opt];
549
        } in {
550
            err.and_then(ArtiRpcError::error_response_as_ptr)
551
               .unwrap_or(std::ptr::null())
552
            // Safety: returned pointer is null, or semantically borrowed from `err`.
553
            // It is only null if `err` was null, or if `err` contained no response field.
554
            // The caller is not allowed to modify it.
555
        }
556
    )
557
}
558

            
559
/// Make and return copy of a provided error.
560
///
561
/// Return NULL if the input is NULL.
562
///
563
/// # Ownership
564
///
565
/// The caller is responsible for making sure that the returned object
566
/// is eventually freed with `arti_rpc_err_free()`.
567
#[allow(clippy::missing_safety_doc)]
568
#[unsafe(no_mangle)]
569
pub unsafe extern "C" fn arti_rpc_err_clone(err: *const ArtiRpcError) -> *mut ArtiRpcError {
570
    ffi_body_raw!(
571
        {
572
            let err: Option<&ArtiRpcError> [in_ptr_opt];
573
        } in {
574
            err.map(|e| Box::into_raw(Box::new(e.clone())))
575
               .unwrap_or(std::ptr::null_mut())
576
            // Safety: returned pointer is null, or newly allocated via Box::new().
577
            // It is only null if the input was null.
578
        }
579
    )
580
}
581

            
582
/// Release storage held by a provided error.
583
#[allow(clippy::missing_safety_doc)]
584
#[unsafe(no_mangle)]
585
pub unsafe extern "C" fn arti_rpc_err_free(err: *mut ArtiRpcError) {
586
    ffi_body_raw!(
587
        {
588
            let err: Option<Box<ArtiRpcError>> [in_ptr_consume_opt];
589
        } in {
590
            drop(err);
591
            // Safety: Return value is (); trivially safe.
592
            ()
593
        }
594
    );
595
}
596

            
597
/// Run `body` and catch panics.  If one occurs, return the result of `on_err` instead.
598
///
599
/// We wrap the body of every C ffi function with this function
600
/// (or with `handle_errors`, which uses this function),
601
/// even if we do not think that the body can actually panic.
602
pub(super) fn abort_on_panic<F, T>(body: F) -> T
603
where
604
    F: FnOnce() -> T + UnwindSafe,
605
{
606
    #[allow(clippy::print_stderr)]
607
    match catch_unwind(body) {
608
        Ok(x) => x,
609
        Err(_panic_info) => {
610
            eprintln!("Internal panic in arti-rpc library: aborting!");
611
            std::process::abort();
612
        }
613
    }
614
}
615

            
616
/// Call `body`, converting any errors or panics that occur into an FfiError,
617
/// and storing that error in `error_out`.
618
pub(super) fn handle_errors<F>(error_out: Option<OutBoxedPtr<FfiError>>, body: F) -> ArtiRpcStatus
619
where
620
    F: FnOnce() -> Result<(), FfiError> + UnwindSafe,
621
{
622
    match abort_on_panic(body) {
623
        Ok(()) => ARTI_RPC_STATUS_SUCCESS,
624
        Err(e) => {
625
            // "body" returned an error.
626
            let status = e.status;
627
            error_out.write_boxed_value_if_ptr_set(e);
628
            status
629
        }
630
    }
631
}