bgpsim 0.20.4

A network control-plane simulator
Documentation
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// BgpSim: BGP Network Simulator written in Rust
// Copyright 2022-2024 Tibor Schneider <sctibor@ethz.ch>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Module that contains all LSA datastructures

use itertools::Itertools;
use ordered_float::NotNan;
use serde::{Deserialize, Serialize};

use crate::formatter::NetworkFormatter;
use crate::network::Network;
use crate::ospf::{LinkWeight, OspfImpl};
use crate::types::{Prefix, RouterId};

/// The different kinds of LSAs. LS type 2 (Network-SLA) and 4 (AS-Boundary Summary LSA) are not
/// implemented.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum LsaType {
    /// These are the router-LSAs. They describe the collected states of the router's interfaces.
    Router,
    /// These are the summary-LSAs. They describe inter-area routes, and enable the condensation
    /// of routing information at area borders.
    Summary,
    /// These are the AS-external-LSAs. Originated by AS boundary routers, they describe routes to
    /// destinations external to the Autonomous System. A default route for the Autonomous System
    /// can also be described by an AS-external-LSA.
    External,
}

impl std::fmt::Display for LsaType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            LsaType::Router => "Router",
            LsaType::Summary => "Summary",
            LsaType::External => "External",
        })
    }
}

///  The maximum age that an LSA can attain. When an LSA's LS age field reaches MaxAge, it is
/// reflooded in an attempt to flush the LSA from the routing domain (See Section 14). LSAs of age
/// MaxAge are not used in the routing table calculation.
pub const MAX_AGE: u16 = u16::MAX;
/// The maximum value that LS Sequence Number can attain.
pub const MAX_SEQ: u32 = u32::MAX;

impl LsaType {
    /// Return `true` if the LSA type is a `LsaType::Router`.
    #[inline(always)]
    pub fn is_router(&self) -> bool {
        matches!(self, LsaType::Router)
    }

    /// Return `true` if the LSA type is a `LsaType::Summary`.
    #[inline(always)]
    pub fn is_summary(&self) -> bool {
        matches!(self, LsaType::Summary)
    }

    /// Return `true` if the LSA type is a `LsaType::External`.
    #[inline(always)]
    pub fn is_external(&self) -> bool {
        matches!(self, LsaType::External)
    }
}

/// A single LSA header field.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LsaHeader {
    /// The type of LSA
    pub lsa_type: LsaType,
    /// The advertising router
    pub router: RouterId,
    /// Target router, only valid for `LsaType::Summary` and `LsaType::External`.
    pub target: Option<RouterId>,
    /// LS sequence number
    pub seq: u32,
    /// LS Age (used for clearing old advertisements)
    pub age: u16,
}

impl LsaHeader {
    /// Return `true` if the LSA type is a `LsaType::Router`.
    #[inline(always)]
    pub fn is_router(&self) -> bool {
        self.lsa_type.is_router()
    }

    /// Return `true` if the LSA type is a `LsaType::Summary`.
    #[inline(always)]
    pub fn is_summary(&self) -> bool {
        self.lsa_type.is_summary()
    }

    /// Return `true` if the LSA type is a `LsaType::External`.
    #[inline(always)]
    pub fn is_external(&self) -> bool {
        self.lsa_type.is_external()
    }

    /// Determine whether `self` is newer than `other`.
    pub fn compare(&self, other: &Self) -> LsaOrd {
        match self.seq.cmp(&other.seq) {
            std::cmp::Ordering::Less => LsaOrd::Older,
            std::cmp::Ordering::Equal => {
                let self_dead = self.age == MAX_AGE;
                let other_dead = other.age == MAX_AGE;
                match (self_dead, other_dead) {
                    (true, false) => LsaOrd::Newer,
                    (false, true) => LsaOrd::Older,
                    (true, true) | (false, false) => LsaOrd::Same,
                }
            }
            std::cmp::Ordering::Greater => LsaOrd::Newer,
        }
    }

    /// Return the router-id of that LSA. This is either the advertising router of a Router-LSA or
    /// the target of a Summary-LSA or External-LSA
    pub fn target(&self) -> RouterId {
        self.target.unwrap_or(self.router)
    }

    /// Get an `LsaKey` for `self`
    #[inline]
    pub fn key(&self) -> LsaKey {
        LsaKey {
            lsa_type: self.lsa_type,
            router: self.router,
            target: self.target,
        }
    }

    /// Whether the LSA has `age` set to `MAX_AGE`.
    pub fn is_max_age(&self) -> bool {
        self.age == MAX_AGE
    }

    /// Whether the LSA has `seq` set to `MAX_SEQ`.
    pub(crate) fn is_max_seq(&self) -> bool {
        self.seq == MAX_SEQ
    }
}

/// Comparison of two LSAs
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LsaOrd {
    /// Both LSAs are equal
    Same,
    /// The LSA is newer than the other
    Newer,
    /// THe LSA is older than the other.
    Older,
}

impl LsaOrd {
    /// Returns `true` if `self` is `Self::Newer`.
    pub fn is_newer(&self) -> bool {
        matches!(self, Self::Newer)
    }

    /// Returns `true` if `self` is `Self::Older`.
    pub fn is_older(&self) -> bool {
        matches!(self, Self::Older)
    }

    /// Returns `true` if `self` is `Self::Same`.
    pub fn is_same(&self) -> bool {
        matches!(self, Self::Same)
    }
}

impl From<std::cmp::Ordering> for LsaOrd {
    fn from(value: std::cmp::Ordering) -> Self {
        match value {
            std::cmp::Ordering::Less => Self::Older,
            std::cmp::Ordering::Equal => Self::Same,
            std::cmp::Ordering::Greater => Self::Newer,
        }
    }
}

impl From<LsaOrd> for std::cmp::Ordering {
    fn from(value: LsaOrd) -> Self {
        match value {
            LsaOrd::Older => Self::Less,
            LsaOrd::Same => Self::Equal,
            LsaOrd::Newer => Self::Greater,
        }
    }
}

impl PartialOrd for LsaHeader {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if self.key() == other.key() {
            Some(self.compare(other).into())
        } else {
            None
        }
    }
}

impl PartialOrd for Lsa {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if self.key() == other.key() {
            Some(self.compare(other).into())
        } else {
            None
        }
    }
}

/// A single LSA
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Lsa {
    /// The LSA Header
    pub header: LsaHeader,
    /// The LSA data
    pub data: LsaData,
}

impl Lsa {
    /// Get an `LsaKey` for `self`
    #[inline]
    pub fn key(&self) -> LsaKey {
        self.header.key()
    }

    /// Whether the LSA has `age` set to `MAX_AGE`.
    pub fn is_max_age(&self) -> bool {
        self.header.is_max_age()
    }

    /// Whether the LSA has `seq` set to `MAX_SEQ`.
    pub(crate) fn is_max_seq(&self) -> bool {
        self.header.is_max_seq()
    }

    /// Compare two LSAs to determine which one is newer.
    pub fn compare(&self, other: &Self) -> LsaOrd {
        self.header.compare(&other.header)
    }

    /// Return `true` if the LSA type is a `LsaType::Router`.
    #[inline(always)]
    pub fn is_router(&self) -> bool {
        self.header.is_router()
    }

    /// Return `true` if the LSA type is a `LsaType::Summary`.
    #[inline(always)]
    pub fn is_summary(&self) -> bool {
        self.header.is_summary()
    }

    /// Return `true` if the LSA type is a `LsaType::External`.
    #[inline(always)]
    pub fn is_external(&self) -> bool {
        self.header.is_external()
    }

    /// Return the router-id of that LSA. This is either the advertising router of a Router-LSA or
    /// the target of a Summary-LSA or External-LSA
    pub fn target(&self) -> RouterId {
        self.header.target.unwrap_or(self.header.router)
    }
}

/// The data associated with a specific LsaHeader. This structure is dependent on the Lsa Type.
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum LsaData {
    /// Type 1 Router-LSA, describing a set of outgoing edges of the advertising router.
    Router(Vec<RouterLsaLink>),
    /// Type 3 Summary-LSA, describing the cost from the advertising router to the area-external
    /// router
    Summary(NotNan<LinkWeight>),
    /// Type 5 External-LSA, describing the cost from the advertising router to the external router
    /// (usually 0)
    External(NotNan<LinkWeight>),
}

impl LsaData {
    /// Get the data of the RouterLSA or `None`.
    pub fn router(&self) -> Option<&Vec<RouterLsaLink>> {
        match self {
            Self::Router(links) => Some(links),
            _ => None,
        }
    }

    /// Get the data of the SummaryLSA, or `None`.
    pub fn summary(&self) -> Option<NotNan<LinkWeight>> {
        match self {
            Self::Summary(w) => Some(*w),
            _ => None,
        }
    }

    /// Get the data of the ExternalLSA, or `None`.
    pub fn external(&self) -> Option<NotNan<LinkWeight>> {
        match self {
            Self::External(w) => Some(*w),
            _ => None,
        }
    }

    /// Get the data of either the SummaryLSA or ExternalLsa, or `None`.
    pub fn summary_external(&self) -> Option<NotNan<LinkWeight>> {
        match self {
            Self::Summary(w) | Self::External(w) => Some(*w),
            _ => None,
        }
    }
}

/// The link type. Currently, we only support point-to-point and virtual links.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum LinkType {
    /// Regular point-to-point link
    PointToPoint = 1,
    /// Virtual link to connect an ABR that is not part of the backbone to the backbone area.
    Virtual = 4,
}

impl LinkType {
    /// Check if the link is a LinkType::PointToPoint
    #[inline(always)]
    pub fn is_p2p(&self) -> bool {
        matches!(self, Self::PointToPoint)
    }

    /// Check if the link is a LinkType::Virtual
    #[inline(always)]
    pub fn is_virtual(&self) -> bool {
        matches!(self, Self::Virtual)
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Copy, Eq, Hash)]
/// A single outgoing link described by a Router-LSA.
pub struct RouterLsaLink {
    /// The link type (either point-to-point or virtual)
    pub link_type: LinkType,
    /// The link destination
    pub target: RouterId,
    /// the outgoing weight of the link
    pub weight: NotNan<LinkWeight>,
}

impl RouterLsaLink {
    /// Check if the link is a LinkType::PointToPoint
    #[inline(always)]
    pub fn is_p2p(&self) -> bool {
        self.link_type.is_p2p()
    }

    /// Check if the link is a LinkType::Virtual
    #[inline(always)]
    pub fn is_virtual(&self) -> bool {
        self.link_type.is_virtual()
    }
}

impl<'n, P: Prefix, Q, Ospf: OspfImpl> NetworkFormatter<'n, P, Q, Ospf> for LsaHeader {
    fn fmt(&self, net: &'n Network<P, Q, Ospf>) -> String {
        let max_age = if self.is_max_age() { " MaxAge" } else { "" };
        match self.lsa_type {
            LsaType::Router => format!(
                "RouterLSA({} [seq={}]{})",
                self.router.fmt(net),
                self.seq,
                max_age
            ),
            LsaType::Summary => format!(
                "SummaryLSA({} --> {} [seq={}]{})",
                self.router.fmt(net),
                self.target.unwrap().fmt(net),
                self.seq,
                max_age
            ),
            LsaType::External => format!(
                "ExternalLSA({} --> {} [seq={}]{})",
                self.router.fmt(net),
                self.target.unwrap().fmt(net),
                self.seq,
                max_age
            ),
        }
    }
}

impl std::fmt::Debug for LsaHeader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let max_age = if self.is_max_age() { " MaxAge" } else { "" };
        match self.lsa_type {
            LsaType::Router => write!(
                f,
                "RouterLSA({} [seq={}]{})",
                self.router.index(),
                self.seq,
                max_age
            ),
            LsaType::Summary => write!(
                f,
                "SummaryLSA({} --> {} [seq={}]{})",
                self.router.index(),
                self.target.unwrap().index(),
                self.seq,
                max_age
            ),
            LsaType::External => write!(
                f,
                "ExternalLSA({} --> {} [seq={}]{})",
                self.router.index(),
                self.target.unwrap().index(),
                self.seq,
                max_age
            ),
        }
    }
}

impl<'n, P: Prefix, Q, Ospf: OspfImpl> NetworkFormatter<'n, P, Q, Ospf> for LsaData {
    fn fmt(&self, net: &'n Network<P, Q, Ospf>) -> String {
        match self {
            LsaData::Router(x) => format!("{{{}}}", x.iter().map(|x| x.fmt(net)).join(", ")),
            LsaData::Summary(weight) => format!("{weight}"),
            LsaData::External(weight) => format!("{weight}"),
        }
    }
}

impl std::fmt::Debug for LsaData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LsaData::Router(x) => {
                write!(f, "{{{}}}", x.iter().map(|x| format!("{x:?}")).join(", "))
            }
            LsaData::Summary(weight) => write!(f, "{weight}"),
            LsaData::External(weight) => write!(f, "{weight}"),
        }
    }
}

impl<'n, P: Prefix, Q, Ospf: OspfImpl> NetworkFormatter<'n, P, Q, Ospf> for Lsa {
    fn fmt(&self, net: &'n Network<P, Q, Ospf>) -> String {
        format!("{} => {}", self.header.fmt(net), self.data.fmt(net))
    }
}

impl std::fmt::Debug for Lsa {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?} => {:?}", self.header, self.data)
    }
}

impl<'n, P: Prefix, Q, Ospf: OspfImpl> NetworkFormatter<'n, P, Q, Ospf> for RouterLsaLink {
    fn fmt(&self, net: &'n Network<P, Q, Ospf>) -> String {
        let ty = match self.link_type {
            LinkType::PointToPoint => "",
            LinkType::Virtual => " [v]",
        };
        format!("{}: {}{}", self.target.fmt(net), self.weight, ty)
    }
}

impl std::fmt::Debug for RouterLsaLink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ty = match self.link_type {
            LinkType::PointToPoint => "",
            LinkType::Virtual => " [v]",
        };
        write!(f, "{}: {}{}", self.target.index(), self.weight, ty)
    }
}

/// A key used to identify a specific LSA
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct LsaKey {
    /// The type of LSA
    pub lsa_type: LsaType,
    /// The advertising router
    pub router: RouterId,
    /// Target router, only valid for `LsaType::Summary` and `LsaType::External`.
    pub target: Option<RouterId>,
}

impl LsaKey {
    /// Create a new RouterLSA key.
    pub fn router(router: RouterId) -> Self {
        Self {
            lsa_type: LsaType::Router,
            router,
            target: None,
        }
    }

    /// Create a new SummaryLSA key.
    pub fn summary(router: RouterId, target: RouterId) -> Self {
        Self {
            lsa_type: LsaType::Summary,
            router,
            target: Some(target),
        }
    }

    /// Create a new ExternalLSA key.
    pub fn external(router: RouterId, target: RouterId) -> Self {
        Self {
            lsa_type: LsaType::External,
            router,
            target: Some(target),
        }
    }

    /// Return `true` if the LSA type is a `LsaType::Router`.
    #[inline(always)]
    pub fn is_router(&self) -> bool {
        self.lsa_type.is_router()
    }

    /// Return `true` if the LSA type is a `LsaType::Summary`.
    #[inline(always)]
    pub fn is_summary(&self) -> bool {
        self.lsa_type.is_summary()
    }

    /// Return `true` if the LSA type is a `LsaType::External`.
    #[inline(always)]
    pub fn is_external(&self) -> bool {
        self.lsa_type.is_external()
    }

    /// Return the router-id of that LSA. This is either the advertising router of a Router-LSA or
    /// the target of a Summary-LSA or External-LSA
    pub fn target(&self) -> RouterId {
        self.target.unwrap_or(self.router)
    }
}

impl std::hash::Hash for LsaKey {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.router.hash(state);
        self.target.hash(state);
    }
}

impl From<LsaHeader> for LsaKey {
    fn from(value: LsaHeader) -> Self {
        value.key()
    }
}

impl From<&LsaHeader> for LsaKey {
    fn from(value: &LsaHeader) -> Self {
        value.key()
    }
}

impl From<Lsa> for LsaKey {
    fn from(value: Lsa) -> Self {
        value.key()
    }
}

impl From<&Lsa> for LsaKey {
    fn from(value: &Lsa) -> Self {
        value.key()
    }
}

impl<'n, P: Prefix, Q, Ospf: OspfImpl> NetworkFormatter<'n, P, Q, Ospf> for LsaKey {
    fn fmt(&self, net: &'n Network<P, Q, Ospf>) -> String {
        match self.lsa_type {
            LsaType::Router => format!("RouterLSA({})", self.router.fmt(net),),
            LsaType::Summary => format!(
                "SummaryLSA({} --> {})",
                self.router.fmt(net),
                self.target.unwrap().fmt(net),
            ),
            LsaType::External => format!(
                "ExternalLSA({} --> {})",
                self.router.fmt(net),
                self.target.unwrap().fmt(net),
            ),
        }
    }
}

impl std::fmt::Debug for LsaKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.lsa_type {
            LsaType::Router => write!(f, "RouterLSA({})", self.router.index(),),
            LsaType::Summary => write!(
                f,
                "SummaryLSA({} --> {})",
                self.router.index(),
                self.target.unwrap().index(),
            ),
            LsaType::External => write!(
                f,
                "ExternalLSA({} --> {})",
                self.router.index(),
                self.target.unwrap().index(),
            ),
        }
    }
}