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

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

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

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

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

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

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

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

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

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

            
363
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
364
        Some(self)
365
    }
366
}
367

            
368
impl IntoFfiError for crate::conn::ConnectFailure {
369
    fn status(&self) -> FfiStatus {
370
        self.final_error.status()
371
    }
372

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

            
377
    fn message(&self) -> String {
378
        self.display_verbose().to_string()
379
    }
380
}
381

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

            
406
    fn as_error(&self) -> Option<&(dyn StdError + 'static)> {
407
        Some(self)
408
    }
409
}
410

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

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

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

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

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

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

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

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

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

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

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

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