rust-rcs-core 0.3.1

Core libraries that provide basic RCS capabilities (SIP, MSRP, etc.)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// Copyright 2023 宋昊文
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[cfg(all(feature = "android", target_os = "android"))]
use std::ffi::{CStr, CString};
use std::{io, ptr::NonNull};

use libc::c_void;
#[cfg(all(feature = "android", target_os = "android"))]
use libc::{c_char, size_t};

use crate::ffi::{log::platform_log, r#async::WakerHandle};

const LOG_TAG: &str = "ffi";

#[cfg(all(feature = "android", target_os = "android"))]
extern "C" {
    fn platform_create_socket() -> *mut SocketCHandle;
    fn platform_socket_bind(
        c_handle: *mut SocketCHandle,
        local_ip: *const c_char,
        local_port: u16,
    ) -> i32;
    fn platform_socket_configure_tls(c_handle: *mut SocketCHandle, host_name: *const c_char)
        -> i32;
    fn platform_socket_connect(
        c_handle: *mut SocketCHandle,
        remote_ip: *const c_char,
        remote_port: u16,
    ) -> i32;
    fn platform_socket_finish_connect(
        c_handle: *mut SocketCHandle,
        waker_handle: *mut c_void,
    ) -> i32; // returns 0 for success, 114 (EALREADY) for pending status
    fn platform_socket_start_handshake(c_handle: *mut SocketCHandle) -> i32;
    fn platform_socket_finish_handshake(
        c_handle: *mut SocketCHandle,
        waker_handle: *mut c_void,
    ) -> i32; // returns 0 for success, 114 (EALREADY) for pending status
    fn platform_read_socket(
        c_handle: *mut SocketCHandle,
        waker_handle: *mut c_void,
        buffer: *mut u8,
        buffer_len: size_t,
        bytes_read: *mut size_t,
    ) -> i32; // returns 0 for success, 11 (EAGAIN/EWOULDBLOCK) for pending status
    fn platform_write_socket(
        c_handle: *mut SocketCHandle,
        waker_handle: *mut c_void,
        buffer: *const u8,
        buffer_len: size_t,
        bytes_written: *mut size_t,
    ) -> i32; // returns 0 for success, 11 (EAGAIN/EWOULDBLOCK) for pending status
    fn platform_shutdown_socket(c_handle: *mut SocketCHandle, waker_handle: *mut c_void) -> i32; // returns 0 for success, 114 (EALREADY) for pending status
    fn platform_close_socket(c_handle: *mut SocketCHandle);
    fn platform_free_socket(c_handle: *mut SocketCHandle);
}

#[repr(C)]
pub struct SocketCHandle {
    _data: [u8; 0],
    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

pub struct SocketCHandleWrapper(NonNull<SocketCHandle>);

impl Drop for SocketCHandleWrapper {
    fn drop(&mut self) {
        #[cfg(all(feature = "android", target_os = "android"))]
        let c_handle = self.0.as_ptr();
        #[cfg(all(feature = "android", target_os = "android"))]
        unsafe {
            platform_free_socket(c_handle);
        }
    }
}

unsafe impl Send for SocketCHandleWrapper {}

pub fn create_socket() -> io::Result<SocketCHandleWrapper> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        unsafe {
            if let Some(c_handle) = platform_create_socket().as_mut() {
                return Ok(SocketCHandleWrapper(NonNull::new(c_handle).unwrap()));
            }
        }
    }

    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn socket_bind(
    c_socket: &SocketCHandleWrapper,
    local_ip: &str,
    local_port: u16,
) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let local_ip = CString::new(local_ip).unwrap();
        let local_ip = local_ip.as_ptr();
        unsafe {
            let r = platform_socket_bind(c_socket, local_ip, local_port);
            platform_log(LOG_TAG, format!("platform_socket_bind returns {}", r));
            if r == 0 {
                return Ok(());
            } else if r == libc::EAGAIN || r == libc::EWOULDBLOCK {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn socket_configure_tls(c_socket: &SocketCHandleWrapper, host_name: &str) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let host_name = CString::new(host_name).unwrap();
        let host_name = host_name.as_ptr();
        unsafe {
            let r = platform_socket_configure_tls(c_socket, host_name);
            platform_log(LOG_TAG, format!("socket_configure_tls returns {}", r));
            if r == 0 {
                return Ok(());
            } else if r == libc::EAGAIN || r == libc::EWOULDBLOCK {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn socket_connect(
    c_socket: &SocketCHandleWrapper,
    remote_ip: &str,
    remote_port: u16,
) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let remote_ip = CString::new(remote_ip).unwrap();
        let remote_ip = remote_ip.as_ptr();
        unsafe {
            let r = platform_socket_connect(c_socket, remote_ip, remote_port);
            platform_log(LOG_TAG, format!("platform_socket_connect returns {}", r));
            if r == 0 {
                return Ok(());
            } else if r == libc::EAGAIN || r == libc::EWOULDBLOCK {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn socket_finish_connect(
    c_socket: &SocketCHandleWrapper,
    waker: WakerHandle,
) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let waker = Box::new(waker);
        let waker = Box::into_raw(waker);
        let waker = waker as *mut c_void;
        unsafe {
            let r = platform_socket_finish_connect(c_socket, waker);
            platform_log(
                LOG_TAG,
                format!("platform_socket_finish_connect returns {}", r),
            );
            if r == 0 {
                return Ok(());
            } else if r == libc::EALREADY {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn socket_start_handshake(c_socket: &SocketCHandleWrapper) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        unsafe {
            let r = platform_socket_start_handshake(c_socket);
            platform_log(
                LOG_TAG,
                format!("platform_socket_start_handshake returns {}", r),
            );
            if r == 0 {
                return Ok(());
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn socket_finish_handshake(
    c_socket: &SocketCHandleWrapper,
    waker: WakerHandle,
) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let waker = Box::new(waker);
        let waker = Box::into_raw(waker);
        let waker = waker as *mut c_void;
        unsafe {
            let r = platform_socket_finish_handshake(c_socket, waker);
            platform_log(
                LOG_TAG,
                format!("platform_socket_finish_handshake returns {}", r),
            );
            if r == 0 {
                return Ok(());
            } else if r == libc::EALREADY {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn read_socket(
    c_socket: &SocketCHandleWrapper,
    buffer: &mut [u8],
    waker: WakerHandle,
) -> io::Result<usize> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let buffer_len = buffer.len();
        let buffer = buffer.as_mut_ptr();
        let waker = Box::new(waker);
        let waker = Box::into_raw(waker);
        let waker = waker as *mut c_void;
        unsafe {
            let mut bytes_read = 0;
            let r = platform_read_socket(c_socket, waker, buffer, buffer_len, &mut bytes_read);
            platform_log(
                LOG_TAG,
                format!(
                    "platform_read_socket returns {} with {} bytes read",
                    r, bytes_read
                ),
            );
            if r == 0 {
                return Ok(bytes_read);
            } else if r == libc::EAGAIN || r == libc::EWOULDBLOCK {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn write_socket(
    c_socket: &SocketCHandleWrapper,
    buffer: &[u8],
    waker: WakerHandle,
) -> io::Result<usize> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let buffer_len = buffer.len();
        let buffer = buffer.as_ptr();
        let waker = Box::new(waker);
        let waker = Box::into_raw(waker);
        let waker = waker as *mut c_void;
        unsafe {
            let mut bytes_written = 0;
            let r = platform_write_socket(c_socket, waker, buffer, buffer_len, &mut bytes_written);
            platform_log(
                LOG_TAG,
                format!(
                    "platform_write_socket returns {} with {} bytes written",
                    r, bytes_written
                ),
            );
            if r == 0 {
                return Ok(bytes_written);
            } else if r == libc::EAGAIN || r == libc::EWOULDBLOCK {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn shutdown_socket(c_socket: &SocketCHandleWrapper, waker: WakerHandle) -> io::Result<()> {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        let waker = Box::new(waker);
        let waker = Box::into_raw(waker);
        let waker = waker as *mut c_void;
        unsafe {
            let r = platform_shutdown_socket(c_socket, waker);
            platform_log(LOG_TAG, format!("platform_shutdown_socket returns {}", r));
            if r == 0 {
                return Ok(());
            } else if r == libc::EALREADY {
                return Err(io::Error::from(io::ErrorKind::WouldBlock));
            } else {
                return Err(io::Error::from(io::ErrorKind::Other));
            }
        }
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    Err(io::Error::from(io::ErrorKind::Unsupported))
}

pub fn close_socket(c_socket: &SocketCHandleWrapper) {
    #[cfg(all(feature = "android", target_os = "android"))]
    {
        let c_socket = c_socket.0.as_ptr();
        unsafe {
            platform_close_socket(c_socket);
        }
    }
}

#[cfg(all(feature = "android", target_os = "android"))]
extern "C" {
    fn platform_get_socket_info(socket_c_handle: *mut SocketCHandle) -> *mut SocketInfoCHandle;
    fn platform_get_socket_af(c_handle: *mut SocketInfoCHandle) -> i32;
    fn platform_get_socket_l_addr(c_handle: *mut SocketInfoCHandle) -> *const c_char;
    fn platform_get_socket_l_port(c_handle: *mut SocketInfoCHandle) -> u16;
    fn platform_free_socket_info(c_handle: *mut SocketInfoCHandle);
}

#[repr(C)]
pub struct SocketInfoCHandle {
    _data: [u8; 0],
    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

pub struct SocketInfoCHandleWrapper(NonNull<SocketInfoCHandle>);

impl Drop for SocketInfoCHandleWrapper {
    fn drop(&mut self) {
        #[cfg(all(feature = "android", target_os = "android"))]
        let c_handle = self.0.as_ptr();
        #[cfg(all(feature = "android", target_os = "android"))]
        unsafe {
            platform_free_socket_info(c_handle);
        }
    }
}

unsafe impl Send for SocketInfoCHandleWrapper {}

pub fn get_socket_info(android_socket: &SocketCHandleWrapper) -> Option<SocketInfoCHandleWrapper> {
    #[cfg(all(feature = "android", target_os = "android"))]
    let android_socket = android_socket.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        if let Some(c_handle) = platform_get_socket_info(android_socket).as_mut() {
            return Some(SocketInfoCHandleWrapper(NonNull::new(c_handle).unwrap()));
        }
    }

    None
}

pub fn get_socket_af(android_socket_info: &SocketInfoCHandleWrapper) -> i32 {
    #[cfg(all(feature = "android", target_os = "android"))]
    let android_socket_info = android_socket_info.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        return platform_get_socket_af(android_socket_info);
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    0
}

pub fn get_socket_local_address(android_socket_info: &SocketInfoCHandleWrapper) -> Option<String> {
    #[cfg(all(feature = "android", target_os = "android"))]
    let android_socket_info = android_socket_info.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        if let Some(ptr) = platform_get_socket_l_addr(android_socket_info).as_ref() {
            let str = CStr::from_ptr(ptr).to_string_lossy().into_owned();
            return Some(str);
        }
    }

    None
}

pub fn get_socket_local_port(android_socket_info: &SocketInfoCHandleWrapper) -> u16 {
    #[cfg(all(feature = "android", target_os = "android"))]
    let android_socket_info = android_socket_info.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        return platform_get_socket_l_port(android_socket_info);
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    0
}

#[cfg(all(feature = "android", target_os = "android"))]
extern "C" {
    fn platform_get_socket_session_cipher_suite(
        socket_c_handle: *mut SocketCHandle,
    ) -> *mut CipherSuiteCHandle;
    fn platform_cipher_suite_get_yy(c_handle: *mut CipherSuiteCHandle) -> u8;
    fn platform_cipher_suite_get_zz(c_handle: *mut CipherSuiteCHandle) -> u8;
    fn platform_free_cipher_suite(c_handle: *mut CipherSuiteCHandle);
}

#[repr(C)]
pub struct CipherSuiteCHandle {
    _data: [u8; 0],
    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

pub struct CipherSuiteCHandleWrapper(NonNull<CipherSuiteCHandle>);

impl Drop for CipherSuiteCHandleWrapper {
    fn drop(&mut self) {
        #[cfg(all(feature = "android", target_os = "android"))]
        let c_handle = self.0.as_ptr();
        #[cfg(all(feature = "android", target_os = "android"))]
        unsafe {
            platform_free_cipher_suite(c_handle);
        }
    }
}

unsafe impl Send for CipherSuiteCHandleWrapper {}

pub fn get_socket_session_cipher_suite(
    android_socket: &SocketCHandleWrapper,
) -> Option<CipherSuiteCHandleWrapper> {
    #[cfg(all(feature = "android", target_os = "android"))]
    let android_socket = android_socket.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        if let Some(c_handle) = platform_get_socket_session_cipher_suite(android_socket).as_mut() {
            return Some(CipherSuiteCHandleWrapper(NonNull::new(c_handle).unwrap()));
        }
    }

    None
}

pub fn cipher_suite_get_yy(c_cipher_suite: &CipherSuiteCHandleWrapper) -> u8 {
    #[cfg(all(feature = "android", target_os = "android"))]
    let c_cipher_suite = c_cipher_suite.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        return platform_cipher_suite_get_yy(c_cipher_suite);
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    0
}

pub fn cipher_suite_get_zz(c_cipher_suite: &CipherSuiteCHandleWrapper) -> u8 {
    #[cfg(all(feature = "android", target_os = "android"))]
    let c_cipher_suite = c_cipher_suite.0.as_ptr();
    #[cfg(all(feature = "android", target_os = "android"))]
    unsafe {
        return platform_cipher_suite_get_zz(c_cipher_suite);
    }

    #[cfg(not(all(feature = "android", target_os = "android")))]
    0
}