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
//! An implemenmtation of a [coap_handler::Handler] around a [scroll_ring::Buffer]
//!
//! ## Usage
//!
//! Wrap a buffer (typically some tasks's linear text output) through
//! [`BufferHandler::new(&buf)`](BufferHandler::new) and place it [`.at(&["output"],
//! ...)`](coap_handler_implementations::HandlerBuilder::at) some CoAP handler tree.
//!
//! ## Examples
//!
//! This crate comes with no example, but the
//! [coap-message-demos](https://crates.io/crates/coap-message-demos) crate makes ample use of it
//! for its logging adapter.
#![no_std]

use coap_message::{MutableWritableMessage, ReadableMessage};
use coap_numbers::{code, content_format, option};
use core::num::Wrapping;

/// CoAP handler for reading from a [Buffer](scroll_ring::Buffer)
///
/// This implements a variant of the
/// [proposed](https://forum.riot-os.org/t/coap-remote-shell/3340/5) stdio handling. It deviates in
/// some details, in particular:
///
/// * It uses CBOR streams rather than a response array, and no array pairs.
/// * It always sends offset and a single data item (effecively leaving it open whether the pattern
///   would be continued `[5, "hello ", 11, "world"]` or `[5, "hello ", "world"]`).
/// * GET always reports the oldest available data (that's probably underspecified in the original
///   proposal)
/// * GETs return immediately.
/// * FETCH only takes a single integer: where to start.
/// * No paired channel.
pub struct BufferHandler<'a, const N: usize>(&'a scroll_ring::Buffer<N>);

impl<'a, const N: usize> BufferHandler<'a, N> {
    /// Construct a handler for a buffer
    ///
    /// This adds nothing to the buffer other than the selection of the CoAP serialization; if it
    /// were not for separation of concerns, the [coap_handler] implementation could just as well
    /// be on the buffer itself.
    pub fn new(buffer: &'a scroll_ring::Buffer<N>) -> Self {
        Self(buffer)
    }
}

#[doc(hidden)]
pub enum RequestedScrollbufPosition {
    FromStart,
    StartingAt(Wrapping<u32>),
}

use RequestedScrollbufPosition::*;

impl<'a, const N: usize> coap_handler::Handler for BufferHandler<'a, N> {
    type RequestData = Result<RequestedScrollbufPosition, u8>;

    fn extract_request_data(
        &mut self,
        req: &impl ReadableMessage,
    ) -> Result<RequestedScrollbufPosition, u8> {
        use coap_handler_implementations::option_processing::OptionsExt;
        use coap_message::MessageOption;

        req.options()
            .filter(|o| {
                !(o.number() == option::ACCEPT
                    && o.value_uint::<u16>()
                        == Some(content_format::from_str("application/cbor-seq").unwrap()))
            })
            // Not processing Content-Format: it's elective anyway
            .ignore_elective_others()
            .map_err(|_| code::BAD_OPTION)?;

        Ok(match req.code().into() {
            code::GET => FromStart,
            code::FETCH => StartingAt(Wrapping({
                let payload = req.payload();
                // Quick and dirty parsing of a single CBOR uint up to 32bit
                match (payload.get(0), payload.len() - 1) {
                    (Some(i @ 0..=23), 0) => (*i).into(),
                    (Some(24), 1) => payload[1].into(),
                    (Some(25), 2) => u16::from_be_bytes(payload[1..3].try_into().unwrap()).into(),
                    (Some(26), 4) => u32::from_be_bytes(payload[1..5].try_into().unwrap()),
                    _ => return Err(code::BAD_REQUEST),
                }
            })),
            _ => return Err(code::METHOD_NOT_ALLOWED),
        })
    }

    fn estimate_length(&mut self, _: &<Self as coap_handler::Handler>::RequestData) -> usize {
        1100
    }
    fn build_response(
        &mut self,
        res: &mut impl MutableWritableMessage,
        req: Result<RequestedScrollbufPosition, u8>,
    ) {
        let mode = match req {
            Ok(m) => m,
            Err(c) => {
                res.set_code(c.try_into().ok().unwrap());
                return;
            }
        };
        res.set_code(code::CONTENT.try_into().ok().unwrap());

        res.add_option_uint(
            option::CONTENT_FORMAT.try_into().ok().unwrap(),
            content_format::from_str("application/cbor-seq").unwrap(),
        );

        let len = res.available_space() - 1;
        let msg_buf = res.payload_mut_with_len(len);

        assert!(len > 8);
        msg_buf[0] = 0x1a; // u32; we'll get the cursor later
        msg_buf[5] = 0x59; // byte string of u16 length; we'll get the length later

        let data_area = &mut msg_buf[8..];

        let (cursor, bytes) = match mode {
            FromStart => match self.0.read_earliest(data_area) {
                Ok((cursor, bytes)) => (cursor, bytes),
                _ => {
                    res.set_code(code::SERVICE_UNAVAILABLE.try_into().ok().unwrap());
                    res.truncate(0);
                    return;
                }
            },
            StartingAt(n) => match self.0.read_from_cursor(n, data_area) {
                Ok(bytes) => (n, bytes),
                _ => {
                    // Both "it's currently locked" and "we've lost the data" are grounds for a
                    // retry with a plain GET; not distinguishing so far
                    res.set_code(code::SERVICE_UNAVAILABLE.try_into().ok().unwrap());
                    res.truncate(0);
                    return;
                }
            },
        };

        let bytes_written = core::cmp::min(bytes, data_area.len());
        msg_buf[1..5].copy_from_slice(&cursor.0.to_be_bytes());
        msg_buf[6..8].copy_from_slice(&(bytes_written as u16).to_be_bytes());
        res.truncate(8 + bytes_written);
    }
}

#[doc(hidden)]
pub struct BufferHandlerRecord(());

impl<'a, const N: usize> coap_handler::Reporting for BufferHandler<'a, N> {
    type Record<'b> = BufferHandlerRecord where Self: 'b;
    type Reporter<'b> = core::iter::Once<BufferHandlerRecord> where Self: 'b;
    fn report(&self) -> Self::Reporter<'_> {
        core::iter::once(BufferHandlerRecord(()))
    }
}

impl<'a> coap_handler::Record for BufferHandlerRecord {
    type PathElement = &'static &'static str;
    type PathElements = core::iter::Empty<&'static &'static str>;
    type Attributes = core::iter::Once<coap_handler::Attribute>;

    fn path(&self) -> Self::PathElements {
        core::iter::empty()
    }
    fn rel(&self) -> Option<&str> {
        None
    }
    fn attributes(&self) -> Self::Attributes {
        core::iter::once(coap_handler::Attribute::Interface(
            "tag:riot-os.org,2021:ser-out",
        ))
    }
}