aboutsummaryrefslogtreecommitdiff
path: root/src/lcp.rs
blob: 457a7c72768b3e12360d385c37270090a72f8e3e (plain) (blame)
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
use byteorder::{ByteOrder, NetworkEndian as NE};

use std::convert::TryFrom;

use crate::auth;
use crate::error::ParseError;

pub const CONFIGURE_REQUEST: u8 = 1;
pub const CONFIGURE_ACK: u8 = 2;
pub const CONFIGURE_NAK: u8 = 3;
pub const CONFIGURE_REJECT: u8 = 4;
pub const TERMINATE_REQUEST: u8 = 5;
pub const TERMINATE_ACK: u8 = 6;
pub const CODE_REJECT: u8 = 7;
pub const PROTOCOL_REJECT: u8 = 8;
pub const ECHO_REQUEST: u8 = 9;
pub const ECHO_REPLY: u8 = 10;
pub const DISCARD_REQUEST: u8 = 11;

#[repr(u8)]
#[derive(PartialEq, Eq, Copy, Clone)]
pub enum Code {
    ConfigureRequest = CONFIGURE_REQUEST,
    ConfigureAck = CONFIGURE_ACK,
    ConfigureNak = CONFIGURE_NAK,
    ConfigureReject = CONFIGURE_REJECT,
    TerminateRequest = TERMINATE_REQUEST,
    TerminateAck = TERMINATE_ACK,
    CodeReject = CODE_REJECT,
    ProtocolReject = PROTOCOL_REJECT,
    EchoRequest = ECHO_REQUEST,
    EchoReply = ECHO_REPLY,
    DiscardRequest = DISCARD_REQUEST,
}

impl TryFrom<u8> for Code {
    type Error = ParseError;
    fn try_from(code: u8) -> Result<Self, ParseError> {
        Ok(match code {
            CONFIGURE_REQUEST => Code::ConfigureRequest,
            CONFIGURE_ACK => Code::ConfigureAck,
            CONFIGURE_NAK => Code::ConfigureNak,
            CONFIGURE_REJECT => Code::ConfigureReject,
            TERMINATE_REQUEST => Code::TerminateRequest,
            TERMINATE_ACK => Code::TerminateAck,
            CODE_REJECT => Code::CodeReject,
            PROTOCOL_REJECT => Code::ProtocolReject,
            ECHO_REQUEST => Code::EchoRequest,
            ECHO_REPLY => Code::EchoReply,
            DISCARD_REQUEST => Code::DiscardRequest,
            _ => return Err(ParseError::InvalidLcpCode(code)),
        })
    }
}

fn ensure_minimal_buffer_length(buffer: &[u8]) -> Result<(), ParseError> {
    if buffer.len() < 4 {
        return Err(ParseError::BufferTooSmall(buffer.len()));
    }
    Ok(())
}

#[derive(Debug)]
pub struct Header<'a>(&'a [u8]);

impl<'a> Header<'a> {
    pub fn with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, None)
    }

    pub fn with_buffer_and_code(
        buffer: &'a [u8],
        expected_code: Option<Code>,
    ) -> Result<Header<'a>, ParseError> {
        ensure_minimal_buffer_length(buffer)?;

        let code = Code::try_from(buffer[0])?;
        if let Some(expected_code) = expected_code {
            if code != expected_code {
                return Err(ParseError::UnexpectedCode(code as u8));
            }
        }

        let length = usize::from(NE::read_u16(&buffer[2..4]));
        if length + 4 > buffer.len() {
            return Err(ParseError::PayloadLengthOutOfBound {
                actual_packet_length: buffer.len() as u16,
                payload_length: length as u16,
            });
        }

        Ok(Header(buffer))
    }

    pub fn configure_request_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::ConfigureRequest))
    }

    pub fn configure_ack_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::ConfigureAck))
    }

    pub fn configure_nak_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::ConfigureNak))
    }

    pub fn configure_reject_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::ConfigureReject))
    }

    pub fn terminate_request_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::TerminateRequest))
    }

    pub fn terminate_ack_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::TerminateAck))
    }

    pub fn code_reject_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::CodeReject))
    }

    pub fn protocol_reject_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::ProtocolReject))
    }

    pub fn echo_request_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::EchoRequest))
    }

    pub fn echo_reply_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::EchoReply))
    }

    pub fn discard_request_with_buffer(buffer: &'a [u8]) -> Result<Self, ParseError> {
        Self::with_buffer_and_code(buffer, Some(Code::DiscardRequest))
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }

    pub fn get_ref(&self) -> &[u8] {
        self.0
    }

    pub fn code(&self) -> u8 {
        self.0[0]
    }

    pub fn identifier(&self) -> u8 {
        self.0[1]
    }

    pub fn len(&self) -> usize {
        usize::from(NE::read_u16(&self.0[2..4]))
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 4
    }

    pub fn payload(&self) -> &[u8] {
        &self.0[4..self.len()]
    }
}

pub struct HeaderBuilder<'a>(&'a mut [u8]);

impl<'a> HeaderBuilder<'a> {
    pub fn code(&self) -> u8 {
        self.0[0]
    }

    pub fn identifier(&self) -> u8 {
        self.0[1]
    }

    pub fn len(&self) -> usize {
        usize::from(NE::read_u16(&self.0[2..4]))
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 4
    }

    pub fn payload(&self) -> &[u8] {
        &self.0[4..self.len()]
    }

    pub fn set_code(&mut self, code: Code) {
        self.0[0] = code as u8;
    }

    pub fn set_identifier(&mut self, identifier: u8) {
        self.0[1] = identifier;
    }

    unsafe fn set_len(&mut self, new_length: u16) {
        NE::write_u16(&mut self.0[2..4], new_length)
    }

    pub fn clear_payload(&mut self) {
        unsafe { self.set_len(0) };
    }

    pub fn create_packet(
        buffer: &'a mut [u8],
        code: Code,
        identifier: u8,
    ) -> Result<Self, ParseError> {
        ensure_minimal_buffer_length(buffer)?;

        let length = buffer[4..].len() as u16;

        buffer[0] = code as u8;
        buffer[1] = identifier;
        NE::write_u16(&mut buffer[2..4], length);

        Ok(HeaderBuilder(buffer))
    }

    pub fn create_configure_request(buffer: &'a mut [u8]) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::ConfigureRequest, rand::random())
    }

    pub fn create_configure_ack(buffer: &'a mut [u8], identifier: u8) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::ConfigureAck, identifier)
    }

    pub fn create_configure_nak(buffer: &'a mut [u8], identifier: u8) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::ConfigureAck, identifier)
    }

    pub fn create_configure_reject(
        buffer: &'a mut [u8],
        identifier: u8,
    ) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::ConfigureReject, identifier)
    }

    pub fn create_terminate_request(buffer: &'a mut [u8]) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::TerminateRequest, rand::random())
    }

    pub fn create_terminate_ack(buffer: &'a mut [u8], identifier: u8) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::TerminateAck, identifier)
    }

    pub fn create_code_reject(buffer: &'a mut [u8], identifier: u8) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::CodeReject, identifier)
    }

    pub fn create_protocol_reject(
        buffer: &'a mut [u8],
        identifier: u8,
    ) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::ProtocolReject, identifier)
    }

    pub fn create_echo_request(buffer: &'a mut [u8]) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::EchoRequest, rand::random())
    }

    pub fn create_echo_reply(buffer: &'a mut [u8], identifier: u8) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::EchoReply, identifier)
    }

    pub fn create_discard_request(buffer: &'a mut [u8]) -> Result<Self, ParseError> {
        Self::create_packet(buffer, Code::DiscardRequest, rand::random())
    }

    pub fn get_ref_mut(&mut self) -> &mut [u8] {
        self.0
    }

    pub fn build(self) -> Result<Header<'a>, ParseError> {
        Header::with_buffer(self.0)
    }
}

fn ensure_minimal_option_length(buffer: &[u8]) -> Result<(), ParseError> {
    if buffer.len() < 2 {
        return Err(ParseError::BufferTooSmall(buffer.len()));
    }
    Ok(())
}

pub const MRU: u8 = 1;
pub const AUTH_PROTOCOL: u8 = 3;
pub const QUALITY_PROTOCOL: u8 = 4;
pub const MAGIC_NUMBER: u8 = 5;
pub const PFC: u8 = 7;
pub const ACFC: u8 = 8;

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ConfigOption<'a> {
    Mru(u16),
    AuthProtocol(auth::Protocol),
    QualityProtocol(&'a [u8]),
    MagicNumber(u32),
    Pfc,
    Acfc,
}

impl<'a> ConfigOption<'a> {
    fn from_buffer(option: &'a [u8]) -> Result<(ConfigOption<'a>, &'a [u8]), ParseError> {
        ensure_minimal_option_length(option)?;

        Ok(match option[0] {
            MRU => {
                // constant length
                if option[1] != 4 {
                    return Err(ParseError::InvalidOptionLength(option[1]));
                }

                (ConfigOption::Mru(NE::read_u16(&option[2..4])), &option[4..])
            }
            AUTH_PROTOCOL => {
                if option[1] < 4 {
                    return Err(ParseError::InvalidOptionLength(option[1]));
                }

                let auth_protocol = auth::Protocol::try_from(&option[2..option[1] as usize])?;
                (
                    ConfigOption::AuthProtocol(auth_protocol),
                    &option[option[1] as usize..],
                )
            }
            QUALITY_PROTOCOL => {
                if option[1] < 4 {
                    return Err(ParseError::InvalidOptionLength(option[1]));
                }

                let quality_protocol = NE::read_u16(&option[2..4]);
                if quality_protocol != 0xc025 {
                    return Err(ParseError::InvalidQualityProtocol(quality_protocol));
                }

                (
                    ConfigOption::QualityProtocol(&option[4..option[1] as usize]),
                    &option[option[1] as usize..],
                )
            }
            MAGIC_NUMBER => {
                // constant length
                if option[1] != 6 {
                    return Err(ParseError::InvalidOptionLength(option[1]));
                }

                (
                    ConfigOption::MagicNumber(NE::read_u32(&option[2..6])),
                    &option[6..],
                )
            }
            PFC => {
                // constant length
                if option[1] != 2 {
                    return Err(ParseError::InvalidOptionLength(option[1]));
                }

                (ConfigOption::Pfc, &option[2..])
            }
            ACFC => {
                // constant length
                if option[1] != 2 {
                    return Err(ParseError::InvalidOptionLength(option[1]));
                }

                (ConfigOption::Acfc, &option[2..])
            }
            _ => return Err(ParseError::InvalidOptionType(option[0])),
        })
    }
}

pub struct ConfigOptionIterator<'a> {
    payload: &'a [u8],
}

impl<'a> ConfigOptionIterator<'a> {
    pub fn new(payload: &'a [u8]) -> Self {
        ConfigOptionIterator { payload }
    }
}

impl<'a> Iterator for ConfigOptionIterator<'a> {
    type Item = ConfigOption<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.payload.is_empty() {
            return None;
        }

        let (opt, payload) = ConfigOption::from_buffer(self.payload).unwrap();
        self.payload = payload;
        Some(opt)
    }
}