1
// SPDX-License-Identifier: BSD-2-Clause
2
/*
3
 * transport/mod.rs - Module file for CoAP transports.
4
 * This file is part of the libcoap-rs crate, see the README and LICENSE files for
5
 * more information and terms of use.
6
 * Copyright © 2021-2023 The NAMIB Project Developers, all rights reserved.
7
 * See the README as well as the LICENSE file for more information.
8
 */
9

            
10
use std::{net::SocketAddr, os::raw::c_uint};
11

            
12
use libcoap_sys::{
13
    coap_endpoint_set_default_mtu, coap_endpoint_t, coap_free_endpoint, coap_new_endpoint, coap_proto_t,
14
};
15

            
16
use crate::{error::EndpointCreationError, types::CoapAddress, CoapContext};
17

            
18
pub type EndpointMtu = c_uint;
19

            
20
#[derive(Debug)]
21
pub struct CoapEndpoint {
22
    raw_endpoint: *mut coap_endpoint_t,
23
}
24

            
25
/// Trait for functions common between all types of endpoints.
26
impl CoapEndpoint {
27
    /// Sets the default MTU value of the endpoint.
28
    pub fn set_default_mtu(&mut self, mtu: EndpointMtu) {
29
        // SAFETY: as_mut_raw_endpoint cannot fail and will always return a valid reference.
30
        // Modifying the state of the endpoint is also fine, because we have a mutable reference
31
        // of the whole endpoint.
32
        unsafe {
33
            coap_endpoint_set_default_mtu(&mut *self.raw_endpoint, mtu);
34
        }
35
    }
36

            
37
    /// Method utilized by transport protocol specific constructors to actually create the endpoint in libcoap
38
233
    pub(crate) fn new_endpoint(
39
233
        context: &mut CoapContext,
40
233
        addr: SocketAddr,
41
233
        proto: coap_proto_t,
42
233
    ) -> Result<Self, EndpointCreationError> {
43
233
        let endpoint = unsafe {
44
233
            // SAFETY: coap_new_endpoint will return null if it is unable to add new endpoint.
45
233
            // These states are processed further in the code
46
233
            coap_new_endpoint(
47
233
                context.as_mut_raw_context(),
48
233
                CoapAddress::from(addr).as_raw_address(),
49
233
                proto,
50
233
            )
51
233
        };
52
233

            
53
233
        if endpoint.is_null() {
54
            Err(EndpointCreationError::Unknown)
55
        } else {
56
233
            Ok(Self { raw_endpoint: endpoint })
57
        }
58
233
    }
59
}
60

            
61
impl Drop for CoapEndpoint {
62
233
    fn drop(&mut self) {
63
233
        // SAFETY: Raw endpoint is guaranteed to exist for as long as the container exists.
64
233
        unsafe { coap_free_endpoint(self.raw_endpoint) }
65
233
    }
66
}