bgpexplorer 0.2.0

This is a BGP route explorer for routing information database with ability to drill-down routes change history
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
use std::error::Error;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use whois_rust::WhoIs;

/// peer protocol mode
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PeerMode {
    /// bgpexplorer connects to BGP router
    BgpActive,
    /// BGP router connects to bgpexplorer
    BgpPassive,
    /// BMP router connects to bgpexplorer
    BmpPassive,
    /// bgpexplorer connects to BMP router
    BmpActive,
}
/// history store mode variations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HistoryChangeMode {
    /// every update recorded, even duplicates
    EveryUpdate,
    /// history record made only if route attributes is differ
    OnlyDiffer,
}

/// peer
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtoPeer {
    pub routerid: Ipv4Addr,
    pub mode: PeerMode,
    pub peer: Option<SocketAddr>,
    pub protolisten: Option<SocketAddr>,
    pub bgppeeras: u32,
    pub flt_rd: Option<zettabgp::afi::BgpRD>
}
impl ProtoPeer {
    pub fn from_ini(
        svcsection: &std::collections::HashMap<
            std::string::String,
            std::option::Option<std::string::String>,
        >,
    ) -> Result<ProtoPeer, ErrorConfig> {
        if !svcsection.contains_key("mode") {
            return Err(ErrorConfig::from_str("Missing value 'mode'"));
        };
        let mode = match svcsection["mode"] {
            None => {
                return Err(ErrorConfig::from_str(
                    "No mode (bgpactive|bgppassive|bmpactive|bmppassive) specified",
                ));
            }
            Some(ref s) => s,
        };
        let peermode = mode.parse()?;
        let peer: Option<std::net::SocketAddr> = if svcsection.contains_key("peer") {
            match svcsection["peer"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid peer was specified"));
                }
                Some(ref s) => match s.parse() {
                    Err(_e) => {
                        let peerip: std::net::IpAddr = match s.parse() {
                            Err(_) => {
                                return Err(ErrorConfig::from_str("invalid peer was specified"));
                            }
                            Ok(v) => v,
                        };
                        Some(std::net::SocketAddr::new(
                            peerip,
                            if peermode == PeerMode::BmpActive {
                                632
                            } else {
                                179
                            },
                        ))
                    }
                    Ok(a) => Some(a),
                },
            }
        } else {
            if peermode == PeerMode::BgpActive || peermode == PeerMode::BmpActive {
                // fatal error
                return Err(ErrorConfig::from_str("peer was not specified"));
            } else {
                None
            }
        };
        let protolisten: Option<SocketAddr> = if svcsection.contains_key("protolisten") {
            match svcsection["protolisten"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid protolisten was specified"));
                }
                Some(ref s) => match s.parse() {
                    Err(_e) => {
                        let peerip: IpAddr = match s.parse() {
                            Err(_) => {
                                return Err(ErrorConfig::from_str(
                                    "invalid protolisten was specified",
                                ));
                            }
                            Ok(v) => v,
                        };
                        Some(SocketAddr::new(
                            peerip,
                            if peermode == PeerMode::BmpPassive {
                                632
                            } else {
                                179
                            },
                        ))
                    }
                    Ok(a) => Some(a),
                },
            }
        } else {
            if peermode == PeerMode::BgpPassive || peermode == PeerMode::BmpPassive {
                Some(SocketAddr::new(
                    IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
                    if peermode == PeerMode::BmpPassive {
                        632
                    } else {
                        179
                    },
                ))
            } else {
                None
            }
        };
        let routerid: Ipv4Addr = if svcsection.contains_key("routerid") {
            match svcsection["routerid"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid routerid was specified"));
                }
                Some(ref s) => match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid routerid - {}",
                            e
                        )));
                    }
                    Ok(a) => a,
                },
            }
        } else {
            Ipv4Addr::new(1, 1, 1, 1)
        };
        let bgppeeras: u32 = if svcsection.contains_key("peeras") {
            match svcsection["peeras"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid bgppeeras was specified"));
                }
                Some(ref s) => match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid bgp peer as - {}",
                            e
                        )));
                    }
                    Ok(a) => a,
                },
            }
        } else {
            0
        };
        let flt_rd = if svcsection.contains_key("filter_rd") {
            match svcsection["filter_rd"] {
                None => {
                    None
                }
                Some(ref s) => match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid bmp filter_rd - {}",
                            e
                        )));
                    }
                    Ok(a) => Some(a),
                },
            }
        } else {
            Some(zettabgp::afi::BgpRD::new(0,0))
        };
        Ok(ProtoPeer {
            routerid: routerid,
            mode: peermode,
            peer: peer,
            protolisten: protolisten,
            bgppeeras: bgppeeras,
            flt_rd: flt_rd
        })
    }
}

#[derive(Debug, Clone)]
pub struct SvcConfig {
    pub httplisten: std::net::SocketAddr,
    pub httproot: String,
    pub historydepth: usize,
    pub httptimeout: u64,
    pub historymode: HistoryChangeMode,
    pub whoisconfig: WhoIs,
    pub whoisdb: String,
    pub whoisreqtimeout: u64,
    pub whoiscachesecs: i64,
    pub whoisdnses: Vec<std::net::SocketAddr>,
    pub peers: Vec<Arc<ProtoPeer>>,
    pub purge_after_withdraws: u64,
    pub purge_every: chrono::Duration,
}

#[derive(Debug)]
pub enum ErrorConfig {
    Static(&'static str),
    Str(String),
}
impl ErrorConfig {
    pub fn from_str(m: &'static str) -> Self {
        ErrorConfig::Static(m)
    }
    pub fn from_string(m: String) -> Self {
        ErrorConfig::Str(m)
    }
}
impl From<&'static str> for ErrorConfig {
    fn from(m: &'static str) -> Self {
        ErrorConfig::Static(m)
    }
}
impl fmt::Display for ErrorConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ErrorConfig: {}",
            match self {
                ErrorConfig::Static(s) => s,
                ErrorConfig::Str(s) => s.as_str(),
            }
        )
    }
}

impl Error for ErrorConfig {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self)
    }
}

impl FromStr for PeerMode {
    type Err = ErrorConfig;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let sp: Vec<&str> = s.split(' ').collect();
        match sp[0] {
            "bgpactive" => Ok(PeerMode::BgpActive),
            "bgppassive" => Ok(PeerMode::BgpPassive),
            "bmppassive" => Ok(PeerMode::BmpPassive),
            "bmpactive" => Ok(PeerMode::BmpActive),
            _ => Err(ErrorConfig::from_str("invalid mode")),
        }
    }
}

impl FromStr for HistoryChangeMode {
    type Err = ErrorConfig;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let sp: Vec<&str> = s.split(' ').collect();
        match sp[0] {
            "every" => Ok(HistoryChangeMode::EveryUpdate),
            "differ" => Ok(HistoryChangeMode::OnlyDiffer),
            _ => Err(ErrorConfig::from_str("invalid history mode")),
        }
    }
}

impl SvcConfig {
    pub fn from_inifile(inifile: &str) -> Result<SvcConfig, ErrorConfig> {
        let conf = ini!(inifile);
        if !conf.contains_key("main") {
            return Err(ErrorConfig::from_str("Missing section 'main' in ini file"));
        }
        let mainsection = &conf["main"];
        let peers: Vec<Arc<ProtoPeer>> = conf
            .iter()
            .filter(|x| x.0 != "main")
            .filter_map(|x| ProtoPeer::from_ini(x.1).ok())
            .map(|x| Arc::new(x))
            .collect();
        if peers.len() < 1 {
            return Err(ErrorConfig::from_str("No valid peers or listens specified"));
        }
        let httplisten: std::net::SocketAddr = match (if mainsection.contains_key("httplisten") {
            match mainsection["httplisten"] {
                Some(ref s) => s.to_string(),
                None => "0.0.0.0:8080".to_string(),
            }
        } else {
            "0.0.0.0:8080".to_string()
        })
        .parse()
        {
            Ok(sa) => sa,
            Err(e) => {
                return Err(ErrorConfig::from_string(format!(
                    "Invalid httplisten - {}",
                    e
                )));
            }
        };
        let httptimeout = if mainsection.contains_key("httptimeout") {
            match mainsection["httptimeout"] {
                Some(ref s) => s.parse().unwrap_or(120),
                None => 120,
            }
        } else {
            120
        };
        let httproot = if mainsection.contains_key("httproot") {
            match mainsection["httproot"] {
                Some(ref s) => s.to_string(),
                None => "./contrib".to_string(),
            }
        } else {
            "./contrib".to_string()
        };
        let historydepth: usize = if mainsection.contains_key("historydepth") {
            match mainsection["historydepth"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid historydepth was specified"));
                }
                Some(ref s) => match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid historydepth - {}",
                            e
                        )));
                    }
                    Ok(a) => a,
                },
            }
        } else {
            10
        };
        let historymode: HistoryChangeMode = if mainsection.contains_key("historymode") {
            match mainsection["historymode"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid historymode was specified"));
                }
                Some(ref s) => match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid historymode - {}",
                            e
                        )));
                    }
                    Ok(a) => a,
                },
            }
        } else {
            HistoryChangeMode::OnlyDiffer
        };
        let purge_after_withdraws: u64 = if mainsection.contains_key("purge_after_withdraws") {
            match mainsection["purge_after_withdraws"] {
                None => {
                    return Err(ErrorConfig::from_str(
                        "invalid purge_after_withdraws was specified",
                    ));
                }
                Some(ref s) => match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid purge_after_withdraws - {}",
                            e
                        )));
                    }
                    Ok(a) => a,
                },
            }
        } else {
            0
        };
        let purge_every: chrono::Duration = if mainsection.contains_key("purge_every") {
            match mainsection["purge_every"] {
                None => {
                    return Err(ErrorConfig::from_str("invalid purge_every was specified"));
                }
                Some(ref s) => chrono::Duration::seconds(match s.parse() {
                    Err(e) => {
                        return Err(ErrorConfig::from_string(format!(
                            "Invalid purge_every - {}",
                            e
                        )));
                    }
                    Ok(a) => a,
                }),
            }
        } else {
            chrono::Duration::minutes(5)
        };
        let whoisreqtimeout: u64 = if mainsection.contains_key("whois_request_timeout") {
            match mainsection["whois_request_timeout"] {
                Some(ref s) => s.parse().unwrap_or(30),
                None => 30,
            }
        } else {
            30
        };
        let whoiscachesecs: i64 = if mainsection.contains_key("whois_cache_seconds") {
            match mainsection["whois_cache_seconds"] {
                Some(ref s) => s.parse().unwrap_or(1800),
                None => 1800,
            }
        } else {
            1800
        };
        let whois: WhoIs = if mainsection.contains_key("whoisjsonconfig") {
            match mainsection["whoisjsonconfig"] {
                Some(ref s) => WhoIs::from_path(s).unwrap(),
                None => {
                    return Err(ErrorConfig::from_str("Invalid whoisjsonconfig"));
                }
            }
        } else {
            return Err(ErrorConfig::from_str("Invalid whoisjsonconfig"));
        };
        let whoisdb: String = if mainsection.contains_key("whoisdb") {
            match mainsection["whoisdb"] {
                Some(ref s) => s.to_string(),
                None => {
                    return Err(ErrorConfig::from_str("Invalid whoisdb"));
                }
            }
        } else {
            "whoiscache.db".to_string()
        };
        let mut dnses = Vec::<std::net::SocketAddr>::new();
        if mainsection.contains_key("whoisdns") {
            match mainsection["whoisdns"] {
                Some(ref s) => {
                    for sdns in s.as_str().split(',') {
                        match sdns.trim().parse() {
                            Ok(sck) => dnses.push(sck),
                            Err(_) => match (sdns.trim().to_string() + ":53").parse() {
                                Ok(sck) => dnses.push(sck),
                                Err(_) => {
                                    eprintln!("Invalid DNS: {}", sdns);
                                }
                            },
                        }
                    }
                }
                None => {
                    return Err(ErrorConfig::from_str("Invalid whoisdns"));
                }
            }
        };
        if dnses.is_empty() {
            dnses.push(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 53));
        };
        Ok(SvcConfig {
            httplisten: httplisten,
            httptimeout: httptimeout,
            httproot: httproot,
            historydepth: historydepth,
            historymode: historymode,
            whoisconfig: whois,
            whoisdb: whoisdb,
            whoisdnses: dnses,
            whoisreqtimeout: whoisreqtimeout,
            whoiscachesecs: whoiscachesecs,
            purge_after_withdraws: purge_after_withdraws,
            purge_every: purge_every,
            peers: peers,
        })
    }
}