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
//! [<img alt="github" src="https://img.shields.io/badge/github-rappet/rust__bgpq3-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/rappet/rust_bgpq3)
//! [<img alt="crates.io" src="https://img.shields.io/crates/v/bgpq3.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/bgpq3)
//! [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-bgpq3-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/bgpq3)
//!
//! This library provides a thing wrapper around the [`bgpq3`]/[`bgpq4`] binary.
//!
//! See [`Bgpq3::query_v4`] and [`Bgpq3::query_v6`].
//!
//! ## Example
//!
//! bgpq3 AS-Set
//!
//! ```
//! extern crate bgpq3;
//!
//! pub fn main() {
//!     let networks = bgpq3::Bgpq3::new().query_v6("AS-RAPPET").unwrap();
//!     println!("{:?}", networks);
//! }
//! ```
//!
//! bgpq3 ASN
//!
//! ```
//! extern crate bgpq3;
//!
//! pub fn main() {
//!     let networks = bgpq3::Bgpq3::new().query_v6(207968).unwrap();
//!     println!("{:?}", networks);
//! }
//! ```
//!
//! bgpq4
//!
//! ```ignore
//! extern crate bgpq3;
//! use bgpq3::{Bgpq3, Version};
//!
//! pub fn main() {
//!     let bgpq4 = Bgpq3::builder().version(Version::Bgpq4).build();
//!     let networks = bgpq4.query_v6("AS-RAPPET").unwrap();
//!     println!("{:?}", networks);
//! }
//! ```
//!
//! ## Feature flags
//!
//! - `tokio` for async process invocation.
//!
//! [`bgpq3`]: https://github.com/snar/bgpq3
//! [`bgpq4`]: https://github.com/bgp/bgpq4

extern crate serde;
extern crate serde_json;
extern crate thiserror;
extern crate ipnetwork;
#[cfg(feature = "tokio")]
extern crate tokio;

use thiserror::Error;
use ipnetwork::{Ipv4Network, Ipv6Network, IpNetworkError};
use serde::Deserialize;
use std::process::Command;

/// A wrapper around the `bgpq3` or `bgpq4` binary.
///
/// The default wrapper can be crated with [`Bgpq3::new`].
/// A custom wrapper can be build using the [`Bgpq3Settings`] builder.
///
/// The binaries have to be located in the `$PATH` environment variable for the default configuration.
///
/// # Example
///
/// Default wrapper using `bgpq3`:
///
/// ```
/// use bgpq3::Bgpq3;
///
/// let bgpq3 = Bgpq3::new();
/// ```
///
/// Custom wrapper using the recommended bgpq4 fork:
///
/// ```
/// use bgpq3::{Bgpq3, Version};
///
/// let bgpq4 = Bgpq3::builder().version(Version::Bgpq4).build();
/// ```
#[derive(Default, Clone)]
pub struct Bgpq3 {
    settings: Bgpq3Settings,
}

impl Bgpq3 {
    /// Creates a new [`Bgpq3`] wrapper with the default settings.
    pub fn new() -> Bgpq3 {
        Default::default()
    }

    /// Creates a new wrapper with bgpq3 as a backend.
    pub fn bgpq3() -> Bgpq3 {
        Bgpq3::builder().version(Version::Bgpq3).build()
    }

    /// Creates a new wrapper with bgpq4 as a backend.
    pub fn bgpq4() -> Bgpq3 {
        Bgpq3::builder().version(Version::Bgpq4).build()
    }

    /// Creates a new [`Bgpq3`] builder [`Bgpq3Settings`].
    pub fn builder() -> Bgpq3Settings {
        Bgpq3Settings::new()
    }

    /// Creates a new [`Bgpq3`] from a builder..
    pub fn with_settings(settings: &Bgpq3Settings) -> Bgpq3 {
        Bgpq3 {
            settings: settings.clone(),
        }
    }

    /// Queries a list of IPv4 networks.
    pub fn query_v4(&self, query: impl Into<Bgpq3Query>) -> Bgpq3Result<Vec<Ipv4Network>> {
        let output = query.into()
            .build_command(&self.settings, false)
            .output()?;
        if !output.status.success() {
            return Err(Bgpq3Error::StatusNotSuccess);
        }
        let deserialized: Bgpq3Output = serde_json::from_slice(output.stdout.as_slice())?;
        deserialized.prefixes_v4()
    }

    /// Queries a list of IPv6 networks.
    pub fn query_v6(&self, query: impl Into<Bgpq3Query>) -> Bgpq3Result<Vec<Ipv6Network>> {
        let output = query.into()
            .build_command(&self.settings, true)
            .output()?;
        if !output.status.success() {
            return Err(Bgpq3Error::StatusNotSuccess);
        }
        let deserialized: Bgpq3Output = serde_json::from_slice(output.stdout.as_slice())?;
        deserialized.prefixes_v6()
    }

    /// Queries a list of IPv4 networks using tokio.
    #[cfg(feature = "tokio")]
    pub async fn tokio_query_v4(&self, query: impl Into<Bgpq3Query>) -> Bgpq3Result<Vec<Ipv4Network>> {
        let output = tokio::process::Command::from(
            query.into()
                .build_command(&self.settings, false)
        )
            .output().await?;
        if !output.status.success() {
            return Err(Bgpq3Error::StatusNotSuccess);
        }
        let deserialized: Bgpq3Output = serde_json::from_slice(output.stdout.as_slice())?;
        deserialized.prefixes_v4()
    }

    /// Queries a list of IPv6 networks using tokio.
    #[cfg(feature = "tokio")]
    pub async fn tokio_query_v6(&self, query: impl Into<Bgpq3Query>) -> Bgpq3Result<Vec<Ipv6Network>> {
        let output = tokio::process::Command::from(
            query.into()
                .build_command(&self.settings, true)
        )
            .output().await?;
        if !output.status.success() {
            return Err(Bgpq3Error::StatusNotSuccess);
        }
        let deserialized: Bgpq3Output = serde_json::from_slice(output.stdout.as_slice())?;
        deserialized.prefixes_v6()
    }
}

#[derive(Deserialize)]
struct Bgpq3Output {
    #[serde(rename = "NN")]
    nn: Vec<Bgpq3OutputInner>,
}

impl Bgpq3Output {
    fn prefixes_v4(self) -> Bgpq3Result<Vec<Ipv4Network>> {
        let prefixes: Result<Vec<Ipv4Network>, IpNetworkError> = self.nn.into_iter()
            .map(|inner| inner.prefix.parse())
            .collect();
        Ok(prefixes?)
    }

    fn prefixes_v6(self) -> Bgpq3Result<Vec<Ipv6Network>> {
        let prefixes: Result<Vec<Ipv6Network>, IpNetworkError> = self.nn.into_iter()
            .map(|inner| inner.prefix.parse())
            .collect();
        Ok(prefixes?)
    }
}

#[derive(Deserialize)]
struct Bgpq3OutputInner {
    prefix: String,
}

/// A query for bgpq3.
///
/// See [`Bgpq3::query_v4`] and [`Bgpq3::query_v6`] for usage examples.
///
/// # Example
///
/// AS-SET
///
/// ```
/// use bgpq3::Bgpq3Query;
/// let query: Bgpq3Query = "AS-RAPPET".into();
/// ```
///
/// ASN
///
/// ```
/// use bgpq3::Bgpq3Query;
/// let query: Bgpq3Query = 207968.into();
/// ```
#[derive(Debug, Clone)]
pub struct Bgpq3Query {
   pub(crate) query_string: String,
}

impl Bgpq3Query {
    pub fn as_set(as_set: &str) -> Bgpq3Query {
        Bgpq3Query {
            query_string: as_set.to_string(),
        }
    }

    pub fn asn(asn: u32) -> Bgpq3Query {
        Bgpq3Query {
            query_string: format!("AS{}", asn.to_string()),
        }
    }

    fn build_command(&self, settings: &Bgpq3Settings, ipv6: bool) -> Command {
        let mut command = Command::new(settings.version.bin_name());
        // JSON
        command.arg("-j");
        if ipv6 {
            command.arg("-6");
        }
        command.arg(&self.query_string);
        command
    }
}

impl From<&str> for Bgpq3Query {
    fn from(as_set: &str) -> Self {
        Bgpq3Query::as_set(as_set)
    }
}

impl From<u32> for Bgpq3Query {
    fn from(asn: u32) -> Self {
        Bgpq3Query::asn(asn)
    }
}

/// Settings to create a new [`Bgpq3`] wrapper.
///
/// [`Bgpq3`]: crate::Bgpq3
#[derive(Default, Debug, Clone)]
pub struct Bgpq3Settings {
    version: Version,
}

impl Bgpq3Settings {
    pub fn new() -> Bgpq3Settings {
        Default::default()
    }

    pub fn version(mut self, version: Version) -> Bgpq3Settings {
        self.version = version;
        self
    }

    pub fn build(self) -> Bgpq3 {
        Bgpq3::with_settings(&self)
    }
}

#[derive(Debug, Error)]
pub enum Bgpq3Error {
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    #[error("bgpq3/bgpq4 did not run successfully")]
    StatusNotSuccess,
    #[error("failed parsing output json: {0}")]
    Json(#[from] serde_json::Error),
    #[error("failed parsing ip-network: {0}")]
    IpNetwork(#[from] IpNetworkError),
}

impl From<Bgpq3Error> for std::io::Error {
    fn from(err: Bgpq3Error) -> Self {
        use std::io::{Error, ErrorKind};

        match err {
            Bgpq3Error::Io(io) => io,
            Bgpq3Error::StatusNotSuccess => Error::new(ErrorKind::Other, err.to_string()),
            Bgpq3Error::Json(err) => err.into(),
            Bgpq3Error::IpNetwork(_) => Error::new(ErrorKind::InvalidData, err.to_string()),
        }
    }
}

pub type Bgpq3Result<T> = Result<T, Bgpq3Error>;

/// Selects, if the bgpq3 or bgpq4 binary is used.
///
/// [`bgpq3`] is used as default.
/// [`bgpq4`] should be preferred.
///
/// [`bgpq3`]: https://github.com/snar/bgpq3
/// [`bgpq4`]: https://github.com/bgp/bgpq4
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Version {
    Bgpq3,
    Bgpq4,
}

impl Version {
    pub fn bin_name(self) -> &'static str {
        match self {
            Version::Bgpq3 => "bgpq3",
            Version::Bgpq4 => "bgpq4"
        }
    }
}

impl Default for Version {
    fn default() -> Self {
        Version::Bgpq3
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}