bgpkit_commons/lib.rs
1//! # Overview
2//!
3//! `bgpkit-commons` is a library for common BGP-related data and functions with a lazy-loading
4//! architecture. Each module can be independently enabled via feature flags, allowing for minimal builds.
5//!
6//! ## Quick Start
7//!
8//! Add `bgpkit-commons` to your `Cargo.toml`:
9//!
10//! ```toml
11//! [dependencies]
12//! bgpkit-commons = "0.10"
13//! ```
14//!
15//! All modules follow the same pattern: create a [`BgpkitCommons`] instance, call a `load_xxx()`
16//! method to fetch data, then use `xxx_yyy()` methods to access it.
17//!
18//! ```rust
19//! # #[cfg(feature = "bogons")]
20//! # fn main() {
21//! use bgpkit_commons::BgpkitCommons;
22//!
23//! let mut commons = BgpkitCommons::new();
24//! commons.load_bogons().unwrap();
25//!
26//! if let Ok(is_bogon) = commons.bogons_match("23456") {
27//! println!("ASN 23456 is a bogon: {}", is_bogon);
28//! }
29//! # }
30//! # #[cfg(not(feature = "bogons"))]
31//! # fn main() {}
32//! ```
33//!
34//! ## Modules
35//!
36//! ### [`asinfo`] — Autonomous System Information
37//!
38//! Feature: `asinfo` | Sources: RIPE NCC, CAIDA as2org, APNIC population, IIJ IHR hegemony, PeeringDB
39//!
40//! - Load: `load_asinfo(as2org, population, hegemony, peeringdb)`, `load_asinfo_cached()`, `load_asinfo_with(builder)`
41//! - Access: `asinfo_get(asn)`, `asinfo_all()`, `asinfo_are_siblings(asn1, asn2)`
42//! - AS name resolution, country mapping, organization data, population statistics, hegemony scores
43//!
44//! ### [`as2rel`] — AS Relationship Data
45//!
46//! Feature: `as2rel` | Source: BGPKIT AS relationship inference
47//!
48//! - Load: `load_as2rel()`
49//! - Access: `as2rel_lookup(asn1, asn2)`
50//! - Provider-customer, peer-to-peer, and sibling relationships between ASes
51//!
52//! ### [`bogons`] — Bogon Detection
53//!
54//! Feature: `bogons` | Source: IANA special registries (IPv4, IPv6, ASN)
55//!
56//! - Load: `load_bogons()`
57//! - Access: `bogons_match(input)`, `bogons_match_prefix(prefix)`, `bogons_match_asn(asn)`, `get_bogon_prefixes()`, `get_bogon_asns()`
58//! - Detect invalid/reserved IP prefixes and ASNs that shouldn't appear in routing
59//!
60//! ### [`countries`] — Country Information
61//!
62//! Feature: `countries` | Source: GeoNames geographical database
63//!
64//! - Load: `load_countries()`
65//! - Access: `country_by_code(code)`, `country_by_code3(code)`, `country_by_name(name)`, `country_all()`
66//! - ISO country code to name mapping and geographical information
67//!
68//! ### [`mrt_collectors`] — MRT Collector Metadata
69//!
70//! Feature: `mrt_collectors` | Sources: RouteViews and RIPE RIS official APIs
71//!
72//! - Load: `load_mrt_collectors()`, `load_mrt_collector_peers()`
73//! - Access: `mrt_collectors_all()`, `mrt_collectors_by_name(name)`, `mrt_collectors_by_country(country)`, `mrt_collector_peers_all()`, `mrt_collector_peers_full_feed()`
74//! - BGP collector information, peer details, full-feed vs partial-feed classification
75//!
76//! ### [`peeringdb`] — PeeringDB Data
77//!
78//! Feature: `peeringdb` | Source: [PeeringDB API](https://www.peeringdb.com/api/)
79//!
80//! - Load: `Peeringdb::new()` (all tables), `Peeringdb::new_networks_only()` (lightweight)
81//! - Access: `get_network(asn)`, `get_ixp(ix_id)`, `get_ixp_memberships(asn)`, `lookup_ixp_prefix(prefix)`, `get_facility(fac_id)`
82//! - Typed structs mirroring all 12 PeeringDB API endpoints: networks, internet exchanges,
83//! IXP prefixes, IXP membership, facilities, organizations, carriers, and more
84//! - `PeeringdbData` is a type alias for the full `Network` struct (backward compatible)
85//!
86//! ### [`rpki`] — RPKI Validation
87//!
88//! Feature: `rpki` | Sources: Cloudflare (real-time), RIPE NCC historical, RPKIviews historical, RPKISPOOL historical
89//!
90//! - Load: `load_rpki(optional_date)`, `load_rpki_historical(date, source)`, `load_rpki_from_files(urls, source, date)`
91//! - Poll: `RpkiTrie::from_cloudflare_conditional(etag, last_modified)` returns `Ok(None)` on `304 Not Modified`
92//! - Access: `rpki_validate(asn, prefix)`, `rpki_validate_check_expiry(asn, prefix, timestamp)`, `rpki_lookup_by_prefix(prefix)`, `rpki_lookup_aspa(customer_asn)`
93//! - Route Origin Authorization (ROA) and ASPA validation, supports real-time and historical sources
94//! - Poll current Cloudflare data with `RpkiTrie::from_cloudflare_conditional`, retaining the returned
95//! [`rpki::RpkiLoad`] validators and keeping the existing trie when the result is `Ok(None)`.
96//! - `BgpkitCommons::reload()` performs a full reload; it does not use validators or provide an atomic
97//! poll-and-swap operation.
98//!
99//! ## Examples
100//!
101//! ### Loading multiple modules
102//!
103//! ```rust
104//! # #[cfg(all(feature = "asinfo", feature = "countries"))]
105//! # fn main() {
106//! use bgpkit_commons::BgpkitCommons;
107//!
108//! let mut commons = BgpkitCommons::new();
109//! commons.load_asinfo(false, false, false, false).unwrap();
110//! commons.load_countries().unwrap();
111//!
112//! if let Ok(Some(asinfo)) = commons.asinfo_get(13335) {
113//! println!("AS13335: {} ({})", asinfo.name, asinfo.country);
114//! }
115//! # }
116//! # #[cfg(not(all(feature = "asinfo", feature = "countries")))]
117//! # fn main() {}
118//! ```
119//!
120//! ### Using AsInfoBuilder
121//!
122//! ```rust
123//! # #[cfg(feature = "asinfo")]
124//! # fn main() {
125//! use bgpkit_commons::BgpkitCommons;
126//!
127//! let mut commons = BgpkitCommons::new();
128//! let builder = commons.asinfo_builder()
129//! .with_as2org()
130//! .with_peeringdb();
131//! commons.load_asinfo_with(builder).unwrap();
132//!
133//! if let Ok(are_siblings) = commons.asinfo_are_siblings(13335, 132892) {
134//! println!("AS13335 and AS132892 are siblings: {}", are_siblings);
135//! }
136//! # }
137//! # #[cfg(not(feature = "asinfo"))]
138//! # fn main() {}
139//! ```
140//!
141//! ### Loading historical RPKI data
142//!
143//! ```rust,no_run
144//! # #[cfg(feature = "rpki")]
145//! # fn main() {
146//! use bgpkit_commons::BgpkitCommons;
147//! use bgpkit_commons::rpki::{HistoricalRpkiSource, RpkiViewsCollector};
148//! use chrono::NaiveDate;
149//!
150//! let mut commons = BgpkitCommons::new();
151//! let date = NaiveDate::from_ymd_opt(2024, 1, 4).unwrap();
152//!
153//! // Load from RIPE NCC historical archives
154//! commons.load_rpki_historical(date, HistoricalRpkiSource::Ripe).unwrap();
155//!
156//! // Or load from RPKIviews collectors
157//! let source = HistoricalRpkiSource::RpkiViews(RpkiViewsCollector::KerfuffleNet);
158//! commons.load_rpki_historical(date, source).unwrap();
159//!
160//! // List available files for a date
161//! let files = commons.list_rpki_files(date, HistoricalRpkiSource::Ripe).unwrap();
162//! # }
163//! # #[cfg(not(feature = "rpki"))]
164//! # fn main() {}
165//! ```
166//!
167//! ### Direct module access
168//!
169//! Modules can also be used directly without `BgpkitCommons`:
170//!
171//! ```rust
172//! # #[cfg(feature = "bogons")]
173//! # fn main() {
174//! use bgpkit_commons::bogons::Bogons;
175//! let bogons = Bogons::new().unwrap();
176//! # }
177//! # #[cfg(not(feature = "bogons"))]
178//! # fn main() {}
179//! ```
180//!
181//! ## Feature Flags
182//!
183//! | Feature | Description |
184//! |---------|-------------|
185//! | `asinfo` | AS information: names, countries, organizations, population, hegemony |
186//! | `as2rel` | AS relationship data |
187//! | `bogons` | Bogon prefix and ASN detection |
188//! | `countries` | Country information lookup |
189//! | `mrt_collectors` | MRT collector metadata |
190//! | `peeringdb` | PeeringDB API data (networks, IXPs, facilities, organizations) |
191//! | `rpki` | RPKI validation (ROA and ASPA) |
192//! | `all` *(default)* | Enables all modules |
193//!
194//! For a minimal build:
195//!
196//! ```toml
197//! [dependencies]
198//! bgpkit-commons = { version = "0.10", default-features = false, features = ["bogons", "countries"] }
199//! ```
200
201#![doc(
202 html_logo_url = "https://raw.githubusercontent.com/bgpkit/assets/main/logos/icon-transparent.png",
203 html_favicon_url = "https://raw.githubusercontent.com/bgpkit/assets/main/logos/favicon.ico"
204)]
205
206#[cfg(feature = "as2rel")]
207pub mod as2rel;
208#[cfg(feature = "asinfo")]
209pub mod asinfo;
210#[cfg(feature = "bogons")]
211pub mod bogons;
212#[cfg(feature = "countries")]
213pub mod countries;
214#[cfg(feature = "mrt_collectors")]
215pub mod mrt_collectors;
216#[cfg(feature = "peeringdb")]
217pub mod peeringdb;
218#[cfg(feature = "rpki")]
219pub mod rpki;
220
221pub mod errors;
222
223// Re-export error types for convenience
224pub use errors::{BgpkitCommonsError, Result};
225
226/// Trait for modules that support lazy loading and reloading of data
227pub trait LazyLoadable {
228 /// Reload the module's data from its external sources
229 fn reload(&mut self) -> Result<()>;
230
231 /// Check if the module's data is currently loaded
232 fn is_loaded(&self) -> bool;
233
234 /// Get a description of the module's current loading status
235 fn loading_status(&self) -> &'static str;
236}
237
238#[derive(Default)]
239pub struct BgpkitCommons {
240 #[cfg(feature = "countries")]
241 countries: Option<crate::countries::Countries>,
242 #[cfg(feature = "rpki")]
243 rpki_trie: Option<crate::rpki::RpkiTrie>,
244 #[cfg(feature = "mrt_collectors")]
245 mrt_collectors: Option<Vec<crate::mrt_collectors::MrtCollector>>,
246 #[cfg(feature = "mrt_collectors")]
247 mrt_collector_peers: Option<Vec<crate::mrt_collectors::MrtCollectorPeer>>,
248 #[cfg(feature = "bogons")]
249 bogons: Option<crate::bogons::Bogons>,
250 #[cfg(feature = "asinfo")]
251 asinfo: Option<crate::asinfo::AsInfoUtils>,
252 #[cfg(feature = "as2rel")]
253 as2rel: Option<crate::as2rel::As2relBgpkit>,
254}
255
256impl BgpkitCommons {
257 pub fn new() -> Self {
258 Self::default()
259 }
260
261 /// Reload all data sources that are already loaded
262 pub fn reload(&mut self) -> Result<()> {
263 #[cfg(feature = "countries")]
264 if self.countries.is_some() {
265 self.load_countries()?;
266 }
267 #[cfg(feature = "rpki")]
268 if let Some(rpki) = self.rpki_trie.as_mut() {
269 rpki.reload()?;
270 }
271 #[cfg(feature = "mrt_collectors")]
272 if self.mrt_collectors.is_some() {
273 self.load_mrt_collectors()?;
274 }
275 #[cfg(feature = "mrt_collectors")]
276 if self.mrt_collector_peers.is_some() {
277 self.load_mrt_collector_peers()?;
278 }
279 #[cfg(feature = "bogons")]
280 if self.bogons.is_some() {
281 self.load_bogons()?;
282 }
283 #[cfg(feature = "asinfo")]
284 if let Some(asinfo) = self.asinfo.as_mut() {
285 asinfo.reload()?;
286 }
287 #[cfg(feature = "as2rel")]
288 if self.as2rel.is_some() {
289 self.load_as2rel()?;
290 }
291
292 Ok(())
293 }
294
295 /// Get loading status for all available modules
296 pub fn loading_status(&self) -> Vec<(&'static str, &'static str)> {
297 #[allow(unused_mut)] // mut needed when any features are enabled
298 let mut status = Vec::new();
299
300 #[cfg(feature = "countries")]
301 if let Some(ref countries) = self.countries {
302 status.push(("countries", countries.loading_status()));
303 } else {
304 status.push(("countries", "Countries data not loaded"));
305 }
306
307 #[cfg(feature = "bogons")]
308 if let Some(ref bogons) = self.bogons {
309 status.push(("bogons", bogons.loading_status()));
310 } else {
311 status.push(("bogons", "Bogons data not loaded"));
312 }
313
314 #[cfg(feature = "rpki")]
315 if let Some(ref rpki) = self.rpki_trie {
316 status.push(("rpki", rpki.loading_status()));
317 } else {
318 status.push(("rpki", "RPKI data not loaded"));
319 }
320
321 #[cfg(feature = "asinfo")]
322 if let Some(ref asinfo) = self.asinfo {
323 status.push(("asinfo", asinfo.loading_status()));
324 } else {
325 status.push(("asinfo", "ASInfo data not loaded"));
326 }
327
328 #[cfg(feature = "as2rel")]
329 if let Some(ref as2rel) = self.as2rel {
330 status.push(("as2rel", as2rel.loading_status()));
331 } else {
332 status.push(("as2rel", "AS2Rel data not loaded"));
333 }
334
335 #[cfg(feature = "mrt_collectors")]
336 {
337 if self.mrt_collectors.is_some() {
338 status.push(("mrt_collectors", "MRT collectors data loaded"));
339 } else {
340 status.push(("mrt_collectors", "MRT collectors data not loaded"));
341 }
342
343 if self.mrt_collector_peers.is_some() {
344 status.push(("mrt_collector_peers", "MRT collector peers data loaded"));
345 } else {
346 status.push(("mrt_collector_peers", "MRT collector peers data not loaded"));
347 }
348 }
349
350 status
351 }
352
353 /// Load countries data
354 #[cfg(feature = "countries")]
355 pub fn load_countries(&mut self) -> Result<()> {
356 self.countries = Some(crate::countries::Countries::new()?);
357 Ok(())
358 }
359
360 /// Load RPKI data from Cloudflare (real-time) or historical archives
361 ///
362 /// - If `date_opt` is `None`, loads real-time data from Cloudflare
363 /// - If `date_opt` is `Some(date)`, loads historical data from RIPE NCC by default
364 ///
365 /// For more control over the data source, use `load_rpki_historical()` instead.
366 #[cfg(feature = "rpki")]
367 pub fn load_rpki(&mut self, date_opt: Option<chrono::NaiveDate>) -> Result<()> {
368 if let Some(date) = date_opt {
369 self.rpki_trie = Some(rpki::RpkiTrie::from_ripe_historical(date)?);
370 } else {
371 self.rpki_trie = Some(rpki::RpkiTrie::from_cloudflare()?);
372 }
373 Ok(())
374 }
375
376 /// Load RPKI data from a specific historical data source
377 ///
378 /// This allows you to choose between RIPE NCC and RPKIviews for historical data.
379 ///
380 /// # Example
381 ///
382 /// ```rust,no_run
383 /// use bgpkit_commons::BgpkitCommons;
384 /// use bgpkit_commons::rpki::{HistoricalRpkiSource, RpkiViewsCollector};
385 /// use chrono::NaiveDate;
386 ///
387 /// let mut commons = BgpkitCommons::new();
388 /// let date = NaiveDate::from_ymd_opt(2024, 1, 4).unwrap();
389 ///
390 /// // Load from RIPE NCC
391 /// commons.load_rpki_historical(date, HistoricalRpkiSource::Ripe).unwrap();
392 ///
393 /// // Or load from RPKIviews
394 /// let source = HistoricalRpkiSource::RpkiViews(RpkiViewsCollector::KerfuffleNet);
395 /// commons.load_rpki_historical(date, source).unwrap();
396 /// ```
397 #[cfg(feature = "rpki")]
398 pub fn load_rpki_historical(
399 &mut self,
400 date: chrono::NaiveDate,
401 source: rpki::HistoricalRpkiSource,
402 ) -> Result<()> {
403 match source {
404 rpki::HistoricalRpkiSource::Ripe => {
405 self.rpki_trie = Some(rpki::RpkiTrie::from_ripe_historical(date)?);
406 }
407 rpki::HistoricalRpkiSource::RpkiViews(collector) => {
408 self.rpki_trie = Some(rpki::RpkiTrie::from_rpkiviews(collector, date)?);
409 }
410 rpki::HistoricalRpkiSource::RpkiSpools(collector) => {
411 self.rpki_trie = Some(rpki::RpkiTrie::from_rpkispools(collector, date)?);
412 }
413 }
414 Ok(())
415 }
416
417 /// Load RPKI data from specific file URLs
418 ///
419 /// This allows loading from specific archive files, which is useful when you want
420 /// to process multiple files or use specific timestamps.
421 ///
422 /// # Arguments
423 ///
424 /// * `urls` - A slice of URLs pointing to RPKI data files
425 /// * `source` - The type of data source (RIPE, RPKIviews, or RPKISPOOL) - determines how files are parsed
426 /// * `date` - Optional date to associate with the loaded data
427 ///
428 /// # Example
429 ///
430 /// ```rust,no_run
431 /// use bgpkit_commons::BgpkitCommons;
432 /// use bgpkit_commons::rpki::HistoricalRpkiSource;
433 ///
434 /// let mut commons = BgpkitCommons::new();
435 /// let urls = vec![
436 /// "https://example.com/rpki-20240104T144128Z.tgz".to_string(),
437 /// ];
438 /// commons.load_rpki_from_files(&urls, HistoricalRpkiSource::RpkiViews(
439 /// bgpkit_commons::rpki::RpkiViewsCollector::KerfuffleNet
440 /// ), None).unwrap();
441 /// ```
442 #[cfg(feature = "rpki")]
443 pub fn load_rpki_from_files(
444 &mut self,
445 urls: &[String],
446 source: rpki::HistoricalRpkiSource,
447 date: Option<chrono::NaiveDate>,
448 ) -> Result<()> {
449 match source {
450 rpki::HistoricalRpkiSource::Ripe => {
451 self.rpki_trie = Some(rpki::RpkiTrie::from_ripe_files(urls, date)?);
452 }
453 rpki::HistoricalRpkiSource::RpkiViews(_) => {
454 self.rpki_trie = Some(rpki::RpkiTrie::from_rpkiviews_files(urls, date)?);
455 }
456 rpki::HistoricalRpkiSource::RpkiSpools(_) => {
457 // For RPKISPOOL, each URL is a tar.zst archive; load the first one
458 if let Some(url) = urls.first() {
459 self.rpki_trie = Some(rpki::RpkiTrie::from_rpkispools_url(url, date)?);
460 }
461 }
462 }
463 Ok(())
464 }
465
466 /// List available RPKI files for a given date from a specific source
467 ///
468 /// # Example
469 ///
470 /// ```rust,no_run
471 /// use bgpkit_commons::BgpkitCommons;
472 /// use bgpkit_commons::rpki::{HistoricalRpkiSource, RpkiViewsCollector};
473 /// use chrono::NaiveDate;
474 ///
475 /// let commons = BgpkitCommons::new();
476 /// let date = NaiveDate::from_ymd_opt(2024, 1, 4).unwrap();
477 ///
478 /// // List files from RIPE NCC
479 /// let ripe_files = commons.list_rpki_files(date, HistoricalRpkiSource::Ripe).unwrap();
480 ///
481 /// // List files from RPKIviews
482 /// let source = HistoricalRpkiSource::RpkiViews(RpkiViewsCollector::KerfuffleNet);
483 /// let rpkiviews_files = commons.list_rpki_files(date, source).unwrap();
484 /// ```
485 #[cfg(feature = "rpki")]
486 pub fn list_rpki_files(
487 &self,
488 date: chrono::NaiveDate,
489 source: rpki::HistoricalRpkiSource,
490 ) -> Result<Vec<rpki::RpkiFile>> {
491 match source {
492 rpki::HistoricalRpkiSource::Ripe => rpki::list_ripe_files(date),
493 rpki::HistoricalRpkiSource::RpkiViews(collector) => {
494 rpki::list_rpkiviews_files(collector, date)
495 }
496 rpki::HistoricalRpkiSource::RpkiSpools(collector) => {
497 rpki::list_rpkispools_files(collector, date)
498 }
499 }
500 }
501
502 /// Load MRT mrt_collectors data
503 #[cfg(feature = "mrt_collectors")]
504 pub fn load_mrt_collectors(&mut self) -> Result<()> {
505 self.mrt_collectors = Some(crate::mrt_collectors::get_all_collectors()?);
506 Ok(())
507 }
508
509 /// Load MRT mrt_collectors data
510 #[cfg(feature = "mrt_collectors")]
511 pub fn load_mrt_collector_peers(&mut self) -> Result<()> {
512 self.mrt_collector_peers = Some(crate::mrt_collectors::get_mrt_collector_peers()?);
513 Ok(())
514 }
515
516 /// Load bogons data
517 #[cfg(feature = "bogons")]
518 pub fn load_bogons(&mut self) -> Result<()> {
519 self.bogons = Some(crate::bogons::Bogons::new()?);
520 Ok(())
521 }
522
523 /// Load AS name and country data
524 #[cfg(feature = "asinfo")]
525 pub fn load_asinfo(
526 &mut self,
527 load_as2org: bool,
528 load_population: bool,
529 load_hegemony: bool,
530 load_peeringdb: bool,
531 ) -> Result<()> {
532 self.asinfo = Some(crate::asinfo::AsInfoUtils::new(
533 load_as2org,
534 load_population,
535 load_hegemony,
536 load_peeringdb,
537 )?);
538 Ok(())
539 }
540
541 #[cfg(feature = "asinfo")]
542 pub fn load_asinfo_cached(&mut self) -> Result<()> {
543 self.asinfo = Some(crate::asinfo::AsInfoUtils::new_from_cached()?);
544 Ok(())
545 }
546
547 /// Returns a builder for loading AS information with specific data sources.
548 ///
549 /// This provides a more ergonomic way to configure which data sources to load
550 /// compared to the `load_asinfo()` method with boolean parameters.
551 ///
552 /// # Example
553 ///
554 /// ```rust,no_run
555 /// use bgpkit_commons::BgpkitCommons;
556 ///
557 /// let mut commons = BgpkitCommons::new();
558 /// let builder = commons.asinfo_builder()
559 /// .with_as2org()
560 /// .with_peeringdb();
561 /// commons.load_asinfo_with(builder).unwrap();
562 /// ```
563 #[cfg(feature = "asinfo")]
564 pub fn asinfo_builder(&self) -> crate::asinfo::AsInfoBuilder {
565 crate::asinfo::AsInfoBuilder::new()
566 }
567
568 /// Load AS information using a pre-configured builder.
569 ///
570 /// # Example
571 ///
572 /// ```rust,no_run
573 /// use bgpkit_commons::BgpkitCommons;
574 ///
575 /// let mut commons = BgpkitCommons::new();
576 /// let builder = commons.asinfo_builder()
577 /// .with_as2org()
578 /// .with_hegemony();
579 /// commons.load_asinfo_with(builder).unwrap();
580 /// ```
581 #[cfg(feature = "asinfo")]
582 pub fn load_asinfo_with(&mut self, builder: crate::asinfo::AsInfoBuilder) -> Result<()> {
583 self.asinfo = Some(builder.build()?);
584 Ok(())
585 }
586
587 /// Load AS-level relationship data
588 #[cfg(feature = "as2rel")]
589 pub fn load_as2rel(&mut self) -> Result<()> {
590 self.as2rel = Some(crate::as2rel::As2relBgpkit::new()?);
591 Ok(())
592 }
593}