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
#![allow(unused)]
//! This module handles converting MRT records into individual per-prefix BGP elements.
//!
//! Each MRT record may contain reachability information for multiple prefixes. This module breaks
//! down MRT records into corresponding BGP elements, and thus allowing users to more conveniently
//! process BGP information on a per-prefix basis.
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::net::IpAddr;
use bgp_models::prelude::*;
use itertools::Itertools;
use log::warn;
use crate::parser::bgp::messages::parse_bgp_update_message;

pub struct Elementor {
    peer_table: Option<PeerIndexTable>,
}

// use macro_rules! <name of macro>{<Body>}
macro_rules! get_attr_value {
    ($a:tt, $b:expr) => {
        if let Attribute::$a(x) = $b {
            Some(x)
        } else {
            None
        }
    };
}

fn get_relevant_attributes(
    attributes: Vec<Attribute>,
) -> (
    Option<AsPath>,
    Option<AsPath>,
    Option<Origin>,
    Option<IpAddr>,
    Option<u32>,
    Option<u32>,
    Option<Vec<MetaCommunity>>,
    Option<AtomicAggregate>,
    Option<(Asn, IpAddr)>,
    Option<Nlri>,
    Option<Nlri>,
) {
    let mut as_path = None;
    let mut as4_path = None;
    let mut origin = None;
    let mut next_hop = None;
    let mut local_pref = Some(0);
    let mut med = Some(0);
    let mut atomic = Some(AtomicAggregate::NAG);
    let mut aggregator = None;
    let mut announced = None;
    let mut withdrawn = None;

    let mut communities_vec: Vec<MetaCommunity> = vec![];

    for attr in attributes {
        match attr.value {
            AttributeValue::Origin(v) => {origin = Some(v)}
            AttributeValue::AsPath(v) => {as_path = Some(v)}
            AttributeValue::As4Path(v) => {as4_path = Some(v)}
            AttributeValue::NextHop(v) => {next_hop = Some(v)}
            AttributeValue::MultiExitDiscriminator(v) => {med = Some(v)}
            AttributeValue::LocalPreference(v) => {local_pref = Some(v)}
            AttributeValue::AtomicAggregate(v) => {atomic = Some(v)}
            AttributeValue::Communities(v) => {communities_vec.extend(v.into_iter().map(|x| MetaCommunity::Community(x)).collect::<Vec<MetaCommunity>>())}
            AttributeValue::ExtendedCommunities(v) => {communities_vec.extend(v.into_iter().map(|x| MetaCommunity::ExtendedCommunity(x)).collect::<Vec<MetaCommunity>>())}
            AttributeValue::LargeCommunities(v) => {communities_vec.extend(v.into_iter().map(|x| MetaCommunity::LargeCommunity(x)).collect::<Vec<MetaCommunity>>())}
            AttributeValue::Aggregator(v, v2) => {aggregator = Some((v,v2))}
            AttributeValue::MpReachNlri(nlri) => {announced = Some(nlri)}
            AttributeValue::MpUnreachNlri(nlri) => {withdrawn = Some(nlri)}
            AttributeValue::OriginatorId(_) | AttributeValue::Clusters(_)| AttributeValue::Development(_) => {}
        };
    }

    let communities = match communities_vec.len()>0 {
        true => Some(communities_vec),
        false => None,
    };

    (
        as_path,
        as4_path,
        origin,
        next_hop,
        local_pref,
        med,
        communities,
        atomic,
        aggregator,
        announced,
        withdrawn,
    )
}

impl Elementor {
    pub fn new() -> Elementor {
        Elementor { peer_table: None }
    }

    /// Convert a [BgpMessage] to a vector of [BgpElem]s.
    ///
    /// A [BgpMessage] may include `Update`, `Open`, `Notification` or `KeepAlive` messages,
    /// and only `Update` message contains [BgpElem]s.
    pub fn bgp_to_elems(msg: BgpMessage, timestamp: f64, peer_ip: &IpAddr, peer_asn: &Asn) -> Vec<BgpElem> {
        match msg {
            BgpMessage::Update(msg) => {
                Elementor::bgp_update_to_elems(msg, timestamp, peer_ip, peer_asn)
            }
            BgpMessage::Open(_) | BgpMessage::Notification(_) | BgpMessage::KeepAlive(_) => {
                vec![]
            }
        }
    }

    /// Convert a [BgpUpdateMessage] to a vector of [BgpElem]s.
    pub fn bgp_update_to_elems(msg: BgpUpdateMessage, timestamp: f64, peer_ip: &IpAddr, peer_asn: &Asn) -> Vec<BgpElem> {
        let mut elems = vec![];

        let (
            as_path,
            as4_path, // Table dump v1 does not have 4-byte AS number
            origin,
            next_hop,
            local_pref,
            med,
            communities,
            atomic,
            aggregator,
            announced,
            withdrawn,
        ) = get_relevant_attributes(msg.attributes);

        let path = match (as_path, as4_path) {
            (None, None) => None,
            (Some(v), None) => Some(v),
            (None, Some(v)) => Some(v),
            (Some(v1), Some(v2)) => {
                Some(AsPath::merge_aspath_as4path(&v1, &v2).unwrap())
            }
        };

        let origin_asns = match &path {
            None => None,
            Some(p) => p.get_origin()
        };

        elems.extend(msg.announced_prefixes.into_iter().map(|p| BgpElem {
            timestamp: timestamp.clone(),
            elem_type: ElemType::ANNOUNCE,
            peer_ip: peer_ip.clone(),
            peer_asn: peer_asn.clone(),
            prefix: p,
            next_hop: next_hop.clone(),
            as_path: path.clone(),
            origin_asns: origin_asns.clone(),
            origin: origin.clone(),
            local_pref: local_pref.clone(),
            med: med.clone(),
            communities: communities.clone(),
            atomic: atomic.clone(),
            aggr_asn: if let Some(v) = &aggregator {
                Some(v.0.clone())
            } else {
                None
            },
            aggr_ip: if let Some(v) = &aggregator {
                Some(v.1.clone())
            } else {
                None
            },
        }));

        if let Some(nlri) = announced {
            elems.extend(nlri.prefixes.into_iter().map(|p| BgpElem {
                timestamp: timestamp.clone(),
                elem_type: ElemType::ANNOUNCE,
                peer_ip: peer_ip.clone(),
                peer_asn: peer_asn.clone(),
                prefix: p,
                next_hop: next_hop.clone(),
                as_path: path.clone(),
                origin: origin.clone(),
                origin_asns: origin_asns.clone(),
                local_pref: local_pref.clone(),
                med: med.clone(),
                communities: communities.clone(),
                atomic: atomic.clone(),
                aggr_asn: if let Some(v) = &aggregator {
                    Some(v.0.clone())
                } else {
                    None
                },
                aggr_ip: if let Some(v) = &aggregator {
                    Some(v.1.clone())
                } else {
                    None
                },
            }));
        }

        elems.extend(msg.withdrawn_prefixes.into_iter().map(|p| BgpElem {
            timestamp: timestamp.clone(),
            elem_type: ElemType::WITHDRAW,
            peer_ip: peer_ip.clone(),
            peer_asn: peer_asn.clone(),
            prefix: p,
            next_hop: None,
            as_path: None,
            origin: None,
            origin_asns: None,
            local_pref: None,
            med: None,
            communities: None,
            atomic: None,
            aggr_asn: None,
            aggr_ip: None,
        }));
        if let Some(nlri) = withdrawn {
            elems.extend(nlri.prefixes.into_iter().map(|p| BgpElem {
                timestamp: timestamp.clone(),
                elem_type: ElemType::WITHDRAW,
                peer_ip: peer_ip.clone(),
                peer_asn: peer_asn.clone(),
                prefix: p,
                next_hop: None,
                as_path: None,
                origin: None,
                origin_asns: None,
                local_pref: None,
                med: None,
                communities: None,
                atomic: None,
                aggr_asn: None,
                aggr_ip: None,
            }));
        };
        elems
    }


    /// Convert a [MrtRecord] to a vector of [BgpElem]s.
    pub fn record_to_elems(&mut self, record: MrtRecord) -> Vec<BgpElem> {
        let mut elems = vec![];
        let t = record.common_header.timestamp.clone();
        let timestamp :f64 = if let Some(micro) = &record.common_header.microsecond_timestamp {
            let m = (micro.clone() as f64)/1000000.0;
            t as f64 + m
        } else {
            f64::from(t)
        };

        match record.message {
            MrtMessage::TableDumpMessage(msg) => {
                let (
                    as_path,
                    _as4_path, // Table dump v1 does not have 4-byte AS number
                    origin,
                    next_hop,
                    local_pref,
                    med,
                    communities,
                    atomic,
                    aggregator,
                    _announced,
                    _withdrawn,
                ) = get_relevant_attributes(msg.attributes);

                let origin_asns = match &as_path {
                    None => None,
                    Some(p) => p.get_origin()
                };

                elems.push(BgpElem {
                    timestamp: timestamp.clone(),
                    elem_type: ElemType::ANNOUNCE,
                    peer_ip: msg.peer_address,
                    peer_asn: msg.peer_asn,
                    prefix: msg.prefix,
                    next_hop,
                    as_path,
                    origin,
                    origin_asns,
                    local_pref,
                    med,
                    communities,
                    atomic,
                    aggr_asn: if let Some(v) = aggregator {
                        Some(v.0)
                    } else {
                        None
                    },
                    aggr_ip: if let Some(v) = aggregator {
                        Some(v.1)
                    } else {
                        None
                    },
                });
            }

            MrtMessage::TableDumpV2Message(msg) => {
                match msg {
                    TableDumpV2Message::PeerIndexTable(p) => {
                        self.peer_table = Some(p);
                    }
                    TableDumpV2Message::RibAfiEntries(t) => {
                        let prefix = t.prefix.clone();
                        for e in t.rib_entries {
                            let pid = e.peer_index;
                            let peer = self
                                .peer_table
                                .as_ref()
                                .unwrap()
                                .peers_map
                                .get(&(pid as u32))
                                .unwrap();
                            let (
                                as_path,
                                as4_path, // Table dump v1 does not have 4-byte AS number
                                origin,
                                next_hop,
                                local_pref,
                                med,
                                communities,
                                atomic,
                                aggregator,
                                announced,
                                _withdrawn,
                            ) = get_relevant_attributes(e.attributes);

                            let path = match (as_path, as4_path) {
                                (None, None) => None,
                                (Some(v), None) => Some(v),
                                (None, Some(v)) => Some(v),
                                (Some(v1), Some(v2)) => {
                                    Some(AsPath::merge_aspath_as4path(&v1, &v2).unwrap())
                                }
                            };

                            let next = match next_hop {
                                None => {
                                    if let Some(v) = announced {
                                        if let Some(h) = v.next_hop {
                                            match h {
                                                NextHopAddress::Ipv4(v) => {
                                                    Some(IpAddr::from(v.clone()))
                                                }
                                                NextHopAddress::Ipv6(v) => {
                                                    Some(IpAddr::from(v.clone()))
                                                }
                                                NextHopAddress::Ipv6LinkLocal(v, _) => {
                                                    Some(IpAddr::from(v.clone()))
                                                }
                                            }
                                        } else {
                                            None
                                        }
                                    } else {
                                        None
                                    }
                                }
                                Some(v) => Some(v),
                            };


                            let origin_asns = match &path {
                                None => None,
                                Some(p) => p.get_origin()
                            };

                            elems.push(BgpElem {
                                timestamp: timestamp.clone(),
                                elem_type: ElemType::ANNOUNCE,
                                peer_ip: peer.peer_address,
                                peer_asn: peer.peer_asn,
                                prefix: prefix.clone(),
                                next_hop: next,
                                as_path: path,
                                origin,
                                origin_asns,
                                local_pref,
                                med,
                                communities,
                                atomic,
                                aggr_asn: if let Some(v) = aggregator {
                                    Some(v.0)
                                } else {
                                    None
                                },
                                aggr_ip: if let Some(v) = aggregator {
                                    Some(v.1)
                                } else {
                                    None
                                },
                            });
                        }
                    }
                    TableDumpV2Message::RibGenericEntries(_t) => {
                        warn!("to_elem for TableDumpV2Message::RibGenericEntries not yet implemented");
                    }
                }
            }
            MrtMessage::Bgp4Mp(msg) => {
                match msg {
                    Bgp4Mp::Bgp4MpStateChange(_v) | Bgp4Mp::Bgp4MpStateChangeAs4(_v) => {}

                    Bgp4Mp::Bgp4MpMessage(v)
                    | Bgp4Mp::Bgp4MpMessageLocal(v)
                    | Bgp4Mp::Bgp4MpMessageAs4(v)
                    | Bgp4Mp::Bgp4MpMessageAs4Local(v) => {
                        elems.extend(
                            Elementor::bgp_to_elems(v.bgp_message, timestamp, &v.peer_ip, &v.peer_asn)
                        );
                    }
                }
            }
        }
        elems
    }
}

#[inline(always)]
pub fn option_to_string<T>(o: &Option<T>) -> String
where
    T: Display,
{
    if let Some(v) = o {
        v.to_string()
    } else {
        String::new()
    }
}