gcdevproxy 0.1.0

GoodCam Device Proxy library
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
use std::{
    borrow::Cow,
    ffi::c_void,
    net::{IpAddr, SocketAddr},
    os::raw::{c_char, c_int},
    ptr,
    sync::Mutex,
    time::Duration,
};

use async_trait::async_trait;
use futures::{
    channel::oneshot::{self, Sender},
    future::Either,
};
use hyper::{Body, Request, Response};
use libc::{EINVAL, EIO};
use tokio::{
    runtime::{self, Runtime},
    task::JoinHandle,
};

use crate::{
    auth::BasicAuthorization, exports::RawContextWrapper, ClientHandlerResult, DeviceHandlerResult,
    Error, ProxyBuilder, ProxyHandle, RequestHandler,
};

/// Foreign callback for asynchronous proxy construction.
type NewProxyCallback = unsafe extern "C" fn(context: *mut c_void, proxy: *mut RawProxyHandle);

/// Foreign callback for joining the proxy runtime.
type ProxyJoinCallback = unsafe extern "C" fn(context: *mut c_void, res: c_int);

/// Foreign device request handler.
type RawDeviceHandlerFn = unsafe extern "C" fn(
    context: *mut c_void,
    authorization: *const BasicAuthorization,
    result: *mut Sender<Result<DeviceHandlerResult, Error>>,
);

/// Foreign client request handler.
type RawClientHandlerFn = unsafe extern "C" fn(
    context: *mut c_void,
    request: *mut Request<Body>,
    result: *mut Sender<Result<ClientHandlerResult, Error>>,
);

/// TLS mode.
enum TlsMode {
    None,
    LetsEncrypt,
    Simple(Vec<u8>, Vec<u8>),
}

/// Foreign request handler.
#[derive(Copy, Clone)]
struct RawRequestHandler {
    handle_device: RawDeviceHandlerFn,
    handle_client: RawClientHandlerFn,
    device_context: *mut c_void,
    client_context: *mut c_void,
}

impl RawRequestHandler {
    /// Create a new request handler.
    fn new() -> Self {
        Self {
            handle_device: dummy_device_request_handler,
            handle_client: dummy_client_request_handler,
            device_context: ptr::null_mut(),
            client_context: ptr::null_mut(),
        }
    }
}

#[async_trait]
impl RequestHandler for RawRequestHandler {
    async fn handle_device_request(
        &self,
        authorization: BasicAuthorization,
    ) -> Result<DeviceHandlerResult, Error> {
        let (tx, rx) = oneshot::channel();

        let this = *self;

        tokio::task::spawn_blocking(move || {
            // we need to capture the whole request handler
            let this = this;

            let tx = Box::into_raw(Box::new(tx));

            unsafe { (this.handle_device)(this.device_context, &authorization, tx) }
        });

        rx.await
            .map_err(|_| Error::from_static_msg("device handler failure"))?
    }

    async fn handle_client_request(
        &self,
        request: Request<Body>,
    ) -> Result<ClientHandlerResult, Error> {
        let (tx, rx) = oneshot::channel();

        let this = *self;

        tokio::task::spawn_blocking(move || {
            // we need to capture the whole request handler
            let this = this;

            let request = Box::into_raw(Box::new(request));

            let tx = Box::into_raw(Box::new(tx));

            unsafe { (this.handle_client)(this.client_context, request, tx) }
        });

        rx.await
            .map_err(|_| Error::from_static_msg("client handler failure"))?
    }
}

unsafe impl Send for RawRequestHandler {}
unsafe impl Sync for RawRequestHandler {}

/// Default device request handler that will reject all incoming connections.
unsafe extern "C" fn dummy_device_request_handler(
    _: *mut c_void,
    _: *const BasicAuthorization,
    tx: *mut Sender<Result<DeviceHandlerResult, Error>>,
) {
    let tx = Box::from_raw(tx);

    let _ = tx.send(Ok(DeviceHandlerResult::Unauthorized));
}

/// Default client request handler that will block all incoming requests.
unsafe extern "C" fn dummy_client_request_handler(
    _: *mut c_void,
    request: *mut Request<Body>,
    tx: *mut Sender<Result<ClientHandlerResult, Error>>,
) {
    Box::from_raw(request);

    let tx = Box::from_raw(tx);

    let response = Response::builder().status(501).body(Body::empty()).unwrap();

    let _ = tx.send(Ok(ClientHandlerResult::block(response)));
}

/// Proxy configuration.
struct ProxyConfig {
    handler: RawRequestHandler,
    hostname: String,
    http_bind_addresses: Vec<SocketAddr>,
    https_bind_addresses: Vec<SocketAddr>,
    tls_mode: TlsMode,
}

impl ProxyConfig {
    /// Create a new proxy configuration.
    fn new() -> Self {
        Self {
            handler: RawRequestHandler::new(),
            hostname: String::from("localhost"),
            http_bind_addresses: Vec::new(),
            https_bind_addresses: Vec::new(),
            tls_mode: TlsMode::None,
        }
    }

    /// Create and populate a proxy builder.
    fn to_builder(&self) -> Result<ProxyBuilder, Error> {
        let mut builder = ProxyBuilder::new();

        builder.hostname(&self.hostname);

        for addr in &self.http_bind_addresses {
            builder.http_bind_address(*addr);
        }

        for addr in &self.https_bind_addresses {
            builder.https_bind_address(*addr);
        }

        match &self.tls_mode {
            TlsMode::None => (),
            TlsMode::LetsEncrypt => {
                builder.lets_encrypt();
            }
            TlsMode::Simple(key, cert) => {
                builder.tls_identity(key, cert)?;
            }
        }

        Ok(builder)
    }
}

/// Proxy context.
struct RawProxyContext {
    runtime: Runtime,
    handle: ProxyHandle,
    task: Option<JoinHandle<Result<(), Error>>>,
}

impl RawProxyContext {
    /// Start a new proxy asynchronously and call a given callback when the
    /// proxy has started.
    fn start<T, F>(builder: ProxyBuilder, request_handler: T, cb: F)
    where
        T: RequestHandler + Send + Sync + 'static,
        F: FnOnce(Result<RawProxyContext, Error>) + Send + 'static,
    {
        let res = runtime::Builder::new_multi_thread()
            .enable_io()
            .enable_time()
            .build();

        let runtime = match res {
            Ok(r) => r,
            Err(err) => return cb(Err(err.into())),
        };

        runtime.handle().clone().spawn(async move {
            let proxy = match builder.build(request_handler).await {
                Ok(p) => p,
                Err(err) => return cb(Err(err)),
            };

            let handle = proxy.handle();

            let task = tokio::spawn(proxy);

            let res = Self {
                runtime,
                handle,
                task: Some(task),
            };

            cb(Ok(res));
        });
    }

    /// Stop the proxy asynchronously.
    fn stop(&mut self, timeout: Duration) {
        if let Some(task) = self.task.take() {
            let handle = self.handle.clone();

            let task = self.runtime.spawn(async move {
                handle.stop();

                let delay = tokio::time::sleep(timeout);

                futures::pin_mut!(delay);
                futures::pin_mut!(task);

                let select = futures::future::select(delay, task);

                match select.await {
                    Either::Left((_, task)) => {
                        // abort the task
                        handle.abort();

                        // and wait until it stops
                        let _ = task.await;

                        Err(Error::from_static_msg("timeout"))
                    }
                    Either::Right((res, _)) => match res {
                        Ok(res) => res.map_err(Error::from),
                        Err(_) => Ok(()),
                    },
                }
            });

            self.task = Some(task);
        }
    }

    /// Abort the proxy.
    fn abort(&self) {
        self.handle.abort();
    }

    /// Join the proxy runtime asynchronously.
    fn join<F>(&mut self, cb: F)
    where
        F: FnOnce(Result<(), Error>) + Send + 'static,
    {
        if let Some(task) = self.task.take() {
            let task = self.runtime.spawn(async move {
                let res = match task.await {
                    Ok(res) => res,
                    Err(_) => Ok(()),
                };

                cb(res);

                Ok(())
            });

            self.task = Some(task);
        } else {
            cb(Ok(()));
        }
    }
}

impl Drop for RawProxyContext {
    fn drop(&mut self) {
        self.handle.abort();
    }
}

/// Proxy handle.
struct RawProxyHandle {
    context: Mutex<RawProxyContext>,
}

impl RawProxyHandle {
    /// Start the proxy.
    ///
    /// This method will block the thread until the proxy is initialized.
    fn start<T>(builder: ProxyBuilder, request_handler: T) -> Result<Self, Error>
    where
        T: RequestHandler + Send + Sync + 'static,
    {
        let (tx, rx) = std::sync::mpsc::channel();

        Self::start_async(builder, request_handler, move |res| {
            let _ = tx.send(res);
        });

        rx.recv().unwrap()
    }

    /// Start the proxy.
    ///
    /// This method will return immediately and call a given callback when the
    /// proxy is ready.
    fn start_async<T, F>(builder: ProxyBuilder, request_handler: T, cb: F)
    where
        T: RequestHandler + Send + Sync + 'static,
        F: FnOnce(Result<RawProxyHandle, Error>) + Send + 'static,
    {
        RawProxyContext::start(builder, request_handler, move |res| match res {
            Ok(ctx) => {
                let res = Self {
                    context: Mutex::new(ctx),
                };

                cb(Ok(res));
            }
            Err(err) => cb(Err(err)),
        })
    }

    /// Stop the proxy asynchronously.
    fn stop(&self, timeout: Duration) {
        self.context.lock().unwrap().stop(timeout);
    }

    /// Abort the proxy.
    fn abort(&self) {
        self.context.lock().unwrap().abort();
    }

    /// Block the current thread until the proxy has stopped.
    fn join(&self) -> Result<(), Error> {
        let (tx, rx) = std::sync::mpsc::channel();

        self.context.lock().unwrap().join(move |res| {
            let _ = tx.send(res);
        });

        match rx.recv() {
            Ok(res) => res,
            Err(_) => Ok(()),
        }
    }

    /// Call a given callback when the proxy has stopped.
    fn join_async<F>(&self, cb: F)
    where
        F: FnOnce(Result<(), Error>) + Send + 'static,
    {
        self.context.lock().unwrap().join(cb);
    }
}

/// Create a new proxy configuration.
#[no_mangle]
extern "C" fn gcdp__proxy_config__new() -> *mut ProxyConfig {
    Box::into_raw(Box::new(ProxyConfig::new()))
}

/// Set proxy hostname.
#[no_mangle]
unsafe extern "C" fn gcdp__proxy_config__set_hostname(
    config: *mut ProxyConfig,
    hostname: *const c_char,
) -> c_int {
    let config = &mut *config;

    if let Some(hostname) = try_result!(EINVAL, super::cstr_to_str(hostname)) {
        config.hostname = hostname.to_string();
    } else {
        throw!(EINVAL, "hostname cannot be null");
    }

    0
}

/// Add HTTP binding.
///
/// The addr should be a C-string representing an IPv4/IPv6 address.
#[no_mangle]
unsafe extern "C" fn gcdp__proxy_config__add_http_bind_addr(
    config: *mut ProxyConfig,
    addr: *const c_char,
    port: u16,
) -> c_int {
    let config = &mut *config;

    config
        .http_bind_addresses
        .push(try_result!(EINVAL, raw_addr_to_socket_addr(addr, port)));

    0
}

/// Add HTTPS binding.
///
/// The addr should be a C-string representing an IPv4/IPv6 address.
#[no_mangle]
unsafe extern "C" fn gcdp__proxy_config__add_https_bind_addr(
    config: *mut ProxyConfig,
    addr: *const c_char,
    port: u16,
) -> c_int {
    let config = &mut *config;

    config
        .https_bind_addresses
        .push(try_result!(EINVAL, raw_addr_to_socket_addr(addr, port)));

    0
}

/// Use Let's encrypt to generate a TLS key and a certificate.
#[no_mangle]
extern "C" fn gcdp__proxy_config__use_lets_encrypt(config: *mut ProxyConfig) {
    let config = unsafe { &mut *config };

    config.tls_mode = TlsMode::LetsEncrypt;
}

/// Use a given TLS identity.
///
/// The key and certificate chain must be in PEM format.
#[no_mangle]
unsafe extern "C" fn gcdp__proxy_config__set_tls_identity(
    config: *mut ProxyConfig,
    key: *const u8,
    key_size: usize,
    cert: *const u8,
    cert_size: usize,
) {
    let config = &mut *config;

    let key = std::slice::from_raw_parts(key, key_size);
    let cert = std::slice::from_raw_parts(cert, cert_size);

    config.tls_mode = TlsMode::Simple(key.to_vec(), cert.to_vec());
}

/// Use a given device request handler.
///
/// The handler and the context must be thread-safe and they must remain valid
/// for the whole lifetime of the proxy.
#[no_mangle]
extern "C" fn gcdp__proxy_config__set_device_handler(
    config: *mut ProxyConfig,
    handler: RawDeviceHandlerFn,
    context: *mut c_void,
) {
    let config = unsafe { &mut *config };

    config.handler.device_context = context;
    config.handler.handle_device = handler;
}

/// Use a given client request handler.
///
/// The handler and the context must be thread-safe and they must remain valid
/// for the whole lifetime of the proxy.
#[no_mangle]
extern "C" fn gcdp__proxy_config__set_client_handler(
    config: *mut ProxyConfig,
    handler: RawClientHandlerFn,
    context: *mut c_void,
) {
    let config = unsafe { &mut *config };

    config.handler.client_context = context;
    config.handler.handle_client = handler;
}

/// Free the configuration.
#[no_mangle]
extern "C" fn gcdp__proxy_config__free(config: *mut ProxyConfig) {
    unsafe { super::free(config) }
}

/// Create a new proxy form a given configuration.
///
/// The function will block the current thread until the proxy is available.
#[no_mangle]
extern "C" fn gcdp__proxy__new(config: *const ProxyConfig) -> *mut RawProxyHandle {
    let config = unsafe { &*config };

    let builder = try_result!(EINVAL, ptr::null_mut(), config.to_builder());

    let handle = try_result!(
        EIO,
        ptr::null_mut(),
        RawProxyHandle::start(builder, config.handler)
    );

    Box::into_raw(Box::new(handle))
}

/// Create a new proxy from a given configuration.
///
/// The function will return immediately and notify a given callback once the
/// proxy is available.
#[no_mangle]
extern "C" fn gcdp__proxy__new_async(
    config: *const ProxyConfig,
    cb: NewProxyCallback,
    context: *mut c_void,
) {
    let config = unsafe { &*config };

    let context = RawContextWrapper(context);

    let cb = move |proxy| unsafe { cb(context.unwrap(), proxy) };

    let builder = match config.to_builder() {
        Ok(b) => b,
        Err(err) => {
            // set the error
            super::set_last_error(EIO, Cow::Owned(err.to_string()));

            // and return NULL
            return cb(ptr::null_mut());
        }
    };

    RawProxyHandle::start_async(builder, config.handler, move |res| match res {
        Ok(handle) => cb(Box::into_raw(Box::new(handle))),
        Err(err) => {
            // set the error
            super::set_last_error(EIO, Cow::Owned(err.to_string()));

            // and return NULL
            cb(ptr::null_mut());
        }
    });
}

/// Stop the proxy.
///
/// This function is asynchronous.
#[no_mangle]
extern "C" fn gcdp__proxy__stop(proxy: *mut RawProxyHandle, timeout: u32) {
    let handle = unsafe { &*proxy };

    handle.stop(Duration::from_millis(timeout as u64));
}

/// Abort the proxy.
///
/// This function is asynchronous.
#[no_mangle]
extern "C" fn gcdp__proxy__abort(proxy: *mut RawProxyHandle) {
    let handle = unsafe { &*proxy };

    handle.abort();
}

/// Block the current thread until the proxy has stopped.
#[no_mangle]
unsafe extern "C" fn gcdp__proxy__join(proxy: *mut RawProxyHandle) -> c_int {
    let handle = &*proxy;

    try_result!(EIO, handle.join());

    0
}

/// Notify a given callback when the proxy stops.
#[no_mangle]
unsafe extern "C" fn gcdp__proxy__join_async(
    proxy: *mut RawProxyHandle,
    cb: ProxyJoinCallback,
    context: *mut c_void,
) {
    let handle = &*proxy;

    let context = RawContextWrapper(context);

    handle.join_async(move |res| match res {
        Ok(()) => cb(context.unwrap(), 0),
        Err(err) => {
            // set the error
            super::set_last_error(EIO, Cow::Owned(err.to_string()));

            // and return the error code
            cb(context.unwrap(), EIO);
        }
    });
}

/// Free the proxy.
#[no_mangle]
extern "C" fn gcdp__proxy__free(proxy: *mut RawProxyHandle) {
    unsafe { super::free(proxy) }
}

/// Set the device handler result to "accept" indicating that the proxy should
/// accept the device connection.
///
/// The function takes ownership of the sender.
#[no_mangle]
extern "C" fn gcdp__device_handler_result__accept(
    tx: *mut Sender<Result<DeviceHandlerResult, Error>>,
) {
    let tx = unsafe { Box::from_raw(tx) };

    let _ = tx.send(Ok(DeviceHandlerResult::Accept));
}

/// Set the device handler result to "unauthorized" indicating that the proxy
/// should reject the device connection.
///
/// The function takes ownership of the sender.
#[no_mangle]
extern "C" fn gcdp__device_handler_result__unauthorized(
    tx: *mut Sender<Result<DeviceHandlerResult, Error>>,
) {
    let tx = unsafe { Box::from_raw(tx) };

    let _ = tx.send(Ok(DeviceHandlerResult::Unauthorized));
}

/// Set the device handler result to "redirect" indicating that the proxy
/// should redirect the device to a given location.
///
/// The function takes ownership of the sender.
#[no_mangle]
unsafe extern "C" fn gcdp__device_handler_result__redirect(
    tx: *mut Sender<Result<DeviceHandlerResult, Error>>,
    location: *const c_char,
) -> c_int {
    let location = if let Some(location) = try_result!(EINVAL, super::cstr_to_str(location)) {
        location
    } else {
        throw!(EINVAL, "location cannot be null");
    };

    let tx = Box::from_raw(tx);

    let _ = tx.send(Ok(DeviceHandlerResult::redirect(location)));

    0
}

/// Set the device handler result to "error" indicating that the handler is not
/// able to handle the request.
///
/// The function takes ownership of the sender.
#[no_mangle]
unsafe extern "C" fn gcdp__device_handler_result__error(
    tx: *mut Sender<Result<DeviceHandlerResult, Error>>,
    error: *const c_char,
) -> c_int {
    let error = try_result!(EINVAL, super::cstr_to_error(error));

    let tx = Box::from_raw(tx);

    let _ = tx.send(Err(error));

    0
}

/// Set the client handler result to "forward" indicating that the proxy should
/// forward the client request to device with a given ID.
///
/// The function takes ownership of the request and the sender.
#[no_mangle]
unsafe extern "C" fn gcdp__client_handler_result__forward(
    tx: *mut Sender<Result<ClientHandlerResult, Error>>,
    device_id: *const c_char,
    request: *mut Request<Body>,
) -> c_int {
    if request.is_null() {
        throw!(EINVAL, "request cannot be null");
    }

    let device_id = if let Some(device_id) = try_result!(EINVAL, super::cstr_to_str(device_id)) {
        device_id
    } else {
        throw!(EINVAL, "device ID cannot be null");
    };

    let request = Box::from_raw(request);

    let tx = Box::from_raw(tx);

    let _ = tx.send(Ok(ClientHandlerResult::forward(device_id, *request)));

    0
}

/// Set the client handler result to "block" indicating that the proxy should
/// block the client request and return a given response instead.
///
/// The function takes ownership of the response and the sender.
#[no_mangle]
unsafe extern "C" fn gcdp__client_handler_result__block(
    tx: *mut Sender<Result<ClientHandlerResult, Error>>,
    response: *mut Response<Body>,
) -> c_int {
    if response.is_null() {
        throw!(EINVAL, "response cannot be null");
    }

    let response = Box::from_raw(response);

    let tx = Box::from_raw(tx);

    let _ = tx.send(Ok(ClientHandlerResult::block(*response)));

    0
}

/// Set the client handler result to "error" indicating that the handler is not
/// able to handle the request.
///
/// The function takes ownership of the sender.
#[no_mangle]
unsafe extern "C" fn gcdp__client_handler_result__error(
    tx: *mut Sender<Result<ClientHandlerResult, Error>>,
    error: *const c_char,
) -> c_int {
    let error = try_result!(EINVAL, super::cstr_to_error(error));

    let tx = Box::from_raw(tx);

    let _ = tx.send(Err(error));

    0
}

/// Get device ID from a given authorization object.
///
/// The device ID will be copied into a given buffer (unless it is NULL).
/// The size parameter is expected to contain the buffer capacity and after the
/// function returns, it will contain the original length of the device ID.
/// The size cannot be NULL.
///
/// The string copied into the buffer may be truncated but it will be always
/// null-terminated.
#[no_mangle]
unsafe extern "C" fn gcdp__authorization__get_device_id(
    authorization: *const BasicAuthorization,
    buffer: *mut c_char,
    size: *mut usize,
) {
    let authorization = &*authorization;

    *size = super::str_to_cstr(authorization.username(), buffer, *size);
}

/// Get device key from a given authorization object.
///
/// The device key will be copied into a given buffer (unless it is NULL).
/// The size parameter is expected to contain the buffer capacity and after the
/// function returns, it will contain the original length of the device key.
/// The size cannot be NULL.
///
/// The string copied into the buffer may be truncated but it will be always
/// null-terminated.
#[no_mangle]
unsafe extern "C" fn gcdp__authorization__get_device_key(
    authorization: *const BasicAuthorization,
    buffer: *mut c_char,
    size: *mut usize,
) {
    let authorization = &*authorization;

    *size = super::str_to_cstr(authorization.password(), buffer, *size);
}

/// Helper function for constructing a socket address from a given C-string and
/// port.
unsafe fn raw_addr_to_socket_addr(addr: *const c_char, port: u16) -> Result<SocketAddr, Error> {
    let addr: IpAddr = super::cstr_to_str(addr)
        .transpose()
        .ok_or_else(|| Error::from_static_msg("address cannot be null"))?
        .ok()
        .map(|addr| addr.parse())
        .and_then(|res| res.ok())
        .ok_or_else(|| Error::from_static_msg("invalid address"))?;

    Ok(SocketAddr::from((addr, port)))
}