1 use std::sync::{Arc, Mutex};
2 use std::sync::atomic::{AtomicBool, Ordering};
4 use std::ops::Bound::Included;
5 use std::collections::BTreeMap;
6 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
7 use std::time::{Duration, Instant};
9 use bgp_rs::{AFI, SAFI, AddPathDirection, Open, OpenCapability, OpenParameter, NLRIEncoding, PathAttribute};
10 use bgp_rs::Capabilities;
15 use tokio::prelude::*;
17 use tokio::codec::Framed;
18 use tokio::net::TcpStream;
19 use tokio::timer::Delay;
21 use futures::sync::mpsc;
23 use crate::printer::Printer;
32 v4_table: BTreeMap<(Ipv4Addr, u8, u32), Arc<Route>>,
33 v6_table: BTreeMap<(Ipv6Addr, u8, u32), Arc<Route>>,
39 v4_table: BTreeMap::new(),
40 v6_table: BTreeMap::new(),
44 fn get_route_attrs(&self, ip: IpAddr) -> Vec<Arc<Route>> {
45 macro_rules! lookup_res {
46 ($addrty: ty, $addr: expr, $table: expr, $addr_bits: expr) => { {
47 let mut res = Vec::new();
48 //TODO: Optimize this!
49 for i in (0..$addr_bits).rev() {
50 let mut lookup = $addr.octets();
52 lookup[lookup.len() - b - 1] = 0;
54 lookup[lookup.len() - (i/8) - 1] &= !(((1u16 << (i % 8)) - 1) as u8);
55 let lookup_addr = <$addrty>::from(lookup);
56 for attrs in $table.range((Included((lookup_addr, $addr_bits - i as u8, 0)), Included((lookup_addr, $addr_bits - i as u8, std::u32::MAX)))) {
57 res.push(Arc::clone(&attrs.1));
59 if !res.is_empty() { break; }
65 IpAddr::V4(v4a) => lookup_res!(Ipv4Addr, v4a, self.v4_table, 32),
66 IpAddr::V6(v6a) => lookup_res!(Ipv6Addr, v6a, self.v6_table, 128)
70 fn withdraw(&mut self, route: NLRIEncoding) {
72 NLRIEncoding::IP(p) => {
73 let (ip, len) = <(IpAddr, u8)>::from(&p);
75 IpAddr::V4(v4a) => self.v4_table.remove(&(v4a, len, 0)),
76 IpAddr::V6(v6a) => self.v6_table.remove(&(v6a, len, 0)),
79 NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
80 let (ip, len) = <(IpAddr, u8)>::from(&p);
82 IpAddr::V4(v4a) => self.v4_table.remove(&(v4a, len, id)),
83 IpAddr::V6(v6a) => self.v6_table.remove(&(v6a, len, id)),
86 NLRIEncoding::IP_MPLS(_) => None,
90 fn announce(&mut self, prefix: NLRIEncoding, route: Arc<Route>) {
92 NLRIEncoding::IP(p) => {
93 let (ip, len) = <(IpAddr, u8)>::from(&p);
95 IpAddr::V4(v4a) => self.v4_table.insert((v4a, len, 0), route),
96 IpAddr::V6(v6a) => self.v6_table.insert((v6a, len, 0), route),
99 NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
100 let (ip, len) = <(IpAddr, u8)>::from(&p);
102 IpAddr::V4(v4a) => self.v4_table.insert((v4a, len, id), route),
103 IpAddr::V6(v6a) => self.v6_table.insert((v6a, len, id), route),
106 NLRIEncoding::IP_MPLS(_) => None,
111 struct BytesCoder<'a>(&'a mut bytes::BytesMut);
112 impl<'a> std::io::Write for BytesCoder<'a> {
113 fn write(&mut self, b: &[u8]) -> Result<usize, std::io::Error> {
114 self.0.extend_from_slice(&b);
117 fn flush(&mut self) -> Result<(), std::io::Error> {
121 struct BytesDecoder<'a> {
122 buf: &'a mut bytes::BytesMut,
125 impl<'a> std::io::Read for BytesDecoder<'a> {
126 fn read(&mut self, b: &mut [u8]) -> Result<usize, std::io::Error> {
127 let copy_len = cmp::min(b.len(), self.buf.len() - self.pos);
128 b[..copy_len].copy_from_slice(&self.buf[self.pos..self.pos + copy_len]);
129 self.pos += copy_len;
134 struct MsgCoder<'a>(&'a Printer);
135 impl<'a> codec::Decoder for MsgCoder<'a> {
137 type Error = std::io::Error;
139 fn decode(&mut self, bytes: &mut bytes::BytesMut) -> Result<Option<Message>, std::io::Error> {
140 let mut decoder = BytesDecoder {
145 stream: &mut decoder,
146 capabilities: Capabilities {
147 FOUR_OCTET_ASN_SUPPORT: true,
148 EXTENDED_PATH_NLRI_SUPPORT: true,
151 Ok((_header, msg)) => {
152 decoder.buf.advance(decoder.pos);
155 Err(e) => match e.kind() {
156 std::io::ErrorKind::UnexpectedEof => Ok(None),
162 impl<'a> codec::Encoder for MsgCoder<'a> {
164 type Error = std::io::Error;
166 fn encode(&mut self, msg: Message, res: &mut bytes::BytesMut) -> Result<(), std::io::Error> {
167 msg.write(&mut BytesCoder(res))?;
172 pub struct BGPClient {
173 routes: Mutex<RoutingTable>,
174 shutdown: AtomicBool,
177 pub fn get_asn(&self, addr: IpAddr) -> u32 {
178 let mut path_vecs = self.routes.lock().unwrap().get_route_attrs(addr).clone();
179 path_vecs.sort_unstable_by(|path_a, path_b| {
180 path_a.pref.cmp(&path_b.pref)
181 .then(path_b.path.len().cmp(&path_a.path.len()))
182 .then(path_b.med.cmp(&path_a.med))
184 // TODO: Find last common ASN among all paths
185 *path_vecs.first().map(|route| route.path.last().unwrap_or(&0)).unwrap_or(&0)
188 pub fn disconnect(&self) {
189 self.shutdown.store(true, Ordering::Relaxed);
192 fn map_attrs(mut attrs: Vec<PathAttribute>) -> Option<Route> {
193 let mut as4_path = None;
194 let mut as_path = None;
197 for attr in attrs.drain(..) {
199 PathAttribute::AS4_PATH(path) => as4_path = Some(path),
200 PathAttribute::AS_PATH(path) => as_path = Some(path),
201 PathAttribute::LOCAL_PREF(p) => pref = p,
202 PathAttribute::MULTI_EXIT_DISC(m) => med = m,
206 if let Some(mut aspath) = as4_path.or(as_path) {
207 let mut path = Vec::new();
208 for seg in aspath.segments.drain(..) {
210 Segment::AS_SEQUENCE(mut asn) => path.append(&mut asn),
211 Segment::AS_SET(_) => {}, // Ignore sets for now, they're not that common anyway
222 fn connect_given_client(addr: SocketAddr, timeout: Duration, printer: &'static Printer, client: Arc<BGPClient>) {
223 let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
224 future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
226 let client_reconn = Arc::clone(&client);
227 tokio::spawn(TcpStream::connect(&addr).select(connect_timeout)
229 Delay::new(Instant::now() + timeout / 10).then(|_| {
232 }).and_then(move |stream| {
233 let (write, read) = Framed::new(stream.0, MsgCoder(printer)).split();
234 let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
235 tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
239 let _ = sender.try_send(Message::Open(Open {
243 identifier: 0x453b1215, // 69.59.18.21
244 parameters: vec![OpenParameter::Capabilities(vec![
245 OpenCapability::MultiProtocol((AFI::IPV4, SAFI::Unicast)),
246 OpenCapability::MultiProtocol((AFI::IPV6, SAFI::Unicast)),
247 OpenCapability::FourByteASN(397444),
248 OpenCapability::RouteRefresh,
249 OpenCapability::AddPath(vec![
250 (AFI::IPV4, SAFI::Unicast, AddPathDirection::ReceivePaths),
251 (AFI::IPV6, SAFI::Unicast, AddPathDirection::ReceivePaths)]),
254 read.for_each(move |bgp_msg| {
255 if client.shutdown.load(Ordering::Relaxed) {
256 return future::err(std::io::Error::new(std::io::ErrorKind::Other, "Shutting Down"));
259 Message::Open(_) => {
260 client.routes.lock().unwrap().v4_table.clear();
261 client.routes.lock().unwrap().v6_table.clear();
262 printer.add_line("Connected to BGP route provider".to_string(), false);
264 Message::KeepAlive => {
265 let _ = sender.try_send(Message::KeepAlive);
267 Message::Update(mut upd) => {
269 let mut route_table = client.routes.lock().unwrap();
270 for r in upd.withdrawn_routes {
271 route_table.withdraw(r);
273 if let Some(path) = Self::map_attrs(upd.attributes) {
274 let path_arc = Arc::new(path);
275 for r in upd.announced_routes {
276 route_table.announce(r, Arc::clone(&path_arc));
283 }).or_else(move |e| {
284 printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
288 if !client_reconn.shutdown.load(Ordering::Relaxed) {
289 BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
296 pub fn new(addr: SocketAddr, timeout: Duration, printer: &'static Printer) -> Arc<BGPClient> {
297 let client = Arc::new(BGPClient {
298 routes: Mutex::new(RoutingTable::new()),
299 shutdown: AtomicBool::new(false),
301 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));