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
//! # BGPd CLI
//!
//! The CLI provided for running the BGPd daemon can also be used to interact with a running instance of BGPd. It uses the default endpoint for the BGPd HTTP API (localhost:8080), but you can point to BGPd running remotely using the `--host` and `--port` options.
//!
//! ## Features
//! - [x] CLI interface for viewing peer status and details
//! - [x] View learned routes (with source)
//! - [x] View advertised routes
//! - [x] Advertise IPv4/IPv6 Unicast routes (More attribute support coming soon)
//! - [x] Advertise IPv4/IPv6 Flowspec flows
//! - [ ] Filter learned/advertised routes (prefix, peer, attributes, ...)
//! - [ ] Enable/disable Peers
//!
//!
//! # Show Commands
//! Use the `bgpd` CLI for viewing peer & route information:
//!
//! ## Neighbors
//!
//! Peer summary:
//! ```sh
//! $ cargo run -- show neighbors
//! Neighbor Router ID AS MsgRcvd MsgSent Uptime State PfxRcd
//! ----------------------------------------------------------------------------------
//! 127.0.0.2 2.2.2.2 100 76 70 00:11:27 Established 4
//! *127.0.0.3 65000 Disabled
//! 172.16.20.2 172.16.20.2 65000 29 28 00:11:33 Established 2
//! ```
//! > Tip: Use the `watch` command for keeping this view up-to-date
//!
//! Peer Detail:
//! ```sh
//! BGP neighbor is 127.0.0.3, remote AS 65000, local AS 65000
//! *Peer is Disabled
//! Neighbor capabilities:
//! IPv4 Unicast
//! IPv4 Flowspec
//! IPv6 Unicast
//! IPv6 Flowspec
//!
//!
//! BGP neighbor is 172.16.20.2, remote AS 65000, local AS 65000
//! BGP version 4, remote router-id 172.16.20.2
//! Local address: 172.16.20.90:55687
//! Remote address: 172.16.20.2:179
//! BGP state = Established, up for 00:11:59
//! Hold time is 90 (00:01:18), keepalive interval is 30
//! Last read 00:00:03, last write 00:00:11
//! Neighbor capabilities:
//! Address family IPv6 Unicast
//! Address family IPv4 Unicast
//!
//! Message Statistics:
//! Sent Received
//! Total 30 29
//! ```
//!
//! ## Routes
//!
//! Learned routes:
//! ```sh
//! $ bgpd show routes learned
//! IPv4 / Unicast
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! --------------------------------------------------------------------------------------------------------------------------------
//! Config 9.9.9.0/24 172.16.20.90 00:08:00 Incomplete 00:08:00
//! 172.16.20.2 172.16.20.0/24 172.16.20.2 00:07:54 IGP 100 00:07:54
//! 127.0.0.2 2.100.0.0/24 127.0.0.2 00:07:46 IGP 500 100 target:65000:1.1.1.1 00:07:46
//! 127.0.0.2 2.200.0.0/24 127.0.0.2 00:07:46 IGP 100 200 00:07:46
//!
//! IPv6 / Flowspec
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! --------------------------------------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 Dst: 3001:99:b::10/128, Src: 3001:99:a::10/128 00:00:39 IGP 100 redirect:6:302 00:00:39
//!
//! IPv6 / Unicast
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------------------
//! Config 3001:404:a::/64 3001:1::1 00:08:00 Incomplete 00:08:00
//! Config 3001:404:b::/64 3001:1::1 00:08:00 Incomplete 00:08:00
//! 172.16.20.2 3001:172:16:20::/64 ::ffff:172.16.20.2 00:07:54 IGP 100 00:07:54
//! 127.0.0.2 2621:a:10::/64 3001:1::1 00:07:46 IGP 600 650 00:07:46
//! 127.0.0.2 2621:a:1337::/64 3001:1::1 00:07:46 IGP 404 100 00:07:46
//! ```
//!
//! Learned routes can be filtered with a peer IP Addr or prefix:
//! ```sh
//! $ bgpd show routes learned 172.16.20.2
//! IPv4 / Unicast
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! --------------------------------------------------------------------------------------------------------------------------------
//! 172.16.20.2 172.16.20.0/24 172.16.20.2 00:07:54 IGP 100 00:07:54
//!
//! IPv6 / Unicast
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------------------
//! 172.16.20.2 3001:172:16:20::/64 ::ffff:172.16.20.2 00:07:54 IGP 100 00:07:54
//! ```
//!
//! ```sh
//! $ bgpd show routes learned 127.0.0.0/24
//! IPv4 / Unicast
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! --------------------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 2.100.0.0/24 127.0.0.2 00:07:46 IGP 500 100 target:65000:1.1.1.1 00:07:46
//! 127.0.0.2 2.200.0.0/24 127.0.0.2 00:07:46 IGP 100 200 00:07:46
//!
//! IPv6 / Flowspec
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! --------------------------------------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 Dst: 3001:99:b::10/128, Src: 3001:99:a::10/128 00:00:39 IGP 100 redirect:6:302 00:00:39
//!
//! IPv6 / Unicast
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 2621:a:10::/64 3001:1::1 00:07:46 IGP 600 650 00:07:46
//! 127.0.0.2 2621:a:1337::/64 3001:1::1 00:07:46 IGP 404 100 00:07:46
//! ```
//!
//! Advertised routes:
//! ```sh
//! $ bgpd show routes advertised
//! IPv4 / Unicast
//! Advertised To Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! -----------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 172.16.20.0/24 172.16.20.2 00:08:01 IGP 100 00:08:01
//! 172.16.20.2 9.9.9.0/24 172.16.20.90 00:08:06 Incomplete 00:08:06
//!
//! IPv6 / Unicast
//! Advertised To Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 3001:172:16:20::/64 ::ffff:172.16.20.2 00:08:01 IGP 100 00:08:01
//! 172.16.20.2 3001:404:a::/64 3001:1::1 00:08:06 Incomplete 00:08:06
//! 172.16.20.2 3001:404:b::/64 3001:1::1 00:08:06 Incomplete 00:08:06
//! ```
//!
//! ## Advertise
//!
//! ### Unicast
//! IPv4 Unicast
//! ```sh
//! $ bgpd advertise route 10.10.10.0/24 172.16.20.90 --local-pref 500
//! Added route to RIB for announcement:
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------
//! API 10.10.10.0/24 172.16.20.90 00:00:00 Incomplete 00:00:00
//! ```
//!
//! IPv6 Unicast
//! ```sh
//! $ bgpd advertise route 10.10.10.0/24 172.16.20.90 --local-pref 500
//! Added route to RIB for announcement:
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------
//! API 10.10.10.0/24 172.16.20.90 00:00:00 Incomplete 00:00:00
//! ```
//!
//! ```sh
//! $ bgpd show routes advertised
//! IPv4 / Unicast
//! Advertised To Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! -----------------------------------------------------------------------------------------------------------------------
//! ...
//! 172.16.20.2 10.10.10.0/24 172.16.20.90 00:01:17 Incomplete 00:01:17
//!
//! IPv6 / Unicast
//! Advertised To Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------------------
//! ...
//! 172.16.20.2 3001:100:abcd::/64 3001:1::1 00:00:03 Incomplete 00:00:03
//! ```
//!
//! ### Flowspec
//! ```sh
//! $ bgpd advertise flow ipv4 'traffic-rate 100' -m 'source 192.168.10.0/24'
//! Added flow to RIB for announcement:
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! ----------------------------------------------------------------------------------------------------------------------------------
//! Config Src 192.168.10.0/24 00:00:00 Incomplete traffic-rate:0:100bps 00:00:00
//! $ bgpd advertise flow ipv6 'redirect 100:200' -m 'destination 3001:10:20::/64'
//! Added flow to RIB for announcement:
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! -----------------------------------------------------------------------------------------------------------------------------
//! Config Dst 3001:10:20::/64 00:00:00 Incomplete redirect:100:200 00:00:00
//! ```
//!
//! ```sh
//! $ bgpd show routes learned
//! IPv4 / Flowspec
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! --------------------------------------------------------------------------------------------------------------------------
//! Config Src 192.168.0.0/16 00:01:55 Incomplete redirect:6:302 00:01:55
//!
//! IPv6 / Flowspec
//! Received From Prefix Next Hop Age Origin Local Pref Metric AS Path Communities Age
//! -----------------------------------------------------------------------------------------------------------------------------------------
//! 127.0.0.2 Dst 3001:99:b::10/128 00:01:24 IGP 200 traffic-rate:0:500bps 00:01:24
//! Src 3001:99:a::10/128
//! Config Src 3001:100::/56 00:01:55 Incomplete traffic-rate:0:24000bps 00:01:55
//! DstPort >8000, && <=8080
//! Packet Length >100
//!
//! ```
use std::error::Error;
use std::net::{IpAddr, SocketAddr};
use colored::*;
use ipnetwork::IpNetwork;
use itertools::Itertools;
use jsonrpsee::http_client::HttpClientBuilder;
use structopt::StructOpt;
use crate::api::rpc::{ApiClient, FlowSpec, RouteSpec};
mod display;
mod table;
use display::{AdvertisedRouteRow, LearnedRouteRow, PeerSummaryRow};
#[derive(StructOpt, Debug)]
#[structopt(name = "bgpd-cli", rename_all = "kebab-case")]
/// CLI to interact with BGPd
pub struct Args {
#[structopt(subcommand)]
pub cmd: Command,
#[structopt(short, long, default_value = "127.0.0.1")]
pub host: String,
#[structopt(short, long, default_value = "8080")]
pub port: u16,
/// API Listening address/port (E.g. 127.0.0.1:8080). If not provided, will fall back to config file value
#[structopt(long)]
pub api: Option<SocketAddr>,
/// Show debug logs (additive for trace logs)
#[structopt(short, parse(from_occurrences), global = true)]
pub verbose: u8,
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
/// CLI to query BGPd
pub enum Command {
#[structopt()]
/// Run BGPd daemon
Run(RunOptions),
#[structopt(alias = "s")]
/// View details about BGPd
Show(Show),
/// Send routes to be advertised
Advertise(Advertise),
}
#[derive(StructOpt, Debug)]
#[structopt(name = "bgpd", rename_all = "kebab-case")]
/// BGPd Server
pub struct RunOptions {
/// Path to BGP service config.toml
pub config_path: String,
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub enum Show {
/// View configured neighbors and session details
/// (* prefix means peer is disabled)
#[structopt(alias = "n", visible_alias = "peers")]
Neighbors(NeighborOptions),
#[structopt(alias = "r")]
Routes(Routes),
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub struct NeighborOptions {
#[structopt()]
detail: bool,
// #[structopt()]
// family: Option<AFI>,
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub enum Routes {
#[structopt()]
Learned(RouteOptions),
#[structopt()]
Advertised(RouteOptions),
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub struct RouteOptions {
/// IP Address or Network Prefix to match route source
#[structopt()]
peer: Option<IpNetwork>,
// #[structopt()]
// family: Option<AFI>,
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub enum Advertise {
#[structopt()]
Route(Route),
#[structopt()]
Flow(Flow),
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub struct Route {
/// Prefix to advertise
#[structopt()]
prefix: IpNetwork,
/// Next Hop for this route
#[structopt()]
next_hop: IpAddr,
/// Origin (defaults to Incomplete)
#[structopt(short, long)]
origin: Option<String>,
/// AS Path (e.g. --as-path 100 200 65000.100), defaults to an empty path
#[structopt(short, long)]
as_path: Option<String>,
/// Local Pref (defaults to 100)
#[structopt(short = "p", long)]
local_pref: Option<u32>,
/// Multi-exit-discriminator
#[structopt(long)]
med: Option<u32>,
/// Communities (e.g. --communities 100 200 redirect:65000:100)
#[structopt(short, long)]
communities: Option<String>,
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub struct Flow {
/// AFI [ipv6, ipv4]
#[structopt()]
family: String,
/// Flowspec action E.g. "redirect 6:302" or "traffic-rate 302"
#[structopt()]
action: String,
/// Origin (defaults to Incomplete)
#[structopt(short, long)]
matches: Vec<String>,
/// Origin (defaults to Incomplete)
#[structopt(short, long)]
origin: Option<String>,
/// AS Path (e.g. --as-path 100 200 65000.100), defaults to an empty path
#[structopt(short, long)]
as_path: Option<String>,
/// Local Pref (defaults to 100)
#[structopt(short = "p", long)]
local_pref: Option<u32>,
/// Multi-exit-discriminator
#[structopt(long)]
med: Option<u32>,
/// Communities (e.g. --communities 100 200 redirect:65000:100)
#[structopt(short, long)]
communities: Option<String>,
}
async fn run_cmd(args: &Args) -> Result<(), Box<dyn Error>> {
let client = {
let base = format!("http://{}:{}", args.host, args.port);
HttpClientBuilder::default().build(base)?
};
match &args.cmd {
Command::Show(show) => match show {
Show::Neighbors(options) => {
if options.detail {
let peers: Vec<_> = client.show_peer_detail().await?;
for peer in peers {
let summ = peer.summary;
let mut lines: Vec<String> = Vec::with_capacity(16);
lines.push(format!(
"BGP neighbor is {}, remote AS {}, local AS {}",
summ.peer, summ.remote_asn, summ.local_asn
));
if !summ.enabled {
lines.push("*Peer is Disabled".to_string());
}
if let Some(router_id) = summ.router_id {
lines.push(format!("BGP version 4, remote router-id {}", router_id));
if let Some(stream) = peer.tcp_connection {
lines.push(format!(" Local address: {}", stream.0));
lines.push(format!(" Remote address: {}", stream.1));
}
lines.push(format!(
"BGP state = {}, up for {}",
summ.state,
summ.uptime.unwrap(),
));
lines.push(format!(
"Hold time is {} ({}), keepalive interval is {}",
peer.hold_timer,
peer.hold_time.unwrap(),
peer.hold_timer_interval,
));
lines.push(format!(
" Last read {}, last write {}",
peer.last_received.unwrap(),
peer.last_sent.unwrap(),
));
}
lines.push("Neighbor capabilities:".to_string());
for capability in &peer.capabilities {
lines.push(format!(" {}", capability));
}
lines.push(format!("",));
if let (Some(sent), Some(rcvd)) = (summ.msg_received, summ.msg_sent) {
lines.push("Message Statistics:".to_string());
lines.push(" Sent Received".to_string());
lines.push(format!(" Total {} {}", sent, rcvd));
}
println!("{}\n", lines.join("\n "));
}
} else {
let peers: Vec<_> = client
.show_peers()
.await?
.into_iter()
.map(PeerSummaryRow)
.collect();
let mut table = table::OutputTable::new();
for peer in peers {
table.add_row(&peer)?;
}
table.print();
}
}
Show::Routes(routes) => match routes {
Routes::Learned(options) => {
let mut routes: Vec<_> = client.show_routes_learned(options.peer).await?;
routes.sort_by_key(|r| (r.afi.clone(), r.safi.clone()));
for (afi, routes) in &routes.into_iter().group_by(|r| r.afi.clone()) {
for (safi, routes) in &routes.group_by(|r| r.safi.clone()) {
println!("{} / {}", afi, safi);
let mut table = table::OutputTable::new();
for route in routes {
table.add_row(&LearnedRouteRow(route))?;
}
table.print();
println!();
}
}
}
Routes::Advertised(options) => {
let mut routes: Vec<_> = client.show_routes_advertised(options.peer).await?;
routes.sort_by_key(|r| (r.afi.clone(), r.safi.clone()));
for (afi, routes) in &routes.into_iter().group_by(|r| r.afi.clone()) {
for (safi, routes) in &routes.group_by(|r| r.safi.clone()) {
println!("{} / {}", afi, safi);
let mut table = table::OutputTable::new();
for route in routes {
table.add_row(&AdvertisedRouteRow(route))?;
}
table.print();
println!();
}
}
}
},
},
Command::Advertise(advertise) => match advertise {
Advertise::Route(route) => {
let mut spec = RouteSpec::new(route.prefix, route.next_hop);
if let Some(origin) = &route.origin {
spec.attributes.origin = Some(origin.to_string());
}
if let Some(local_pref) = &route.local_pref {
spec.attributes.local_pref = Some(*local_pref);
}
if let Some(med) = &route.med {
spec.attributes.multi_exit_disc = Some(*med);
}
if let Some(as_path) = &route.as_path {
spec.attributes.as_path =
as_path.split(' ').map(|asn| asn.to_string()).collect();
}
if let Some(communities) = &route.communities {
spec.attributes.communities = communities
.split(' ')
.map(|comm| comm.to_string())
.collect();
}
match client.advertise_route(spec).await? {
Ok(advertised) => {
println!("Added route to RIB for announcement:");
let mut table = table::OutputTable::new();
table.add_row(&LearnedRouteRow(advertised))?;
table.print();
}
Err(err) => eprintln!("Error adding route: {}", err),
}
}
Advertise::Flow(flow) => {
let afi = match flow.family.to_lowercase().as_str() {
"ipv4" => 1,
"ipv6" => 2,
_ => {
eprintln!("Invalid family, must be one of: [ipv4, ipv6]");
return Ok(()); // TODO, return err
}
};
let mut spec = FlowSpec::new(afi, flow.action.to_string(), flow.matches.clone());
if let Some(origin) = &flow.origin {
spec.attributes.origin = Some(origin.to_string());
}
if let Some(local_pref) = &flow.local_pref {
spec.attributes.local_pref = Some(*local_pref);
}
if let Some(med) = &flow.med {
spec.attributes.multi_exit_disc = Some(*med);
}
if let Some(as_path) = &flow.as_path {
spec.attributes.as_path =
as_path.split(' ').map(|asn| asn.to_string()).collect();
}
if let Some(communities) = &flow.communities {
spec.attributes.communities = communities
.split(' ')
.map(|comm| comm.to_string())
.collect();
}
match client.advertise_flow(spec).await? {
Ok(advertised) => {
println!("Added flow to RIB for announcement:");
let mut table = table::OutputTable::new();
table.add_row(&LearnedRouteRow(advertised))?;
table.print();
}
Err(err) => eprintln!("Error adding flow: {}", err),
}
}
},
_ => unimplemented!(), // ::Run should never get called since it's handled in main
}
Ok(())
}
/// BGPd interactive commands (other than running the daemon)
pub async fn query_bgpd(args: &Args) {
if let Err(err) = run_cmd(args).await {
eprintln!("{}", err.to_string().red());
}
}