1
//! Exposed C APIs for arti-rpc-client-core.
2
//!
3
//! See top-level documentation in header file for C conventions that affect the safety of these functions.
4
//! (These include things like "all input pointers must be valid" and so on.)
5

            
6
pub mod err;
7
mod util;
8

            
9
use err::{ArtiRpcError, InvalidInput};
10
use std::ffi::{c_char, c_int, c_void};
11
use std::sync::Mutex;
12
use util::{
13
    OptOutPtrExt as _, OptOutValExt, OutBoxedPtr, OutSocketOwned, OutVal, ffi_body_raw,
14
    ffi_body_with_err,
15
};
16

            
17
#[cfg(not(windows))]
18
use std::os::fd::{AsRawFd, BorrowedFd};
19

            
20
#[cfg(windows)]
21
use std::os::windows::io::{AsRawSocket, BorrowedSocket};
22

            
23
use crate::conn::ShutdownKind;
24
use crate::{
25
    ObjectId, RpcConnBuilder, RpcPoll,
26
    conn::{AnyResponse, RequestHandle},
27
    util::Utf8CString,
28
};
29

            
30
/// A status code returned by an Arti RPC function.
31
///
32
/// On success, a function will return `ARTI_SUCCESS (0)`.
33
/// On failure, a function will return some other status code.
34
pub type ArtiRpcStatus = u32;
35

            
36
/// An open connection to Arti over an a RPC protocol.
37
///
38
/// This is a thread-safe type: you may safely use it from multiple threads at once.
39
///
40
/// Once you are no longer going to use this connection at all, you must free
41
/// it with [`arti_rpc_conn_free`]
42
pub type ArtiRpcConn = crate::RpcConn;
43

            
44
/// A builder object used to configure and construct
45
/// a connection to Arti over the RPC protocol.
46
///
47
/// This is a thread-safe type: you may safely use it from multiple threads at once.
48
///
49
/// Once you are done with this object, you must free it with [`arti_rpc_conn_builder_free`].
50
pub struct ArtiRpcConnBuilder(Mutex<RpcConnBuilder>);
51

            
52
/// An object used to poll a nonblocking RPC connection for responses.
53
///
54
/// `ArtiRpcPoll` is used to integrate an Arti RPC connection with a polling-based
55
/// event loop.  See [`arti_rpc_conn_builder_connect_polling`] for more information.
56
//
57
// Note: we add a mutex to ArtiRpcPoll because we do not trust the user to keep its
58
// use to a single thread.
59
pub struct ArtiRpcPoll(Mutex<RpcPoll>);
60

            
61
/// An owned string, returned by this library.
62
///
63
/// This string must be released with `arti_rpc_str_free`.
64
/// You can inspect it with `arti_rpc_str_get`, but you may not modify it.
65
/// The string is guaranteed to be UTF-8 and NUL-terminated.
66
pub type ArtiRpcStr = Utf8CString;
67

            
68
/// A handle to an in-progress RPC request.
69
///
70
/// This handle must eventually be freed with `arti_rpc_handle_free`.
71
///
72
/// You can wait for the next message with `arti_rpc_handle_wait`.
73
pub type ArtiRpcHandle = RequestHandle;
74

            
75
/// The type of a message returned by an RPC request.
76
pub type ArtiRpcResponseType = c_int;
77

            
78
/// The type of an entry prepended to a connect point search path.
79
pub type ArtiRpcBuilderEntryType = c_int;
80

            
81
/// The manner in which we should shut down using `arti_rpc_conn_shutdown`.
82
pub type ArtiRpcShutdownKind = c_int;
83

            
84
/// The type of a data stream socket.
85
/// (This is always `int` on Unix-like platforms,
86
/// and SOCKET on Windows.)
87
//
88
// NOTE: We declare this as a separate type so that we can give it a default.
89
#[repr(transparent)]
90
pub struct ArtiRpcRawSocket(
91
    #[cfg(windows)] std::os::windows::raw::SOCKET,
92
    #[cfg(not(windows))] c_int,
93
);
94

            
95
impl Default for ArtiRpcRawSocket {
96
    fn default() -> Self {
97
        #[cfg(windows)]
98
        {
99
            Self(!0)
100
        }
101
        #[cfg(not(windows))]
102
        {
103
            Self(-1)
104
        }
105
    }
106
}
107
#[cfg(not(windows))]
108
impl<'a> From<BorrowedFd<'a>> for ArtiRpcRawSocket {
109
    fn from(value: BorrowedFd<'a>) -> Self {
110
        Self(value.as_raw_fd())
111
    }
112
}
113
#[cfg(windows)]
114
impl<'a> From<BorrowedSocket<'a>> for ArtiRpcRawSocket {
115
    fn from(value: BorrowedSocket<'a>) -> Self {
116
        Self(value.as_raw_socket())
117
    }
118
}
119

            
120
/// User-provided information used to implement [`crate::EventLoop`].
121
///
122
/// This type is crate-internal; in the API, we instead take its members as arguments.
123
///
124
/// See [`crate::EventLoop`] for semantics, and [`arti_rpc_conn_builder_connect_polling`]
125
/// for semantics.
126
struct UserEventLoop {
127
    /// A function to invoke with `callback_data_ptr` when the connection starts wanting to write.
128
    /// Returns 0 or an errno.
129
    start_writing_callback: unsafe extern "C" fn(*mut c_void) -> c_int,
130
    /// A function to invoke with `callback_data_ptr` when the connection stop wanting to write.
131
    /// Returns 0 or an errno.
132
    stop_writing_callback: unsafe extern "C" fn(*mut c_void) -> c_int,
133
    /// An argument to pass to one of the callbacks in this struct.
134
    callback_data_ptr: *mut c_void,
135
}
136

            
137
impl crate::EventLoop for UserEventLoop {
138
    fn stop_writing(&mut self) -> std::io::Result<()> {
139
        // SAFETY: the safety requirements for this function are documented in
140
        // `arti_rpc_conn_builder_connect_polling`.
141
        let r = unsafe { (self.stop_writing_callback)(self.callback_data_ptr) };
142
        if r == 0 {
143
            Ok(())
144
        } else {
145
            Err(std::io::Error::from_raw_os_error(r))
146
        }
147
    }
148

            
149
    fn start_writing(&mut self) -> std::io::Result<()> {
150
        // SAFETY: the safety requirements for this function are documented in
151
        // `arti_rpc_conn_builder_connect_polling`.
152
        let r = unsafe { (self.start_writing_callback)(self.callback_data_ptr) };
153
        if r == 0 {
154
            Ok(())
155
        } else {
156
            Err(std::io::Error::from_raw_os_error(r))
157
        }
158
    }
159
}
160

            
161
// SAFETY: We document the thread-safety requirements for UserEventLoop's members in
162
// `arti_rpc_conn_builder_connect_polling`.
163
unsafe impl Send for UserEventLoop {}
164
unsafe impl Sync for UserEventLoop {}
165

            
166
/// A user-provided tag used to distinguish responses for requests submitted to
167
/// [`arti_rpc_conn_submit()`].
168
///
169
/// This value is two pointers wide to facilitate using it to store
170
/// a function pointer and an argument, where appropriate.
171
#[derive(Clone, Copy, Default)]
172
#[repr(C)]
173
#[allow(missing_docs, clippy::exhaustive_structs)]
174
pub struct ArtiRpcUserTag {
175
    pub a: usize,
176
    pub b: usize,
177
}
178

            
179
impl From<crate::UserTag> for ArtiRpcUserTag {
180
    fn from(value: crate::UserTag) -> Self {
181
        Self {
182
            a: value.0,
183
            b: value.1,
184
        }
185
    }
186
}
187
impl From<ArtiRpcUserTag> for crate::UserTag {
188
    fn from(value: ArtiRpcUserTag) -> Self {
189
        Self(value.a, value.b)
190
    }
191
}
192

            
193
/// Try to create a new `ArtiRpcConnBuilder`, with default settings.
194
///
195
/// On success, return `ARTI_RPC_STATUS_SUCCESS` and set `*builder_out`
196
/// to a new `ArtiRpcConnBuilder`.
197
/// Otherwise return some other status code, set `*builder_out` to NULL, and set
198
/// `*error_out` (if provided) to a newly allocated error object.
199
///
200
/// # Ownership
201
///
202
/// The caller is responsible for making sure that `*builder_out` and `*error_out`,
203
/// if set, are eventually freed.
204
#[allow(clippy::missing_safety_doc)]
205
#[unsafe(no_mangle)]
206
pub unsafe extern "C" fn arti_rpc_conn_builder_new(
207
    builder_out: *mut *mut ArtiRpcConnBuilder,
208
    error_out: *mut *mut ArtiRpcError,
209
) -> ArtiRpcStatus {
210
    ffi_body_with_err!(
211
        {
212
            let builder_out: Option<OutBoxedPtr<ArtiRpcConnBuilder>> [out_ptr_opt];
213
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
214
        } in {
215
            let builder = ArtiRpcConnBuilder(Mutex::new(RpcConnBuilder::new()));
216
            builder_out.write_boxed_value_if_ptr_set(builder);
217
        }
218
    )
219
}
220

            
221
/// Release storage held by an `ArtiRpcConnBuilder`.
222
#[allow(clippy::missing_safety_doc)]
223
#[unsafe(no_mangle)]
224
pub unsafe extern "C" fn arti_rpc_conn_builder_free(builder: *mut ArtiRpcConnBuilder) {
225
    ffi_body_raw!(
226
        {
227
            let builder: Option<Box<ArtiRpcConnBuilder>> [in_ptr_consume_opt];
228
        } in {
229
            drop(builder);
230
            // Safety: return value is (); trivially safe.
231
            ()
232
        }
233
    );
234
}
235

            
236
/// Constant to denote a literal connect point.
237
///
238
/// This constant is passed to [`arti_rpc_conn_builder_prepend_entry`].
239
pub const ARTI_RPC_BUILDER_ENTRY_LITERAL_CONNECT_POINT: ArtiRpcBuilderEntryType = 1;
240

            
241
/// Constant to denote a path in which Arti configuration variables are expanded.
242
///
243
/// This constant is passed to [`arti_rpc_conn_builder_prepend_entry`].
244
pub const ARTI_RPC_BUILDER_ENTRY_EXPANDABLE_PATH: ArtiRpcBuilderEntryType = 2;
245

            
246
/// Constant to denote a literal path that is not expanded.
247
///
248
/// This constant is passed to [`arti_rpc_conn_builder_prepend_entry`].
249
pub const ARTI_RPC_BUILDER_ENTRY_LITERAL_PATH: ArtiRpcBuilderEntryType = 3;
250

            
251
/// Prepend a single entry to the connection point path in `builder`.
252
///
253
/// This entry will be considered before any entries in `${ARTI_RPC_CONNECT_PATH}`,
254
/// but after any entry in `${ARTI_RPC_CONNECT_PATH_OVERRIDE}`.
255
///
256
/// The interpretation will depend on the value of `entry_type`.
257
///
258
/// On success, return `ARTI_RPC_STATUS_SUCCESS`.
259
/// Otherwise return some other status code, and set
260
/// `*error_out` (if provided) to a newly allocated error object.
261
///
262
/// # Ownership
263
///
264
/// The caller is responsible for making sure that `*error_out`,
265
/// if set, is eventually freed.
266
#[allow(clippy::missing_safety_doc)]
267
#[unsafe(no_mangle)]
268
pub unsafe extern "C" fn arti_rpc_conn_builder_prepend_entry(
269
    builder: *const ArtiRpcConnBuilder,
270
    entry_type: ArtiRpcBuilderEntryType,
271
    entry: *const c_char,
272
    error_out: *mut *mut ArtiRpcError,
273
) -> ArtiRpcStatus {
274
    ffi_body_with_err!(
275
        {
276
            let builder: Option<&ArtiRpcConnBuilder> [in_ptr_opt];
277
            let entry: Option<&str> [in_str_opt];
278
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
279
        } in {
280
            let builder = builder.ok_or(InvalidInput::NullPointer)?;
281
            let entry = entry.ok_or(InvalidInput::NullPointer)?;
282
            let mut b = builder.0.lock().expect("Poisoned lock");
283
            match entry_type {
284
                ARTI_RPC_BUILDER_ENTRY_LITERAL_CONNECT_POINT =>
285
                    b.prepend_literal_entry(entry.to_string()),
286
                ARTI_RPC_BUILDER_ENTRY_EXPANDABLE_PATH =>
287
                    b.prepend_path(entry.into()),
288
                ARTI_RPC_BUILDER_ENTRY_LITERAL_PATH =>
289
                    b.prepend_literal_path(entry.into()),
290
                _ => return Err(InvalidInput::InvalidConstValue.into()),
291
            }
292
        }
293
    )
294
}
295

            
296
/// Instruct `builder` to prefer connection points that grant superuser permission.
297
///
298
/// If no such connect points are found,
299
/// and `required` is true,
300
/// then the connection will fail with an error.
301
/// On success, return `ARTI_RPC_STATUS_SUCCESS`.
302
/// Otherwise return some other status code, and set
303
/// `*error_out` (if provided) to a newly allocated error object.
304
///
305
/// # Ownership
306
///
307
/// The caller is responsible for making sure that `*error_out`,
308
/// if set, is eventually freed.
309
#[allow(clippy::missing_safety_doc)]
310
#[unsafe(no_mangle)]
311
pub unsafe extern "C" fn arti_rpc_conn_builder_prefer_superuser_permission(
312
    builder: *const ArtiRpcConnBuilder,
313
    required: c_int,
314
    error_out: *mut *mut ArtiRpcError,
315
) -> ArtiRpcStatus {
316
    ffi_body_with_err!(
317
        {
318
            let builder: Option<&ArtiRpcConnBuilder> [in_ptr_opt];
319
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
320
        } in {
321
            let builder = builder.ok_or(InvalidInput::NullPointer)?;
322
            let mut b = builder.0.lock().expect("Poisoned lock");
323
            b.prefer_superuser_permission(required != 0);
324
        }
325
    )
326
}
327

            
328
/// Use `builder` to open a new RPC connection to Arti.
329
///
330
/// On success, return `ARTI_RPC_STATUS_SUCCESS`,
331
/// and set `conn_out` to a new ArtiRpcConn.
332
/// Otherwise return some other status code, set *conn_out to NULL, and set
333
/// `*error_out` (if provided) to a newly allocated error object.
334
///
335
/// # Ownership
336
///
337
/// The caller is responsible for making sure that `*rpc_conn_out` and `*error_out`,
338
/// if set, are eventually freed.
339
#[allow(clippy::missing_safety_doc)]
340
#[unsafe(no_mangle)]
341
pub unsafe extern "C" fn arti_rpc_conn_builder_connect(
342
    builder: *const ArtiRpcConnBuilder,
343
    rpc_conn_out: *mut *mut ArtiRpcConn,
344
    error_out: *mut *mut ArtiRpcError,
345
) -> ArtiRpcStatus {
346
    ffi_body_with_err!(
347
        {
348
            let builder: Option<&ArtiRpcConnBuilder> [in_ptr_opt];
349
            let rpc_conn_out: Option<OutBoxedPtr<ArtiRpcConn>> [out_ptr_opt];
350
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
351
        } in {
352
            let builder = builder.ok_or(InvalidInput::NullPointer)?;
353
            let b = builder.0.lock().expect("Poisoned lock");
354
            let conn = b.connect()?;
355
            rpc_conn_out.write_boxed_value_if_ptr_set(conn);
356
        }
357
    )
358
}
359

            
360
/// Use `builder` to open a new RPC connection to Arti,
361
/// with support to integrate with an event-driven IO loop.
362
///
363
/// If you are not integrating with poll() or select()-style loop,
364
/// you do not need to use this function.
365
///
366
/// On success, return `ARTI_RPC_STATUS_SUCCESS`,
367
/// set `rpc_conn_out` to a new ArtiRpcConn,
368
/// and set `poll_out` to a new ArtiRpcPoll.
369
/// Otherwise return some other status code, set *conn_out and *poll_out to NULL,
370
/// and set `*error_out` (if provided) to a newly allocated error object.
371
///
372
/// # Callbacks, data, and requirements.
373
///
374
/// The user code must provide an event loop
375
/// that can monitor an underlying connection for readability and writability.
376
///
377
/// The RPC library provides the user code with an OS handle to monitor.
378
/// The user code should always monitor this handle for readability.
379
/// It should monitor the handle for writability whenever the connection
380
/// "wants to write".
381
/// Whenever one of these events occurs, the user code should invoke
382
/// `arti_rpc_poll_poll` until it indicates that it would block.
383
///
384
/// The `start_writing_callback` and `start_reading_callback` functions
385
/// must be provided.  They will be invoked (respectively) whenever the connection
386
/// starts wanting to write, or stops wanting to write.
387
/// They should return 0 on success, and _return_ an `errno` value on failure.
388
/// (Any `errno` value that they _set_ will be ignored.)
389
/// They will be passed `callback_data_ptr` as an argument.
390
///
391
/// If your program invokes `arti_rpc_*` from multiple threads,
392
/// these functions must be thread-safe.
393
///
394
/// There are additional requirements for these functions.
395
/// For full information, see the documentation for [`EventLoop`](crate::EventLoop`).
396
///
397
/// # Ownership
398
///
399
/// The caller is responsible for making sure that `*rpc_conn_out`,
400
/// `*rpc_poll_out`, and `*error_out`,
401
/// if set, are eventually freed.
402
///
403
/// The caller is responsible for making sure that `callback_data_ptr`,
404
/// and the callback functions,
405
/// live for at least as long as the returned `ArtiRpcPoll`.
406
#[allow(clippy::missing_safety_doc)]
407
#[unsafe(no_mangle)]
408
pub unsafe extern "C" fn arti_rpc_conn_builder_connect_polling(
409
    builder: *const ArtiRpcConnBuilder,
410
    start_writing_callback: Option<unsafe extern "C" fn(*mut c_void) -> c_int>,
411
    stop_writing_callback: Option<unsafe extern "C" fn(*mut c_void) -> c_int>,
412
    callback_data_ptr: *mut c_void,
413
    rpc_conn_out: *mut *mut ArtiRpcConn,
414
    rpc_poll_out: *mut *mut ArtiRpcPoll,
415
    error_out: *mut *mut ArtiRpcError,
416
) -> ArtiRpcStatus {
417
    ffi_body_with_err!(
418
        {
419
            let builder: Option<&ArtiRpcConnBuilder> [in_ptr_opt];
420
            let rpc_conn_out: Option<OutBoxedPtr<ArtiRpcConn>> [out_ptr_opt];
421
            let rpc_poll_out: Option<OutBoxedPtr<ArtiRpcPoll>> [out_ptr_opt];
422
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
423
        } in {
424
            let builder = builder.ok_or(InvalidInput::NullPointer)?;
425
            let start_writing_callback = start_writing_callback.ok_or(InvalidInput::NullPointer)?;
426
            let stop_writing_callback = stop_writing_callback.ok_or(InvalidInput::NullPointer)?;
427

            
428
            let event_loop = Box::new(UserEventLoop {
429
                start_writing_callback, stop_writing_callback,
430
                callback_data_ptr,
431
            });
432

            
433
            let b = builder.0.lock().expect("Poisoned lock");
434
            let (conn, poll) = b.connect_polling(event_loop)?;
435
            let poll = ArtiRpcPoll(Mutex::new(poll));
436
            rpc_conn_out.write_boxed_value_if_ptr_set(conn);
437
            rpc_poll_out.write_boxed_value_if_ptr_set(poll);
438
        }
439
    )
440
}
441

            
442
/// Given a pointer to an RPC connection, return the object ID for its negotiated session.
443
///
444
/// (The session was negotiated as part of establishing the connection.
445
/// Its object ID is necessary to invoke most other functionality on Arti.)
446
///
447
/// The caller should be prepared for a possible NULL return, in case somehow
448
/// no session was negotiated.
449
///
450
/// # Ownership
451
///
452
/// The resulting string is a reference to part of the `ArtiRpcConn`.
453
/// It lives for no longer than the underlying `ArtiRpcConn` object.
454
#[allow(clippy::missing_safety_doc)]
455
#[unsafe(no_mangle)]
456
pub unsafe extern "C" fn arti_rpc_conn_get_session_id(
457
    rpc_conn: *const ArtiRpcConn,
458
) -> *const c_char {
459
    ffi_body_raw! {
460
        {
461
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
462
        } in {
463
            rpc_conn.and_then(crate::RpcConn::session)
464
                .map(|s| s.as_ptr())
465
                .unwrap_or(std::ptr::null())
466
            // Safety: returned pointer is null, or semantically borrowed from `rpc_conn`.
467
            // It is only null if `rpc_conn` was null or its session was null.
468
            // The caller is not allowed to modify it.
469
        }
470
    }
471
}
472

            
473
/// Run an RPC request over `rpc_conn` and wait for a successful response.
474
///
475
/// The message `msg` should be a valid RPC request in JSON format.
476
/// If you omit its `id` field, one will be generated: this is typically the best way to use this function.
477
///
478
/// On success, return `ARTI_RPC_STATUS_SUCCESS` and set `*response_out` to a newly allocated string
479
/// containing the JSON response to your request (including `id` and `response` fields).
480
///
481
/// Otherwise return some other status code,  set `*response_out` to NULL,
482
/// and set `*error_out` (if provided) to a newly allocated error object.
483
///
484
/// (If response_out is set to NULL, then any successful response will be ignored.)
485
///
486
/// # Ownership
487
///
488
/// The caller is responsible for making sure that `*error_out`, if set, is eventually freed.
489
///
490
/// The caller is responsible for making sure that `*response_out`, if set, is eventually freed.
491
#[allow(clippy::missing_safety_doc)]
492
#[unsafe(no_mangle)]
493
pub unsafe extern "C" fn arti_rpc_conn_execute(
494
    rpc_conn: *const ArtiRpcConn,
495
    msg: *const c_char,
496
    response_out: *mut *mut ArtiRpcStr,
497
    error_out: *mut *mut ArtiRpcError,
498
) -> ArtiRpcStatus {
499
    ffi_body_with_err!(
500
        {
501
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
502
            let msg: Option<&str> [in_str_opt];
503
            let response_out: Option<OutBoxedPtr<ArtiRpcStr>> [out_ptr_opt];
504
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
505
        } in {
506
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
507
            let msg = msg.ok_or(InvalidInput::NullPointer)?;
508

            
509
            let success = rpc_conn.execute(msg)??;
510
            response_out.write_boxed_value_if_ptr_set(Utf8CString::from(success));
511
        }
512
    )
513
}
514

            
515
/// Send an RPC request over `rpc_conn`, and return a handle that can wait for a successful response.
516
///
517
/// The message `msg` should be a valid RPC request in JSON format.
518
/// If you omit its `id` field, one will be generated: this is typically the best way to use this function.
519
///
520
/// On success, return `ARTI_RPC_STATUS_SUCCESS` and set `*handle_out` to a newly allocated `ArtiRpcHandle`.
521
///
522
/// Otherwise return some other status code,  set `*handle_out` to NULL,
523
/// and set `*error_out` (if provided) to a newly allocated error object.
524
///
525
/// (If `handle_out` is set to NULL, the request will not be sent, and an error will be returned.)
526
///
527
/// # Ownership
528
///
529
/// The caller is responsible for making sure that `*error_out`, if set, is eventually freed.
530
///
531
/// The caller is responsible for making sure that `*handle_out`, if set, is eventually freed.
532
#[allow(clippy::missing_safety_doc)]
533
#[unsafe(no_mangle)]
534
pub unsafe extern "C" fn arti_rpc_conn_execute_with_handle(
535
    rpc_conn: *const ArtiRpcConn,
536
    msg: *const c_char,
537
    handle_out: *mut *mut ArtiRpcHandle,
538
    error_out: *mut *mut ArtiRpcError,
539
) -> ArtiRpcStatus {
540
    ffi_body_with_err!(
541
        {
542
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
543
            let msg: Option<&str> [in_str_opt];
544
            let handle_out: Option<OutBoxedPtr<ArtiRpcHandle>> [out_ptr_opt];
545
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
546
        } in {
547
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
548
            let msg = msg.ok_or(InvalidInput::NullPointer)?;
549
            let handle_out = handle_out.ok_or(InvalidInput::NullPointer)?;
550

            
551
            let handle = rpc_conn.execute_with_handle(msg)?;
552
            handle_out.write_value_boxed(handle);
553
        }
554
    )
555
}
556

            
557
/// Attempt to cancel the request on `rpc_conn` with the provided `handle`.
558
///
559
/// Note that cancellation _will_ fail if the handle has already been cancelled,
560
/// or has already succeeded or failed.
561
///
562
/// On success, return `ARTI_RPC_STATUS_SUCCESS`.
563
///
564
/// Otherwise return some other status code,
565
/// and set `*error_out` (if provided) to a newly allocated error object.
566
#[allow(clippy::missing_safety_doc)]
567
#[unsafe(no_mangle)]
568
pub unsafe extern "C" fn arti_rpc_conn_cancel_handle(
569
    rpc_conn: *const ArtiRpcConn,
570
    handle: *const ArtiRpcHandle,
571
    error_out: *mut *mut ArtiRpcError,
572
) -> ArtiRpcStatus {
573
    ffi_body_with_err!(
574
        {
575
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
576
            let handle: Option<&ArtiRpcHandle> [in_ptr_opt];
577
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
578
        } in {
579
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
580
            let handle = handle.ok_or(InvalidInput::NullPointer)?;
581
            let id = handle.id();
582
            rpc_conn.cancel(id)?;
583
        }
584
    )
585
}
586

            
587
/// A constant indicating that a message is a final result.
588
///
589
/// After a result has been received, a handle will not return any more responses,
590
/// and should be freed.
591
pub const ARTI_RPC_RESPONSE_TYPE_RESULT: ArtiRpcResponseType = 1;
592
/// A constant indicating that a message is a non-final update.
593
///
594
/// After an update has been received, the handle may return additional responses.
595
pub const ARTI_RPC_RESPONSE_TYPE_UPDATE: ArtiRpcResponseType = 2;
596
/// A constant indicating that a message is a final error.
597
///
598
/// After an error has been received, a handle will not return any more responses,
599
/// and should be freed.
600
pub const ARTI_RPC_RESPONSE_TYPE_ERROR: ArtiRpcResponseType = 3;
601

            
602
impl AnyResponse {
603
    /// Return an appropriate `ARTI_RPC_RESPONSE_TYPE_*` for this response.
604
    fn response_type(&self) -> ArtiRpcResponseType {
605
        match self {
606
            Self::Success(_) => ARTI_RPC_RESPONSE_TYPE_RESULT,
607
            Self::Update(_) => ARTI_RPC_RESPONSE_TYPE_UPDATE,
608
            Self::Error(_) => ARTI_RPC_RESPONSE_TYPE_ERROR,
609
        }
610
    }
611
}
612

            
613
/// Wait until some response arrives on an arti_rpc_handle, or until an error occurs.
614
///
615
/// On success, return `ARTI_RPC_STATUS_SUCCESS`; set `*response_out`, if present, to a
616
/// newly allocated string, and set `*response_type_out`, if present, to the type of the response.
617
/// (The type will be `ARTI_RPC_RESPONSE_TYPE_RESULT` if the response is a final result,
618
/// or `ARTI_RPC_RESPONSE_TYPE_ERROR` if the response is a final error,
619
/// or `ARTI_RPC_RESPONSE_TYPE_UPDATE` if the response is a non-final update.)
620
///
621
/// Otherwise return some other status code, set `*response_out` to NULL,
622
/// set `*response_type_out` to zero,
623
/// and set `*error_out` (if provided) to a newly allocated error object.
624
///
625
/// Note that receiving an error reply from Arti is _not_ treated as an error in this function.
626
/// That is to say, if Arti sends back an error, this function will return `ARTI_SUCCESS`,
627
/// and deliver the error from Arti in `*response_out`, setting `*response_type_out` to
628
/// `ARTI_RPC_RESPONSE_TYPE_ERROR`.
629
///
630
/// It is safe to call this function on the same handle from multiple threads at once.
631
/// If you do, each response will be sent to exactly one thread.
632
/// It is unspecified which thread will receive which response or which error.
633
///
634
/// # Ownership
635
///
636
/// The caller is responsible for making sure that `*error_out`, if set, is eventually freed.
637
///
638
/// The caller is responsible for making sure that `*response_out`, if set, is eventually freed.
639
#[allow(clippy::missing_safety_doc)]
640
#[unsafe(no_mangle)]
641
pub unsafe extern "C" fn arti_rpc_handle_wait(
642
    handle: *const ArtiRpcHandle,
643
    response_out: *mut *mut ArtiRpcStr,
644
    response_type_out: *mut ArtiRpcResponseType,
645
    error_out: *mut *mut ArtiRpcError,
646
) -> ArtiRpcStatus {
647
    ffi_body_with_err! {
648
        {
649
            let handle: Option<&ArtiRpcHandle> [in_ptr_opt];
650
            let response_out: Option<OutBoxedPtr<ArtiRpcStr>> [out_ptr_opt];
651
            let response_type_out: Option<OutVal<ArtiRpcResponseType>> [out_val_opt];
652
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
653
        } in {
654
            let handle = handle.ok_or(InvalidInput::NullPointer)?;
655

            
656
            let response = handle.wait_with_updates()?;
657

            
658
            let rtype = response.response_type();
659
            response_type_out.write_value_if_ptr_set(rtype);
660
            response_out.write_boxed_value_if_ptr_set(response.into_string());
661
        }
662
    }
663
}
664

            
665
/// Release storage held by an `ArtiRpcHandle`.
666
///
667
/// NOTE: This does not cancel the underlying request if it is still running.
668
/// To cancel a request, use `arti_rpc_conn_cancel_handle`.
669
#[allow(clippy::missing_safety_doc)]
670
#[unsafe(no_mangle)]
671
pub unsafe extern "C" fn arti_rpc_handle_free(handle: *mut ArtiRpcHandle) {
672
    ffi_body_raw!(
673
        {
674
            let handle: Option<Box<ArtiRpcHandle>> [in_ptr_consume_opt];
675
        } in {
676
            drop(handle);
677
            // Safety: Return value is (); trivially safe.
678
            ()
679
        }
680
    );
681
}
682

            
683
/// Submit an RPC request to `rpc_conn`, but do not wait for a response.
684
///
685
/// The message `msg` should be a valid RPC request in JSON format.
686
/// If you omit its `id` field, one will be generated:
687
/// this is typically the best way to use this function.
688
///
689
/// The `tag` value should be a value to identify this request;
690
/// it will be returned later along with any responses to this request.
691
///
692
/// On success, return `ARTI_RPC_STATUS_SUCCESS`.
693
///
694
/// Otherwise return some other status code,  set `*response_out` to NULL,
695
/// and set `*error_out` (if provided) to a newly allocated error object.
696
///
697
/// After calling this function, the caller must later make sure
698
/// that [`arti_rpc_conn_wait()`] is called on the connection to wait for responses
699
/// to _any_ submitted request.
700
/// (If the  connection was crated with [`arti_rpc_conn_builder_connect_polling`],
701
/// the user must call [`arti_rpc_poll_poll()`] instead.)
702
///
703
/// (If nobody is running [`arti_rpc_conn_wait()`] or [`arti_rpc_poll_poll()`],
704
/// then responses will never be handled,
705
/// and can potentially fill up memory.)
706
///
707
/// # Ownership
708
///
709
/// The caller is responsible for making sure that `*error_out`, if set, is eventually freed.
710
///
711
/// # Thread safety
712
///
713
/// It is safe to call this function from multiple threads at once;
714
/// it is not specified which thread will receive notifications for which request.
715
#[allow(clippy::missing_safety_doc)]
716
#[unsafe(no_mangle)]
717
pub unsafe extern "C" fn arti_rpc_conn_submit(
718
    rpc_conn: *const ArtiRpcConn,
719
    msg: *const c_char,
720
    tag: *const ArtiRpcUserTag,
721
    error_out: *mut *mut ArtiRpcError,
722
) -> ArtiRpcStatus {
723
    ffi_body_with_err!(
724
        {
725
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
726
            let msg: Option<&str> [in_str_opt];
727
            let tag: Option<&ArtiRpcUserTag> [in_ptr_opt];
728
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
729
        } in {
730
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
731
            let msg = msg.ok_or(InvalidInput::NullPointer)?;
732
            let tag = tag.ok_or(InvalidInput::NullPointer)?;
733

            
734
            let () = rpc_conn.submit((*tag).into(), msg)?;
735
        }
736
    )
737
}
738

            
739
/// Wait for responses to arrive for requests sent via [`arti_rpc_conn_submit`].
740
///
741
/// On success, return `ARTI_RPC_STATUS_SUCCESS`;
742
/// set `*tag_out`, if present,  to the `ArtiRpcUserTag` originally provided with the request;
743
/// set `*response_out`, if present, to a newly allocated string;
744
/// and set `*response_type_out`,  if present, to the type of the response.
745
/// (The type will be `ARTI_RPC_RESPONSE_TYPE_RESULT` if the response is a final result,
746
/// or `ARTI_RPC_RESPONSE_TYPE_ERROR` if the response is a final error,
747
/// or `ARTI_RPC_RESPONSE_TYPE_UPDATE` if the response is a non-final update.)
748
///
749
/// Otherwise return some other status code, set `*response_out` to NULL,
750
/// set `*response_type_out` and `*tag_out` to zero,
751
/// and set `*error_out` (if provided) to a newly allocated error object.
752
///
753
/// Note that receiving an error reply from Arti is _not_ treated as an error in this function.
754
/// That is to say, if Arti sends back an error, this function will return `ARTI_SUCCESS`,
755
/// and deliver the error from Arti in `*response_out`, setting `*response_type_out` to
756
/// `ARTI_RPC_RESPONSE_TYPE_ERROR`.
757
///
758
/// # Thread safety
759
///
760
/// It is safe to call this function from multiple threads at once;
761
/// it is not specified which thread will receive notifications for which request.
762
///
763
/// # Ownership
764
///
765
/// The caller is responsible for making sure that `*error_out`, if set, is eventually freed.
766
///
767
/// The caller is responsible for making sure that `*response_out`, if set,
768
/// is eventually freed.
769
#[allow(clippy::missing_safety_doc)]
770
#[unsafe(no_mangle)]
771
pub unsafe extern "C" fn arti_rpc_conn_wait(
772
    rpc_conn: *const ArtiRpcConn,
773
    tag_out: *mut ArtiRpcUserTag,
774
    response_out: *mut *mut ArtiRpcStr,
775
    response_type_out: *mut ArtiRpcResponseType,
776
    error_out: *mut *mut ArtiRpcError,
777
) -> ArtiRpcStatus {
778
    ffi_body_with_err!(
779
        {
780
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
781
            let tag_out: Option<OutVal<ArtiRpcUserTag>> [out_val_opt];
782
            let response_out: Option<OutBoxedPtr<ArtiRpcStr>> [out_ptr_opt];
783
            let response_type_out: Option<OutVal<ArtiRpcResponseType>> [out_val_opt];
784
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
785
        } in {
786
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
787

            
788
            let (tag, response) = rpc_conn.wait()?;
789
            tag_out.write_value_if_ptr_set(tag.into());
790

            
791
            let rtype = response.response_type();
792
            response_type_out.write_value_if_ptr_set(rtype);
793
            response_out.write_boxed_value_if_ptr_set(response.into_string());
794
        }
795
    )
796
}
797

            
798
/// Argument for [`arti_rpc_conn_shutdown`]: Shut down immediately.
799
///
800
/// If a request has been queued but a reply has not yet been received for that request,
801
/// it is indeterminate whether that request will actually be sent,
802
/// or whether it will be dropped from the outgoing queue.
803
/// If you require a request to be executed, wait until a reply has been received
804
/// before you shut down the RPC connection.
805
///
806
/// It is unspecified whether the underlying socket is closed immediately,
807
/// or whether it will only close when the [`ArtiRpcConn`] is freed.
808
pub const ARTI_RPC_SHUTDOWN_IMMEDIATE: ArtiRpcShutdownKind = 1;
809

            
810
impl ShutdownKind {
811
    /// Try to convert `input` to a [`ShutdownKind`].  Return an error if it is not recognized.
812
    fn from_c(input: ArtiRpcShutdownKind) -> Result<ShutdownKind, InvalidInput> {
813
        Ok(match input {
814
            ARTI_RPC_SHUTDOWN_IMMEDIATE => ShutdownKind::Immediate,
815
            _ => return Err(InvalidInput::InvalidConstValue),
816
        })
817
    }
818
}
819

            
820
/// Tell an RPC connection to shut down.
821
///
822
/// The `how` argument determines the exact manner in which the connection is shut down.
823
#[allow(clippy::missing_safety_doc)]
824
#[unsafe(no_mangle)]
825
pub unsafe extern "C" fn arti_rpc_conn_shutdown(
826
    rpc_conn: *const ArtiRpcConn,
827
    how: ArtiRpcShutdownKind,
828
    error_out: *mut *mut ArtiRpcError,
829
) -> ArtiRpcStatus {
830
    ffi_body_with_err!(
831
        {
832
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
833
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
834
        } in {
835
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
836
            let how = ShutdownKind::from_c(how)?;
837

            
838
            rpc_conn.shutdown(how)?;
839
        }
840
    )
841
}
842

            
843
/// Handle IO events for the associated RPC connection, without blocking.
844
///
845
/// This method requires that the connection was created with
846
/// [`arti_rpc_conn_builder_connect_polling()`].
847
/// It reads and writes data from the RPC server, until either:
848
///
849
/// * A response is available to a request created with [`arti_rpc_conn_submit`].
850
///   In this case,
851
///   `*tag_out`, if present, is set to the `ArtiRpcUserTag` originally provided with the request;
852
///   `*response_out`, if present, is set to a newly allocated string;
853
///   `*response_type_out`, if present, is set to the type of the response.
854
///   The `*would_block_out` flag, if present, is set to 0.
855
///   Other output pointers, if present, are set to NULL or 0.
856
///
857
/// * No further progress can be made without blocking.
858
///   In this case,
859
///   `*would_block_out` is set to 1.
860
///   Other output pointers, if present, are set to NULL or 0.
861
///
862
/// * An error occurs.
863
///   (This does not include receiving an error response from the RPC server.)
864
///   In this case, `*error_out`, if present, is set to that error.
865
///   Other output pointers, if present, are set to NULL or 0.
866
///
867
/// Returns `ARTI_RPC_SUCCESS` in the first two cases,
868
/// and an error code on failure.
869
///
870
/// # Thread safety
871
///
872
/// While it is not unsafe to call this function at once,
873
/// it is generally pointless:
874
/// only one thread can make progress at a time.
875
///
876
/// # Ownership
877
///
878
/// The caller is responsible for making sure
879
/// that `*tag_out`, *response_out`, and `*error_out`,
880
/// if set, are eventually freed.
881
#[allow(clippy::missing_safety_doc)]
882
#[unsafe(no_mangle)]
883
pub unsafe extern "C" fn arti_rpc_poll_poll(
884
    rpc_poll: *const ArtiRpcPoll,
885
    tag_out: *mut ArtiRpcUserTag,
886
    response_out: *mut *mut ArtiRpcStr,
887
    response_type_out: *mut ArtiRpcResponseType,
888
    would_block_out: *mut c_int,
889
    error_out: *mut *mut ArtiRpcError,
890
) -> ArtiRpcStatus {
891
    ffi_body_with_err!({
892
        let rpc_poll: Option<&ArtiRpcPoll> [in_ptr_opt];
893
        let tag_out: Option<OutVal<ArtiRpcUserTag>> [out_val_opt];
894
        let response_out: Option<OutBoxedPtr<ArtiRpcStr>> [out_ptr_opt];
895
        let response_type_out: Option<OutVal<ArtiRpcResponseType>> [out_val_opt];
896
        let would_block_out: Option<OutVal<c_int>> [out_val_opt];
897
        err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
898
    } in {
899
        let rpc_poll = rpc_poll.ok_or(InvalidInput::NullPointer)?;
900

            
901
        let (tag, response)  = match rpc_poll.0.lock().expect("Lock poisoned").poll()? {
902
            Ok(v) => v,
903
            Err(crate::WouldBlock) => {
904
                would_block_out.write_value_if_ptr_set(1);
905
                return Ok(());
906
            }
907
        };
908

            
909
        tag_out.write_value_if_ptr_set(tag.into());
910
        let rtype = response.response_type();
911
        response_type_out.write_value_if_ptr_set(rtype);
912
        response_out.write_boxed_value_if_ptr_set(response.into_string());
913
    })
914
}
915

            
916
/// Return true if `rpc_poll` wants to write,
917
/// and false otherwise.
918
///
919
/// See [`arti_rpc_conn_builder_connect_polling`] for more information.
920
#[allow(clippy::missing_safety_doc)]
921
#[unsafe(no_mangle)]
922
pub unsafe extern "C" fn arti_rpc_poll_wants_to_write(rpc_poll: *const ArtiRpcPoll) -> c_int {
923
    ffi_body_raw!({
924
        let rpc_poll: Option<&ArtiRpcPoll> [in_ptr_opt];
925
    } in {
926
        let Some(rpc_poll) = rpc_poll else {
927
            return 0;
928
        };
929
        let wants_to_write: bool = rpc_poll.0.lock()
930
            .expect("Lock poisoned")
931
            .wants_to_write();
932
        // Safety: return type is c_int; trivially safe.
933
        c_int::from(wants_to_write)
934
    })
935
}
936

            
937
/// Return the raw OS socket associated with the provided `ArtiRpcPoll`.
938
///
939
/// This function returns a SOCKET on windows, and a file descriptor elsewhere.
940
///
941
/// On failure, returns INVALID_SOCKET on windows, and -1 elsewhere.
942
///
943
/// # Ownership
944
///
945
/// The returned socket is owned by the `ArtiRpcPoll`.
946
/// The caller must not close it, read from it, or write to it.
947
/// It should _only_ be polled for readiness events.
948
#[allow(clippy::missing_safety_doc)]
949
#[unsafe(no_mangle)]
950
pub unsafe extern "C" fn arti_rpc_poll_get_socket(
951
    rpc_poll: *const ArtiRpcPoll,
952
) -> ArtiRpcRawSocket {
953
    ffi_body_raw!({
954
        let rpc_poll: Option<&ArtiRpcPoll> [in_ptr_opt];
955
    } in {
956
        let Some(rpc_poll) = rpc_poll else {
957
            return ArtiRpcRawSocket::default();
958
        };
959
        let raw_socket: Result<ArtiRpcRawSocket, _> = {
960
            let rpc_poll = rpc_poll.0.lock().expect("Lock poisoned");
961
            #[cfg(windows)]
962
            {
963
                rpc_poll.try_as_socket().map(ArtiRpcRawSocket::from)
964
            }
965
            #[cfg(not(windows))]
966
            {
967
                rpc_poll.try_as_fd().map(ArtiRpcRawSocket::from)
968
            }
969
        };
970

            
971
        // Safety: return type is trivially safe.
972
        raw_socket.unwrap_or_default()
973
    })
974
}
975

            
976
/// Free the provided `ArtiRpcPoll`.
977
#[allow(clippy::missing_safety_doc)]
978
#[unsafe(no_mangle)]
979
pub unsafe extern "C" fn arti_rpc_poll_free(rpc_poll: *mut ArtiRpcPoll) {
980
    ffi_body_raw!(
981
        {
982
            let rpc_poll: Option<Box<ArtiRpcPoll>> [in_ptr_consume_opt];
983
        } in {
984
            drop(rpc_poll);
985
            // Safety: Return value is (); trivially safe.
986
            ()
987
        }
988
    );
989
}
990

            
991
/// Free a string returned by the Arti RPC API.
992
#[allow(clippy::missing_safety_doc)]
993
#[unsafe(no_mangle)]
994
pub unsafe extern "C" fn arti_rpc_str_free(string: *mut ArtiRpcStr) {
995
    ffi_body_raw!(
996
        {
997
            let string: Option<Box<ArtiRpcStr>> [in_ptr_consume_opt];
998
        } in {
999
            drop(string);
            // Safety: Return value is (); trivially safe.
            ()
        }
    );
}
/// Return a const pointer to the underlying nul-terminated string from an `ArtiRpcStr`.
///
/// The resulting string is guaranteed to be valid UTF-8.
///
/// (Returns NULL if the input is NULL.)
///
/// # Correctness requirements
///
/// The resulting string pointer is valid only for as long as the input `string` is not freed.
#[allow(clippy::missing_safety_doc)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn arti_rpc_str_get(string: *const ArtiRpcStr) -> *const c_char {
    ffi_body_raw!(
        {
            let string: Option<&ArtiRpcStr> [in_ptr_opt];
        } in {
            // Safety: returned pointer is null, or semantically borrowed from `string`.
            // It is only null if `string` was null.
            // The caller is not allowed to modify it.
            match string {
                Some(s) => s.as_ptr(),
                None => std::ptr::null(),
            }
        }
    )
}
/// Close and free an open Arti RPC connection.
#[allow(clippy::missing_safety_doc)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn arti_rpc_conn_free(rpc_conn: *mut ArtiRpcConn) {
    ffi_body_raw!(
        {
            let rpc_conn: Option<Box<ArtiRpcConn>> [in_ptr_consume_opt];
        } in {
            drop(rpc_conn);
            // Safety: Return value is (); trivially safe.
            ()
        }
    );
}
/// Try to open an anonymized data stream over Arti.
///
/// Use the proxy information associated with `rpc_conn` to make the stream,
/// and store the resulting fd (or `SOCKET` on Windows) into `*socket_out`.
///
/// The stream will target the address `hostname`:`port`.
///
/// If `on_object` is provided, it is an `ObjectId` for client-like object
/// (such as a Session or a Client)
/// that should be used to make the stream.
///
/// The resulting stream will be configured
/// not to share a circuit with any other stream
/// having a different `isolation`.
/// (If your application doesn't care about isolating its streams from one another,
/// it is acceptable to leave `isolation` as an empty string.)
///
/// If `stream_id_out` is provided,
/// the resulting stream will have an identifier within the RPC system,
/// so that you can run other RPC commands on it.
///
/// On success, return `ARTI_RPC_STATUS_SUCCESS`.
/// Otherwise return some other status code, set `*socket_out` to -1
/// (or `INVALID_SOCKET` on Windows),
/// and set `*error_out` (if provided) to a newly allocated error object.
///
/// # Caveats
///
/// When possible, use a hostname rather than an IP address.
/// If you *must* use an IP address, make sure that you have not gotten it
/// by a non-anonymous DNS lookup.
/// (Calling `gethostname()` or `getaddrinfo()` directly
/// would lose anonymity: they inform the user's DNS server,
/// and possibly many other parties, about the target address
/// you are trying to visit.)
///
/// The resulting socket will actually be a TCP connection to Arti,
/// not directly to your destination.
/// Therefore, passing it to functions like `getpeername()`
/// may give unexpected results.
///
/// If `stream_id_out` is provided,
/// the caller is responsible for releasing the ObjectId;
/// Arti will not deallocate it even when the stream is closed.
///
/// # Ownership
///
/// The caller is responsible for making sure that
/// `*stream_id_out` and `*error_out`, if set,
/// are eventually freed.
///
/// The caller is responsible for making sure that `*socket_out`, if set,
/// is eventually closed.
#[allow(clippy::missing_safety_doc)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn arti_rpc_conn_open_stream(
    rpc_conn: *const ArtiRpcConn,
    hostname: *const c_char,
    port: c_int,
    on_object: *const c_char,
    isolation: *const c_char,
    socket_out: *mut ArtiRpcRawSocket,
    stream_id_out: *mut *mut ArtiRpcStr,
    error_out: *mut *mut ArtiRpcError,
) -> ArtiRpcStatus {
    ffi_body_with_err! {
        {
            let rpc_conn: Option<&ArtiRpcConn> [in_ptr_opt];
            let on_object: Option<&str> [in_str_opt];
            let hostname: Option<&str> [in_str_opt];
            let isolation: Option<&str> [in_str_opt];
            let socket_out: Option<OutSocketOwned<'_>> [out_socket_owned_opt];
            let stream_id_out: Option<OutBoxedPtr<ArtiRpcStr>> [out_ptr_opt];
            err error_out: Option<OutBoxedPtr<ArtiRpcError>>;
        } in {
            let rpc_conn = rpc_conn.ok_or(InvalidInput::NullPointer)?;
            let hostname = hostname.ok_or(InvalidInput::NullPointer)?;
            let socket_out = socket_out.ok_or(InvalidInput::NullPointer)?;
            let isolation = isolation.ok_or(InvalidInput::NullPointer)?;
            let port: u16 = port.try_into().map_err(|_| InvalidInput::BadPort)?;
            if port == 0 {
                return Err(InvalidInput::BadPort.into());
            }
            let on_object = on_object.map(|o| ObjectId::try_from(o.to_owned()))
                .transpose()
                .expect("C string somehow contained NUL.");
            let stream = match stream_id_out {
                Some(stream_id_out) => {
                    let (stream_id, stream) = rpc_conn.open_stream_as_object(
                        on_object.as_ref(),
                        (hostname, port),
                        isolation)?;
                    stream_id_out.write_value_boxed(stream_id.into());
                    stream
                }
                None => {
                    rpc_conn.open_stream(on_object.as_ref(), (hostname, port), isolation)?
                }
            };
            // We call this last so that the stream will definitely be converted to an fd, or
            // dropped.
            socket_out.write_socket(stream);
        }
    }
}