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 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, uses the Display of this error, and of its sources, to build a string.
217
    /// The format and content of this string is not specified, and is not guaranteed
218
    /// to remain stable.
219
    fn message(&self) -> String {
220
        use tor_error::ErrorReport as _;
221
        match self.as_error() {
222
            Some(e) => {
223
                let msg = e.report().to_string();
224
                // Note: Having to strip the prefix here is somewhat annoying.
225
                msg.strip_prefix("error: ")
226
                    .map(str::to_string)
227
                    .unwrap_or_else(|| msg)
228
            }
229
            None => self.to_string(),
230
        }
231
    }
232
    /// Return the OS error code (if any) underlying this error.
233
    ///
234
    /// On unix-like platforms, this is an `errno`; on Windows, it's a
235
    /// code from `GetLastError.`
236
    fn os_error_code(&self) -> Option<i32> {
237
        let mut err = self.as_error()?;
238

            
239
        loop {
240
            if let Some(io_error) = err.downcast_ref::<IoError>() {
241
                return io_error.raw_os_error() as Option<i32>;
242
            }
243
            err = err.source()?;
244
        }
245
    }
246
    /// Consume this error and return an [`ErrorResponse`]
247
    fn into_error_response(self) -> Option<ErrorResponse> {
248
        None
249
    }
250
}
251
impl<T: IntoFfiError> From<T> for FfiError {
252
    fn from(value: T) -> Self {
253
        let status = value.status() as u32;
254
        let message = value
255
            .message()
256
            .try_into()
257
            .expect("Error message had a NUL?");
258
        let os_error_code = value.os_error_code();
259
        let error_response = value.into_error_response();
260
        Self {
261
            status,
262
            message,
263
            error_response,
264
            os_error_code,
265
        }
266
    }
267
}
268
impl From<void::Void> for FfiError {
269
    fn from(value: void::Void) -> Self {
270
        void::unreachable(value)
271
    }
272
}
273

            
274
/// Tried to call a ffi function with a not-permitted argument.
275
#[derive(Clone, Debug, thiserror::Error)]
276
pub(super) enum InvalidInput {
277
    /// Tried to convert a NULL pointer to an FFI object.
278
    #[error("Provided argument was NULL.")]
279
    NullPointer,
280

            
281
    /// Tried to convert a non-UTF string.
282
    #[error("Provided string was not UTF-8")]
283
    BadUtf8,
284

            
285
    /// Tried to use an invalid port.
286
    #[error("Port was not in range 1..65535")]
287
    BadPort,
288

            
289
    /// Tried to use an invalid constant
290
    #[error("Provided constant was not recognized")]
291
    InvalidConstValue,
292
}
293

            
294
impl From<void::Void> for InvalidInput {
295
    fn from(value: void::Void) -> Self {
296
        void::unreachable(value)
297
    }
298
}
299

            
300
impl IntoFfiError for InvalidInput {
301
    fn status(&self) -> FfiStatus {
302
        FfiStatus::InvalidInput
303
    }
304
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
305
        Some(self)
306
    }
307
}
308

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

            
332
    fn into_error_response(self) -> Option<ErrorResponse> {
333
        use crate::ConnectError as E;
334
        match self {
335
            E::AuthenticationFailed(msg) => Some(msg),
336
            _ => None,
337
        }
338
    }
339
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
340
        Some(self)
341
    }
342
}
343

            
344
impl IntoFfiError for tor_rpc_connect::ConnectError {
345
    fn status(&self) -> FfiStatus {
346
        use FfiStatus as F;
347
        use tor_rpc_connect::ConnectError as E;
348
        match self {
349
            E::Io(_) => F::ConnectIo,
350
            E::ExplicitAbort => F::AllConnectAttemptsFailed,
351
            E::LoadCookie(_)
352
            | E::UnsupportedSocketType
353
            | E::UnsupportedAuthType
354
            | E::AfUnixSocketPathAccess(_) => F::ConnectPointNotUsable,
355
            _ => F::Internal,
356
        }
357
    }
358

            
359
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
360
        Some(self)
361
    }
362
}
363

            
364
impl IntoFfiError for crate::conn::ConnectFailure {
365
    fn status(&self) -> FfiStatus {
366
        self.final_error.status()
367
    }
368

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

            
373
    fn message(&self) -> String {
374
        self.display_verbose().to_string()
375
    }
376
}
377

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

            
402
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
403
        Some(self)
404
    }
405
}
406

            
407
impl IntoFfiError for crate::ProtoError {
408
    fn status(&self) -> FfiStatus {
409
        use crate::ProtoError as E;
410
        use FfiStatus as F;
411
        match self {
412
            E::Shutdown(_) => F::Shutdown,
413
            E::InvalidRequest(_) => F::InvalidInput,
414
            E::RequestIdInUse => F::InvalidInput,
415
            E::RequestCompleted => F::RequestCompleted,
416
            E::DuplicateWait => F::Internal,
417
            E::CouldNotEncode(_) => F::Internal,
418
            E::InternalRequestFailed(_) => F::PeerProtocolViolation,
419
        }
420
    }
421
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
422
        Some(self)
423
    }
424
}
425

            
426
impl IntoFfiError for crate::BuilderError {
427
    fn status(&self) -> FfiStatus {
428
        use crate::BuilderError as E;
429
        use FfiStatus as F;
430
        match self {
431
            E::InvalidConnectString => F::InvalidInput,
432
        }
433
    }
434
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
435
        Some(self)
436
    }
437
}
438

            
439
impl IntoFfiError for ErrorResponse {
440
    fn status(&self) -> FfiStatus {
441
        FfiStatus::RequestFailed
442
    }
443
    fn into_error_response(self) -> Option<ErrorResponse> {
444
        Some(self)
445
    }
446
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
447
        None
448
    }
449
}
450

            
451
/// An error returned by the Arti RPC code, exposed as an object.
452
///
453
/// When a function returns an [`ArtiRpcStatus`] other than [`ARTI_RPC_STATUS_SUCCESS`],
454
/// it will also expose a newly allocated value of this type
455
/// via its `error_out` parameter.
456
pub type ArtiRpcError = FfiError;
457

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

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

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

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

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

            
574
/// Release storage held by a provided error.
575
#[allow(clippy::missing_safety_doc)]
576
#[unsafe(no_mangle)]
577
pub unsafe extern "C" fn arti_rpc_err_free(err: *mut ArtiRpcError) {
578
    ffi_body_raw!(
579
        {
580
            let err: Option<Box<ArtiRpcError>> [in_ptr_consume_opt];
581
        } in {
582
            drop(err);
583
            // Safety: Return value is (); trivially safe.
584
            ()
585
        }
586
    );
587
}
588

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

            
608
/// Call `body`, converting any errors or panics that occur into an FfiError,
609
/// and storing that error in `error_out`.
610
pub(super) fn handle_errors<F>(error_out: Option<OutBoxedPtr<FfiError>>, body: F) -> ArtiRpcStatus
611
where
612
    F: FnOnce() -> Result<(), FfiError> + UnwindSafe,
613
{
614
    match abort_on_panic(body) {
615
        Ok(()) => ARTI_RPC_STATUS_SUCCESS,
616
        Err(e) => {
617
            // "body" returned an error.
618
            let status = e.status;
619
            error_out.write_boxed_value_if_ptr_set(e);
620
            status
621
        }
622
    }
623
}