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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Checking for validity of route announcements.

use std::{fmt, io};
use std::str::FromStr;
use chrono::{DateTime, Utc};
use rpki::resources::{Asn, Prefix};
use rpki::rtr::payload::RouteOrigin;
use serde::Deserialize;
use crate::payload::{PayloadInfo, PayloadSnapshot};
use crate::utils::date::format_iso_date;


//------------ RouteValidityList ---------------------------------------------

/// Information about the RPKI validity of route announcements.
#[derive(Clone, Debug)]
pub struct RouteValidityList<'a> {
    routes: Vec<RouteValidity<'a>>,
    created: DateTime<Utc>,
}

impl<'a> RouteValidityList<'a> {
    /// Creates a value from requests and a snapshot.
    fn from_requests(
        requests: &RequestList, snapshot: &'a PayloadSnapshot
    ) -> Self {
        RouteValidityList {
            routes: requests.routes.iter().map(|route| {
                RouteValidity::new(route.prefix, route.asn, snapshot)
            }).collect(),
            created: snapshot.created(),
        }
    }

    pub fn write_plain<W: io::Write>(
        &self,
        target: &mut W
    ) -> Result<(), io::Error> {
        for route in &self.routes {
            route.write_plain(target)?;
        }
        Ok(())
    }

    pub fn write_json<W: io::Write>(
        &self,
        target: &mut W
    ) -> Result<(), io::Error> {
        writeln!(target, "{{\n  \"validated_routes\": [")?;
        let mut first = true;
        for route in &self.routes {
            if first {
                first = false;
            }
            else {
                writeln!(target, ",")?;
            }
            write!(target, "    ")?;
            route.write_single_json("    ", target)?;
        }
        writeln!(target,
            "\n  ],\
            \n  \"generatedTime\": \"{}\"\
            \n}}",
            format_iso_date(self.created),
        )
    }

    pub fn iter_state(
        &self
    ) -> impl Iterator<Item = (Prefix, Asn, RouteState)> + '_ {
        self.routes.iter().map(|route| {
            (route.prefix, route.asn, route.state())
        })
    }
}


//------------ RouteValidity -------------------------------------------------

/// Information about the RPKI validity of a single route announcement.
#[derive(Clone, Debug)]
pub struct RouteValidity<'a> {
    /// The address prefix of the route announcement.
    prefix: Prefix,

    /// The origin AS number of the route announcement.
    asn: Asn,

    /// Indexes of the matched VRPs in `origins`.
    matched: Vec<(RouteOrigin, &'a PayloadInfo)>,

    /// Indexes of covering VRPs that don’t match because of the ´asn`.
    bad_asn: Vec<(RouteOrigin, &'a PayloadInfo)>,

    /// Indexes of covering VRPs that don’t match because of the prefix length.
    bad_len: Vec<(RouteOrigin, &'a PayloadInfo)>,
}

impl<'a> RouteValidity<'a> {
    pub fn new(
        prefix: Prefix,
        asn: Asn,
        snapshot: &'a PayloadSnapshot
    ) -> Self {
        let mut matched = Vec::new();
        let mut bad_asn = Vec::new();
        let mut bad_len = Vec::new();
        for item in snapshot.origins() {
            if item.0.prefix.prefix().covers(prefix) {
                if prefix.len() > item.0.prefix.resolved_max_len() {
                    bad_len.push(item);
                }
                else if item.0.asn != asn {
                    bad_asn.push(item);
                }
                else {
                    matched.push(item)
                }
            }
        }
        RouteValidity { prefix, asn, matched, bad_asn, bad_len }
    }

    pub fn prefix(&self) -> Prefix {
        self.prefix
    }

    pub fn asn(&self) -> Asn {
        self.asn
    }

    pub fn state(&self) -> RouteState {
        if self.matched.is_empty() {
            if self.bad_asn.is_empty() && self.bad_len.is_empty() {
                RouteState::NotFound
            }
            else {
                RouteState::Invalid
            }
        }
        else {
            RouteState::Valid
        }
    }

    pub fn reason(&self) -> Option<&'static str> {
        if self.matched.is_empty() {
            if !self.bad_asn.is_empty() {
                Some("as")
            }
            else if !self.bad_len.is_empty() {
                Some("length")
            }
            else {
                None
            }
        }
        else {
            None
        }
    }

    pub fn description(&self) -> &'static str {
        if self.matched.is_empty() {
            if !self.bad_asn.is_empty() {
                DESCRIPTION_BAD_ASN
            }
            else if !self.bad_len.is_empty() {
                DESCRIPTION_BAD_LEN
            }
            else {
                DESCRIPTION_NOT_FOUND
            }
        }
        else {
            DESCRIPTION_VALID
        }
    }

    pub fn matched(&self) -> &[(RouteOrigin, &'a PayloadInfo)] {
        &self.matched
    }

    pub fn bad_asn(&self) -> &[(RouteOrigin, &'a PayloadInfo)] {
        &self.bad_asn
    }

    pub fn bad_len(&self) -> &[(RouteOrigin, &'a PayloadInfo)] {
        &self.bad_len
    }

    pub fn write_plain<W: io::Write>(
        &self,
        target: &mut W
    ) -> Result<(), io::Error> {
        writeln!(target, "{} => {}: {}", self.prefix, self.asn, self.state())
    }

    pub fn into_json(self, current: &PayloadSnapshot) -> Vec<u8> {
        let mut res = Vec::new();
        self.write_json(current, &mut res).unwrap();
        res
    }

    pub fn write_json<W: io::Write>(
        &self,
        current: &PayloadSnapshot,
        target: &mut W
    ) -> Result<(), io::Error> {
        write!(target, "{{\n  \"validated_route\": ")?;
        self.write_single_json("  ", target)?;
        writeln!(target,
            ",\n  \"generatedTime\": \"{}\"\
            \n}}",
            format_iso_date(current.created()),
        )
    }

    fn write_single_json<W: io::Write>(
        &self,
        indent: &str,
        target: &mut W
    ) -> Result<(), io::Error> {
        writeln!(target, "{{\n\
            {indent}  \"route\": {{\n\
            {indent}    \"origin_asn\": \"{}\",\n\
            {indent}    \"prefix\": \"{}\"\n\
            {indent}  }},\n\
            {indent}  \"validity\": {{\n\
            {indent}    \"state\": \"{}\",",  
            self.asn,
            self.prefix,
            self.state(),
            indent = indent,
        )?;
        if let Some(reason) = self.reason() {
            writeln!(target, "{}    \"reason\": \"{}\",", indent, reason)?;
        }
        writeln!(
            target,
            "{indent}    \"description\": \"{}\",\n\
             {indent}    \"VRPs\": {{",
            self.description(), indent = indent
        )?;

        Self::write_vrps_json(
            indent, "matched", &self.matched, target
        )?;
        writeln!(target, ",")?;
        Self::write_vrps_json(
            indent, "unmatched_as", &self.bad_asn, target
        )?;
        writeln!(target, ",")?;
        Self::write_vrps_json(
            indent, "unmatched_length", &self.bad_len, target
        )?;

        write!(
            target, "\n\
            {indent}    }}\n\
            {indent}  }}\n\
            {indent}}}",
            indent = indent
        )
    }

    fn write_vrps_json<W: io::Write>(
        indent: &str,
        category: &str,
        vrps: &[(RouteOrigin, &'a PayloadInfo)],
        target: &mut W
    ) -> Result<(), io::Error> {
        write!(target, "{}      \"{}\": [", indent, category)?;
        let mut first = true;
        for item in vrps.iter() {
            if first {
                first = false;
            }
            else {
                write!(target, ",")?;
            }

            write!(
                target,
                "\n\
                {indent}        {{\n\
                {indent}          \"asn\": \"{}\",\n\
                {indent}          \"prefix\": \"{}\",\n\
                {indent}          \"max_length\": \"{}\"\n\
                {indent}        }}",
                item.0.asn,
                item.0.prefix.prefix(),
                item.0.prefix.resolved_max_len(),
                indent = indent
            )?
        }
        write!(target, "\n{}      ]", indent)
    }

}


//------------ RouteState ----------------------------------------------------

/// The RPKI state of a route announcement.
///
/// These states are defined in [RFC 6811] and determine whether a route
/// announcement has passed by RPKI route origin validation.
///
/// The states are determined based on two terms:
///
/// * A VRP is said to _cover_ an announcement if its prefix covers the
///   announcement, that is the VRP’s prefixes length is less or equal and
///   the bits of its network prefix match the respective bits of the
///   announcment’s prefix.
/// * A VRP is said to _match_ an announcement if it covers the announcment
///   and in addition the announcement’s origin AS number is equal to the
///   VRP’s AS number and the announcement’s prefix length is less or equal
///   to the VRP’s maximum length (which is considered equal to the prefix
///   length if absent).
///
/// With these definitions in mind, there are three states described by the
/// three variants of this enum.
///
/// [RFC 6811]: https://tools.ietf.org/html/rfc6811
#[derive(Clone, Copy, Debug)]
pub enum RouteState {
    /// RPKI Valid.
    ///
    /// At least one VRP matches the annoncement.
    Valid,

    /// RPKI Invalid.
    ///
    /// At least one VRP covers the announcement but no VRP matches it.
    Invalid,

    /// RPKI Not Found.
    ///
    /// No VRP covers the announcement.
    NotFound
}

impl fmt::Display for RouteState {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            RouteState::Valid => "valid",
            RouteState::Invalid => "invalid",
            RouteState::NotFound => "not-found",
        })
    }
}


//------------ RequestList ---------------------------------------------------

/// A list of requests for route validity checks.
///
/// This type is intended to be used for deserialization of such a list from a
/// file.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct RequestList {
    /// All the requests.
    routes: Vec<Request>,
}

impl RequestList {
    /// Loads the request list from a plain text reader.
    pub fn from_plain_reader<R: io::BufRead>(
        reader: R
    ) -> Result<Self, io::Error>
    {
        let mut res = Self::default();

        for (line_no, line) in reader.lines().enumerate() {
            let line = line?;
            let mut tokens = line.split_whitespace();

            // PREFIX => ASN [# anything ]

            let prefix = match tokens.next() {
                Some(prefix) => {
                    match Prefix::from_str(prefix) {
                        Ok(prefix) => prefix,
                        Err(_) => {
                            return Err(io::Error::new(
                                io::ErrorKind::Other,
                                format!(
                                    "line {}: expecting prefix, got '{}'",
                                    line_no + 1, prefix
                                )
                            ))
                        }
                    }
                }
                None => continue
            };

            match tokens.next() {
                Some("=>") => { }
                Some(token) => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        format!(
                            "line {}: expecting '=>', got '{}'",
                            line_no + 1, token
                        )
                    ))
                }
                None => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        format!(
                            "line {}: expecting '=>', got end of line",
                            line_no + 1
                        )
                    ))
                }
            }

            let asn = match tokens.next() {
                Some(asn) => {
                    match Asn::from_str(asn) {
                        Ok(asn) => asn,
                        Err(_) => {
                            return Err(io::Error::new(
                                io::ErrorKind::Other,
                                format!(
                                    "line {}: expecting AS number, got '{}'",
                                    line_no + 1, asn
                                )
                            ))
                        }
                    }
                }
                None => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        format!(
                            "line {}: expecting AS number, got end of line",
                            line_no + 1
                        )
                    ))
                }
            };

            match tokens.next() {
                Some("#") | None => { }
                Some(token) => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        format!(
                            "line {}: expecting '#'  or end of line, got '{}'",
                            line_no + 1, token
                        )
                    ))
                }
            }

            res.routes.push(Request { prefix, asn });
        }

        Ok(res)
    }

    /// Loads the request list from a json-formatted reader.
    pub fn from_json_reader<R: io::Read>(
        reader: &mut R
    ) -> Result<Self, serde_json::Error> {
        serde_json::from_reader(reader)
    }

    /// Creates a request list with a single entry.
    pub fn single(prefix: Prefix, asn: Asn) -> Self {
        RequestList {
            routes: vec![Request { prefix, asn }]
        }
    }

    /// Checks the validity of all routes and returns a vec with results.
    pub fn validity<'a>(
        &self,
        snapshot: &'a PayloadSnapshot
    ) -> RouteValidityList<'a> {
        RouteValidityList::from_requests(self, snapshot)
    }
}


//------------ Request -------------------------------------------------------

/// A request for a route validity check.
#[derive(Clone, Debug, Deserialize)]
struct Request {
    /// The address prefix of the route announcement.
    prefix: Prefix,

    /// The origin AS number of the route announcement.
    #[serde(deserialize_with = "Asn::deserialize_from_any")]
    asn: Asn,
}


//------------ Constants -----------------------------------------------------

// Description texts as provided by the RIPE NCC Validator.
//
const DESCRIPTION_VALID: &str = "At least one VRP Matches the Route Prefix";
const DESCRIPTION_BAD_ASN: &str = "At least one VRP Covers the Route Prefix, \
                                   but no VRP ASN matches the route origin \
                                   ASN";
const DESCRIPTION_BAD_LEN: &str = "At least one VRP Covers the Route Prefix, \
                                   but the Route Prefix length is greater \
                                   than the maximum length allowed by VRP(s) \
                                   matching this route origin ASN";
const DESCRIPTION_NOT_FOUND: &str = "No VRP Covers the Route Prefix";


//============ Tests =========================================================

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn request_list_from_json_reader() {
        let _ = RequestList::from_json_reader(
            &mut include_bytes!("../test/validate/beacons.json").as_ref()
        );
    }
}