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
use coap_message::{MessageOption, MutableWritableMessage, ReadableMessage};
use coap_numbers::{code, option};
use windowed_infinity::WindowedInfinity;
pub fn codeconvert<O: TryFrom<u8>>(code: u8) -> O {
code.try_into()
.or_else(|_| code::INTERNAL_SERVER_ERROR.try_into())
.map_err(|_| "Responde type can't even express tha simplest error codes")
.unwrap()
}
pub(crate) fn optconvert<O: TryFrom<u16>>(option: u16) -> O {
option
.try_into()
.map_err(|_| "Response type can't express options required by handler")
.unwrap()
}
pub(crate) trait Renderable {
fn render(&self, message: &mut impl coap_message::MinimalWritableMessage);
}
pub struct Block2RequestData {
blknum: u32,
szx: u8,
}
#[derive(Debug)]
pub struct BadBlock2Option;
impl Block2RequestData {
pub fn from_message(message: &impl ReadableMessage) -> Result<Self, BadBlock2Option> {
let mut b2options = message.options().filter(|o| o.number() == option::BLOCK2);
match b2options.next() {
None => Ok(Self::default()),
Some(o) => {
if b2options.next().is_none() {
Self::from_option(&o)
} else {
Err(BadBlock2Option)
}
}
}
}
pub fn from_option(option: &impl MessageOption) -> Result<Self, BadBlock2Option> {
debug_assert!(option.number() == option::BLOCK2);
let o: u32 = option.value_uint().ok_or(BadBlock2Option)?;
if o >= 0x1000000 {
return Err(BadBlock2Option);
}
Ok(Self {
szx: (o as u8) & 0x7,
blknum: o >> 4,
})
}
pub fn to_option_value(&self, more: bool) -> u32 {
(self.blknum << 4) | if more { 0x08 } else { 0 } | self.szx as u32
}
pub fn size(&self) -> u16 {
1 << (4 + self.szx)
}
pub fn before(&self) -> u32 {
self.size() as u32 * self.blknum
}
pub fn shrink(mut self, size: u16) -> Option<Self> {
while self.size() > size {
if self.szx == 0 {
return None;
}
self.szx -= 1;
self.blknum *= 2;
}
Some(self)
}
}
impl Default for Block2RequestData {
fn default() -> Self {
Self { szx: 6, blknum: 0 }
}
}
pub fn block2_write<F, R>(
block2: Block2RequestData,
response: &mut impl MutableWritableMessage,
f: F,
) -> R
where
F: FnOnce(&mut windowed_infinity::TeeForCrc<'_, '_, u64>) -> R,
{
block2_write_with_cf(block2, response, f, None)
}
#[derive(PartialEq)]
enum Characterization {
Underflow,
Inside,
Overflow,
}
use Characterization::*;
impl Characterization {
fn new(cursor: isize, buffer: &[u8]) -> Self {
match usize::try_from(cursor) {
Err(_) => Underflow,
Ok(i) if i == buffer.len() => Inside,
_ => Overflow,
}
}
}
pub(crate) fn block2_write_with_cf<F, R>(
block2: Block2RequestData,
response: &mut impl MutableWritableMessage,
f: F,
cf: Option<u16>,
) -> R
where
F: FnOnce(&mut windowed_infinity::TeeForCrc<'_, '_, u64>) -> R,
{
let estimated_option_size = 25; let payload_budget = response.available_space() - estimated_option_size;
let block2 = block2
.shrink(payload_budget as u16)
.expect("Tiny buffer allocated");
response.add_option(optconvert(option::ETAG), &[0, 0, 0, 0, 0, 0, 0, 0]);
if let Some(cf) = cf {
if let Ok(cfopt) = option::CONTENT_FORMAT.try_into() {
response.add_option_uint(cfopt, cf);
}
}
response.add_option_uint(optconvert(option::BLOCK2), block2.to_option_value(false));
let (characterization, written, etag, ret) = {
let full_payload = response.payload_mut_with_len(block2.size().into());
let writer = WindowedInfinity::new(
&mut full_payload[..block2.size() as usize],
-(block2.before() as isize),
);
let etag = crc::Crc::<u64>::new(&crc::CRC_64_ECMA_182);
let mut writer = writer.tee_crc64(&etag);
let ret = f(&mut writer);
let (writer, etag) = writer.into_windowed_and_crc();
let written = writer.written();
(
Characterization::new(writer.cursor(), written),
written.len(),
etag.finalize().to_le_bytes(),
ret,
)
};
response.truncate(written);
if characterization == Underflow {
unimplemented!("Report out-of-band seek");
}
response.mutate_options(|optnum, value| {
match optnum.into() {
option::ETAG => {
value.copy_from_slice(&etag);
}
option::BLOCK2 if characterization == Overflow => {
value[value.len() - 1] |= 0x08;
}
_ => (),
};
});
ret
}
pub struct MaskingUriUpToPath<'m, M: ReadableMessage>(pub &'m M);
impl<'m, M: ReadableMessage> ReadableMessage for MaskingUriUpToPath<'m, M> {
type Code = M::Code;
type MessageOption<'a> = M::MessageOption<'a>
where
Self: 'a,
;
type OptionsIter<'a> = MaskingUriUpToPathIter<M::OptionsIter<'a>>
where
Self: 'a,
;
fn options(&self) -> Self::OptionsIter<'_> {
MaskingUriUpToPathIter(self.0.options())
}
fn code(&self) -> M::Code {
self.0.code()
}
fn payload(&self) -> &[u8] {
self.0.payload()
}
}
pub struct MaskingUriUpToPathIter<I>(I);
impl<MO: MessageOption, I: Iterator<Item = MO>> Iterator for MaskingUriUpToPathIter<I> {
type Item = MO;
fn next(&mut self) -> Option<MO> {
loop {
let result = self.0.next()?;
match result.number() {
coap_numbers::option::URI_HOST => continue,
coap_numbers::option::URI_PATH => continue,
_ => return Some(result),
}
}
}
}
pub(crate) struct MaskingUriUpToPathN<'m, M: ReadableMessage> {
message: &'m M,
strip_paths: usize,
}
impl<'m, M: ReadableMessage> MaskingUriUpToPathN<'m, M> {
pub(crate) fn new(message: &'m M, strip_paths: usize) -> Self {
Self {
message,
strip_paths,
}
}
}
impl<'m, M: ReadableMessage> ReadableMessage for MaskingUriUpToPathN<'m, M> {
type Code = M::Code;
type MessageOption<'a> = M::MessageOption<'a>
where
Self: 'a,
;
type OptionsIter<'a> = MaskingUriUpToPathNIter<M::OptionsIter<'a>>
where
Self: 'a,
;
fn options(&self) -> Self::OptionsIter<'_> {
MaskingUriUpToPathNIter {
inner: self.message.options(),
remaining_strip: self.strip_paths,
}
}
fn code(&self) -> M::Code {
self.message.code()
}
fn payload(&self) -> &[u8] {
self.message.payload()
}
}
pub struct MaskingUriUpToPathNIter<I> {
inner: I,
remaining_strip: usize,
}
impl<MO: MessageOption, I: Iterator<Item = MO>> Iterator for MaskingUriUpToPathNIter<I> {
type Item = MO;
fn next(&mut self) -> Option<MO> {
loop {
let result = self.inner.next()?;
match result.number() {
coap_numbers::option::URI_HOST => continue,
coap_numbers::option::URI_PATH if self.remaining_strip > 0 => {
self.remaining_strip -= 1;
continue;
}
_ => return Some(result),
}
}
}
}