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
use std::str::FromStr;
use std::time::Duration;
/// Rust Async CoAP Client
// https://github.com/ryankurte/rust-coap-client
// Copyright 2021 ryan kurte <ryan@kurte.nz>
use std::{
    convert::{TryFrom, TryInto},
    marker::PhantomData,
};

use log::{debug, error};
use structopt::StructOpt;
use strum_macros::{Display, EnumString, EnumVariantNames};

pub use coap_lite::RequestType as Method;
use coap_lite::{CoapRequest, MessageType, Packet, ResponseType};

pub mod backend;
pub use backend::Backend;

pub const COAP_MTU: usize = 1600;

/// Client connection options
#[derive(Debug, Clone, PartialEq, StructOpt)]
pub struct ClientOptions {
    #[structopt(long, parse(try_from_str = humantime::parse_duration), default_value = "500ms")]
    /// Client / Connection timeout
    pub connect_timeout: Duration,

    /// CA certificate for TLS/DTLS modes
    #[structopt(long)]
    pub tls_ca: Option<String>,

    /// Client certificate for TLS/DTLS modes with client-auth
    #[structopt(long)]
    pub tls_cert: Option<String>,

    /// Client key for TLS/DTLS modes with client-auth
    #[structopt(long)]
    pub tls_key: Option<String>,

    /// Skip verifying peer certificate
    #[structopt(long)]
    pub tls_skip_verify: bool,
}

impl Default for ClientOptions {
    fn default() -> Self {
        Self {
            connect_timeout: Duration::from_secs(2),
            tls_ca: None,
            tls_cert: None,
            tls_key: None,
            tls_skip_verify: false,
        }
    }
}

/// Request options, for configuring CoAP requests
#[derive(Debug, Clone, PartialEq, StructOpt)]
pub struct RequestOptions {
    #[structopt(long)]
    /// Disable message acknowlegement
    pub non_confirmable: bool,
    #[structopt(long, default_value = "3")]
    /// Number of retries (for acknowleged messages)
    pub retries: usize,
    #[structopt(long, parse(try_from_str = humantime::parse_duration), default_value = "2s")]
    /// Request -> response timeout
    pub timeout: Duration,
    #[structopt(long, parse(try_from_str = humantime::parse_duration), default_value = "500ms")]
    /// Base period for exponential backoff
    pub backoff: Duration,
}

impl Default for RequestOptions {
    fn default() -> Self {
        Self {
            non_confirmable: false,
            retries: 3,
            timeout: Duration::from_secs(2),
            backoff: Duration::from_millis(500),
        }
    }
}

/// Supported transports / schemes
#[derive(Clone, PartialEq, Debug, Display, EnumString, EnumVariantNames)]
pub enum Transport {
    /// Basic UDP transport
    #[strum(serialize = "udp", serialize = "coap")]
    Udp,
    /// Datagram TLS over UDP
    #[strum(serialize = "dtls", serialize = "coaps")]
    Dtls,
    /// Basic TLS transport
    Tcp,
    /// TLS over TCP
    Tls,
}

/// CoAP client errors
// TODO: impl std::error::Error via thiserror
#[derive(Debug, thiserror::Error)]
pub enum Error<T: std::fmt::Debug> {
    #[error("Transport / Backend error: {:?}", 0)]
    Transport(T),
    #[error("Invalid host specification")]
    InvalidHost,
    #[error("Invalid URL")]
    InvalidUrl,
    #[error("Invalid Scheme")]
    InvalidScheme,
}

/// Options for connecting client to hosts
#[derive(Clone, PartialEq, Debug)]
pub struct HostOptions {
    /// Transport / scheme for connection
    pub scheme: Transport,
    /// Host to connect to
    pub host: String,
    /// Port for connection
    pub port: u16,
    /// Resource path (if provided)
    pub resource: String,
}

impl Default for HostOptions {
    fn default() -> Self {
        Self {
            scheme: Transport::Udp,
            host: "localhost".to_string(),
            port: 5683,
            resource: "".to_string(),
        }
    }
}

impl ToString for HostOptions {
    fn to_string(&self) -> String {
        format!("{}://{}:{}", self.scheme, self.port, self.host)
    }
}

impl TryFrom<(&str, u16)> for HostOptions {
    type Error = std::io::Error;

    /// Convert from host and port
    fn try_from(v: (&str, u16)) -> Result<HostOptions, Self::Error> {
        Ok(Self {
            host: v.0.to_string(),
            port: v.1,
            ..Default::default()
        })
    }
}

impl TryFrom<(Transport, &str, u16)> for HostOptions {
    type Error = std::io::Error;

    /// Convert from scheme, host and port
    fn try_from(v: (Transport, &str, u16)) -> Result<HostOptions, Self::Error> {
        Ok(Self {
            scheme: v.0,
            host: v.1.to_string(),
            port: v.2,
            ..Default::default()
        })
    }
}

impl TryFrom<&str> for HostOptions {
    type Error = std::io::Error;

    /// Parse from string
    fn try_from(url: &str) -> Result<HostOptions, Self::Error> {
        // Split URL to parameters
        let params = match url::Url::from_str(url) {
            Ok(v) => v,
            Err(e) => {
                error!("Error parsing URL '{}': {:?}", url, e);
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Invalid Url",
                ));
            }
        };

        // Match transport (or default to UDP)
        let s = params.scheme();
        let scheme = match (s, Transport::from_str(s)) {
            ("", _) => Transport::Udp,
            (_, Ok(v)) => v,
            (_, Err(_e)) => {
                error!("Unrecognized or unsupported scheme: {}", params.scheme());
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Invalid Scheme",
                ));
            }
        };

        // Match port (or derive based on scheme default)
        let p = params.port();
        let port = match (p, &scheme) {
            (Some(p), _) => p,
            (None, Transport::Udp) => 5683,
            (None, Transport::Dtls) => 5684,
            (None, Transport::Tcp) => 5683,
            (None, Transport::Tls) => 5684,
        };

        Ok(HostOptions {
            scheme,
            host: params.host_str().unwrap_or("localhost").to_string(),
            port,
            resource: params.path().to_string(),
        })
    }
}

/// Async CoAP client, generic over Backend implementations
pub struct Client<E, T: Backend<E>> {
    transport: T,
    _e: PhantomData<E>,
}

/// Tokio base CoAP client
#[cfg(feature = "backend-tokio")]
pub type TokioClient = Client<std::io::Error, backend::Tokio>;

#[cfg(feature = "backend-tokio")]
impl TokioClient {
    /// Create a new client with the provided host and client options
    pub async fn connect<H>(host: H, opts: &ClientOptions) -> Result<Self, std::io::Error>
    where
        H: TryInto<HostOptions>,
        <H as TryInto<HostOptions>>::Error: std::fmt::Debug,
    {
        // Convert provided host options
        let peer: HostOptions = match host.try_into() {
            Ok(v) => v,
            Err(e) => {
                error!("Error parsing host options: {:?}", e);
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Invalid host options",
                ));
            }
        };
        let connect_str = format!("{}:{}", peer.host, peer.port);
        debug!("Using host options: {:?} (connect: {})", peer, connect_str);

        // Create appropriate transport
        let transport = match &peer.scheme {
            Transport::Udp => backend::Tokio::new_udp(&connect_str).await?,
            Transport::Dtls => backend::Tokio::new_dtls(&connect_str, opts).await?,
            _ => {
                error!("Transport '{}' not yet implemented", peer.scheme);
                unimplemented!()
            }
        };

        // Return client object
        Ok(Self {
            transport,
            _e: PhantomData,
        })
    }

    /// Close the provided client, ending all existing sessions
    pub async fn close(self) -> Result<(), std::io::Error> {
        self.transport.close().await
    }
}

/// Mark clients as Send if the backend is
unsafe impl<E, B: Backend<E> + Send> Send for Client<E, B> {}

impl<E, T> Client<E, T>
where
    T: Backend<E>,
    E: std::fmt::Debug,
{
    /// Perform a basic CoAP request
    pub async fn request(
        &mut self,
        method: Method,
        resource: &str,
        data: Option<&[u8]>,
        opts: &RequestOptions,
    ) -> Result<Packet, Error<E>> {
        // Build request object
        let mut request = CoapRequest::<&str>::new();

        request.message.header.message_id = rand::random();

        request.set_method(method);
        request.set_path(resource);

        match !opts.non_confirmable {
            true => request.message.header.set_type(MessageType::Confirmable),
            false => request.message.header.set_type(MessageType::NonConfirmable),
        }

        if let Some(d) = data {
            request.message.payload = d.to_vec();
        }

        let t = rand::random::<u32>();
        let token = t.to_le_bytes().to_vec();
        request.message.set_token(token);

        // Send request via backing transport
        let resp = self
            .transport
            .request(request.message, opts.clone())
            .await
            .map_err(Error::Transport)?;

        // TODO: handle response error codes here...

        Ok(resp)
    }

    /// Observe the provided resource
    pub async fn observe(
        &mut self,
        resource: &str,
        opts: &RequestOptions,
    ) -> Result<<T as Backend<E>>::Observe, E> {
        self.transport
            .observe(resource.to_string(), opts.clone())
            .await
    }

    /// Deregister an observation
    pub async fn unobserve(&mut self, o: <T as Backend<E>>::Observe) -> Result<(), E> {
        self.transport.unobserve(o).await
    }

    /// Perform a Get request from the provided resource
    pub async fn get(
        &mut self,
        resource: &str,
        opts: &RequestOptions,
    ) -> Result<Vec<u8>, Error<E>> {
        let resp = self.request(Method::Get, resource, None, opts).await?;
        Ok(resp.payload)
    }

    /// Perform a Put request to the provided resource
    pub async fn put(
        &mut self,
        resource: &str,
        data: Option<&[u8]>,
        opts: &RequestOptions,
    ) -> Result<Vec<u8>, Error<E>> {
        let resp = self.request(Method::Put, resource, data, opts).await?;
        Ok(resp.payload)
    }

    /// Perform a Post request to the provided resource
    pub async fn post(
        &mut self,
        resource: &str,
        data: Option<&[u8]>,
        opts: &RequestOptions,
    ) -> Result<Vec<u8>, Error<E>> {
        let resp = self.request(Method::Post, resource, data, opts).await?;
        Ok(resp.payload)
    }
}

fn token_as_u32(token: &[u8]) -> u32 {
    let mut v = 0;

    for i in 0..token.len() {
        v |= (token[i] as u32) << (i * 8);
    }

    v
}

fn status_is_ok(status: ResponseType) -> bool {
    use ResponseType::*;

    match status {
        Created | Deleted | Valid | Changed | Content | Continue => true,
        _ => false,
    }
}