1 use std::sync::{Arc, Mutex};
2 use std::sync::atomic::{AtomicBool, Ordering};
4 use std::collections::{HashMap, hash_map};
5 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
6 use std::time::{Duration, Instant};
8 use bgp_rs::{AFI, SAFI, AddPathDirection, Open, OpenCapability, OpenParameter, NLRIEncoding, PathAttribute};
9 use bgp_rs::Capabilities;
14 use tokio::prelude::*;
16 use tokio::codec::Framed;
17 use tokio::net::TcpStream;
18 use tokio::timer::Delay;
20 use futures::sync::mpsc;
22 use crate::printer::{Printer, Stat};
23 use crate::timeout_stream::TimeoutStream;
25 const PATH_SUFFIX_LEN: usize = 3;
27 struct Route { // 32 bytes with a path id u32
28 path_suffix: [u32; PATH_SUFFIX_LEN],
34 const ROUTE_LEN: usize = 36 - std::mem::size_of::<(u32, Route)>();
36 // To keep memory tight (and since we dont' need such close alignment), newtype the v4/v6 routing
37 // table entries to make sure they are aligned to single bytes.
40 #[derive(PartialEq, Eq, Hash)]
45 impl From<(Ipv4Addr, u8)> for V4Addr {
46 fn from(p: (Ipv4Addr, u8)) -> Self {
54 const V4_ALIGN: usize = 1 - std::mem::align_of::<V4Addr>();
56 const V4_SIZE: usize = 5 - std::mem::size_of::<V4Addr>();
59 #[derive(PartialEq, Eq, Hash)]
64 impl From<(Ipv6Addr, u8)> for V6Addr {
65 fn from(p: (Ipv6Addr, u8)) -> Self {
73 const V6_ALIGN: usize = 1 - std::mem::align_of::<V6Addr>();
75 const V6_SIZE: usize = 17 - std::mem::size_of::<V6Addr>();
78 // We really want a HashMap for the values here, but they'll only ever contain a few entries,
79 // and Vecs are way more memory-effecient in that case.
80 v4_table: HashMap<V4Addr, Vec<(u32, Route)>>,
81 v6_table: HashMap<V6Addr, Vec<(u32, Route)>>,
83 routes_with_max: usize,
89 v4_table: HashMap::with_capacity(900_000),
90 v6_table: HashMap::with_capacity(100_000),
96 fn get_route_attrs(&self, ip: IpAddr) -> (u8, Vec<&Route>) {
97 macro_rules! lookup_res {
98 ($addrty: ty, $addr: expr, $table: expr, $addr_bits: expr) => { {
99 //TODO: Optimize this (probably means making the tables btrees)!
100 let mut lookup = <$addrty>::from(($addr, $addr_bits));
101 for i in 0..$addr_bits {
102 if let Some(routes) = $table.get(&lookup) {
103 if routes.len() > 0 {
104 return (lookup.pfxlen, routes.iter().map(|v| &v.1).collect());
107 lookup.addr[lookup.addr.len() - (i/8) - 1] &= !(1u8 << (i % 8));
114 IpAddr::V4(v4a) => lookup_res!(V4Addr, v4a, self.v4_table, 32),
115 IpAddr::V6(v6a) => lookup_res!(V6Addr, v6a, self.v6_table, 128)
119 fn withdraw(&mut self, route: NLRIEncoding) {
120 macro_rules! remove {
121 ($rt: expr, $v: expr, $id: expr) => { {
122 match $rt.entry($v.into()) {
123 hash_map::Entry::Occupied(mut entry) => {
124 if entry.get().len() == self.max_paths {
125 self.routes_with_max -= 1;
126 if self.routes_with_max == 0 {
130 entry.get_mut().retain(|e| e.0 != $id);
131 if entry.get_mut().is_empty() {
140 NLRIEncoding::IP(p) => {
141 let (ip, len) = <(IpAddr, u8)>::from(&p);
143 IpAddr::V4(v4a) => remove!(self.v4_table, (v4a, len), 0),
144 IpAddr::V6(v6a) => remove!(self.v6_table, (v6a, len), 0),
147 NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
148 let (ip, len) = <(IpAddr, u8)>::from(&p);
150 IpAddr::V4(v4a) => remove!(self.v4_table, (v4a, len), id),
151 IpAddr::V6(v6a) => remove!(self.v6_table, (v6a, len), id),
154 NLRIEncoding::IP_MPLS(_) => (),
155 NLRIEncoding::IP_MPLS_WITH_PATH_ID(_) => (),
156 NLRIEncoding::IP_VPN_MPLS(_) => (),
157 NLRIEncoding::L2VPN(_) => (),
161 fn announce(&mut self, prefix: NLRIEncoding, route: Route) {
162 macro_rules! insert {
163 ($rt: expr, $v: expr, $id: expr) => { {
164 let old_max_paths = self.max_paths;
165 let entry = $rt.entry($v.into()).or_insert_with(|| Vec::with_capacity(old_max_paths));
166 let entry_had_max = entry.len() == self.max_paths;
167 entry.retain(|e| e.0 != $id);
169 entry.reserve_exact(1);
171 entry.reserve_exact(cmp::max(self.max_paths, entry.len() + 1) - entry.len());
173 entry.push(($id, route));
174 if entry.len() > self.max_paths {
175 self.max_paths = entry.len();
176 self.routes_with_max = 1;
177 } else if entry.len() == self.max_paths {
178 if !entry_had_max { self.routes_with_max += 1; }
183 NLRIEncoding::IP(p) => {
184 let (ip, len) = <(IpAddr, u8)>::from(&p);
186 IpAddr::V4(v4a) => insert!(self.v4_table, (v4a, len), 0),
187 IpAddr::V6(v6a) => insert!(self.v6_table, (v6a, len), 0),
190 NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
191 let (ip, len) = <(IpAddr, u8)>::from(&p);
193 IpAddr::V4(v4a) => insert!(self.v4_table, (v4a, len), id),
194 IpAddr::V6(v6a) => insert!(self.v6_table, (v6a, len), id),
197 NLRIEncoding::IP_MPLS(_) => (),
198 NLRIEncoding::IP_MPLS_WITH_PATH_ID(_) => (),
199 NLRIEncoding::IP_VPN_MPLS(_) => (),
200 NLRIEncoding::L2VPN(_) => (),
205 struct BytesCoder<'a>(&'a mut bytes::BytesMut);
206 impl<'a> std::io::Write for BytesCoder<'a> {
207 fn write(&mut self, b: &[u8]) -> Result<usize, std::io::Error> {
208 self.0.extend_from_slice(&b);
211 fn flush(&mut self) -> Result<(), std::io::Error> {
215 struct BytesDecoder<'a> {
216 buf: &'a mut bytes::BytesMut,
219 impl<'a> std::io::Read for BytesDecoder<'a> {
220 fn read(&mut self, b: &mut [u8]) -> Result<usize, std::io::Error> {
221 let copy_len = cmp::min(b.len(), self.buf.len() - self.pos);
222 b[..copy_len].copy_from_slice(&self.buf[self.pos..self.pos + copy_len]);
223 self.pos += copy_len;
228 struct MsgCoder(Option<Capabilities>);
229 impl codec::Decoder for MsgCoder {
231 type Error = std::io::Error;
233 fn decode(&mut self, bytes: &mut bytes::BytesMut) -> Result<Option<Message>, std::io::Error> {
234 let mut decoder = BytesDecoder {
238 let def_cap = Default::default();
239 let mut reader = Reader {
240 stream: &mut decoder,
241 capabilities: if let Some(cap) = &self.0 { cap } else { &def_cap },
243 match reader.read() {
244 Ok((_header, msg)) => {
245 decoder.buf.advance(decoder.pos);
246 if let Message::Open(ref o) = &msg {
247 self.0 = Some(Capabilities::from_parameters(o.parameters.clone()));
251 Err(e) => match e.kind() {
252 std::io::ErrorKind::UnexpectedEof => Ok(None),
258 impl codec::Encoder for MsgCoder {
260 type Error = std::io::Error;
262 fn encode(&mut self, msg: Message, res: &mut bytes::BytesMut) -> Result<(), std::io::Error> {
263 msg.encode(&mut BytesCoder(res))?;
268 pub struct BGPClient {
269 routes: Mutex<RoutingTable>,
270 shutdown: AtomicBool,
273 pub fn get_asn(&self, addr: IpAddr) -> u32 {
274 let lock = self.routes.lock().unwrap();
275 let mut path_vecs = lock.get_route_attrs(addr).1;
276 if path_vecs.is_empty() { return 0; }
278 path_vecs.sort_unstable_by(|path_a, path_b| {
279 path_a.pref.cmp(&path_b.pref)
280 .then(path_b.path_len.cmp(&path_a.path_len))
281 .then(path_b.med.cmp(&path_a.med))
284 let primary_route = path_vecs.pop().unwrap();
285 if path_vecs.len() > 3 {
286 // If we have at least 3 paths, try to find the last unique ASN which doesn't show up in other paths
287 // If we hit a T1 that is reasonably assumed to care about net neutrality, return the
289 let mut prev_asn = 0;
290 'asn_candidates: for asn in primary_route.path_suffix.iter().rev() {
291 if *asn == 0 { continue 'asn_candidates; }
293 // Included: CenturyLink (L3), Cogent, Telia, NTT, GTT, Level3,
294 // GBLX (L3), Zayo, TI Sparkle Seabone, HE, Telefonica
295 // Left out from Caida top-20: TATA, PCCW, Vodafone, RETN, Orange, Telstra,
296 // Singtel, Rostelecom, DTAG
297 209|174|1299|2914|3257|3356|3549|6461|6762|6939|12956 if prev_asn != 0 => return prev_asn,
298 _ => if path_vecs.iter().any(|route| !route.path_suffix.contains(asn)) {
299 if prev_asn != 0 { return prev_asn } else {
300 // Multi-origin prefix, just give up and take the last AS in the
302 break 'asn_candidates;
305 // We only ever possibly return an ASN if it appears in all paths
310 // All paths were the same, if the first ASN is non-0, return it.
316 for asn in primary_route.path_suffix.iter().rev() {
324 pub fn get_path(&self, addr: IpAddr) -> (u8, [u32; PATH_SUFFIX_LEN]) {
325 let lock = self.routes.lock().unwrap();
326 let (prefixlen, mut path_vecs) = lock.get_route_attrs(addr);
327 if path_vecs.is_empty() { return (0, [0; PATH_SUFFIX_LEN]); }
329 path_vecs.sort_unstable_by(|path_a, path_b| {
330 path_a.pref.cmp(&path_b.pref)
331 .then(path_b.path_len.cmp(&path_a.path_len))
332 .then(path_b.med.cmp(&path_a.med))
335 let primary_route = path_vecs.pop().unwrap();
336 (prefixlen, primary_route.path_suffix)
339 pub fn disconnect(&self) {
340 self.shutdown.store(true, Ordering::Relaxed);
343 fn map_attrs(mut attrs: Vec<PathAttribute>) -> Option<Route> {
344 let mut as4_path = None;
345 let mut as_path = None;
348 for attr in attrs.drain(..) {
350 PathAttribute::AS4_PATH(path) => as4_path = Some(path),
351 PathAttribute::AS_PATH(path) => as_path = Some(path),
352 PathAttribute::LOCAL_PREF(p) => pref = p,
353 PathAttribute::MULTI_EXIT_DISC(m) => med = m,
357 if let Some(mut aspath) = as4_path.or(as_path) {
358 let mut pathvec = Vec::new();
359 for seg in aspath.segments.drain(..) {
361 Segment::AS_SEQUENCE(mut asn) => pathvec.append(&mut asn),
362 Segment::AS_SET(_) => {}, // Ignore sets for now, they're not that common anyway
365 let path_len = pathvec.len() as u32;
366 pathvec.dedup_by(|a, b| (*a).eq(b)); // Drop prepends, cause we don't care in this case
368 let mut path_suffix = [0; PATH_SUFFIX_LEN];
369 for (idx, asn) in pathvec.iter().rev().enumerate() {
370 path_suffix[PATH_SUFFIX_LEN - idx - 1] = *asn;
371 if idx == PATH_SUFFIX_LEN - 1 { break; }
383 fn connect_given_client(addr: SocketAddr, timeout: Duration, printer: &'static Printer, client: Arc<BGPClient>) {
384 tokio::spawn(Delay::new(Instant::now() + timeout / 4).then(move |_| {
385 let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
386 future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
388 let client_reconn = Arc::clone(&client);
389 TcpStream::connect(&addr).select(connect_timeout)
391 Delay::new(Instant::now() + timeout / 2).then(|_| {
394 }).and_then(move |stream| {
395 let (write, read) = Framed::new(stream.0, MsgCoder(None)).split();
396 let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
397 tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
401 let _ = sender.try_send(Message::Open(Open {
404 hold_timer: timeout.as_secs() as u16,
405 identifier: 0x453b1215, // 69.59.18.21
406 parameters: vec![OpenParameter::Capabilities(vec![
407 OpenCapability::MultiProtocol((AFI::IPV4, SAFI::Unicast)),
408 OpenCapability::MultiProtocol((AFI::IPV6, SAFI::Unicast)),
409 OpenCapability::FourByteASN(397444),
410 OpenCapability::RouteRefresh,
411 OpenCapability::AddPath(vec![
412 (AFI::IPV4, SAFI::Unicast, AddPathDirection::ReceivePaths),
413 (AFI::IPV6, SAFI::Unicast, AddPathDirection::ReceivePaths)]),
416 TimeoutStream::new_persistent(read, timeout).for_each(move |bgp_msg| {
417 if client.shutdown.load(Ordering::Relaxed) {
418 return future::err(std::io::Error::new(std::io::ErrorKind::Other, "Shutting Down"));
421 Message::Open(_) => {
422 client.routes.lock().unwrap().v4_table.clear();
423 client.routes.lock().unwrap().v6_table.clear();
424 printer.add_line("Connected to BGP route provider".to_string(), false);
426 Message::KeepAlive => {
427 let _ = sender.try_send(Message::KeepAlive);
429 Message::Update(mut upd) => {
431 let mut route_table = client.routes.lock().unwrap();
432 for r in upd.withdrawn_routes {
433 route_table.withdraw(r);
435 if let Some(path) = Self::map_attrs(upd.attributes) {
436 for r in upd.announced_routes {
437 route_table.announce(r, path.clone());
440 printer.set_stat(Stat::V4RoutingTableSize(route_table.v4_table.len()));
441 printer.set_stat(Stat::V6RoutingTableSize(route_table.v6_table.len()));
442 printer.set_stat(Stat::RoutingTablePaths(route_table.max_paths));
447 }).or_else(move |e| {
448 printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
452 if !client_reconn.shutdown.load(Ordering::Relaxed) {
453 BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
461 pub fn new(addr: SocketAddr, timeout: Duration, printer: &'static Printer) -> Arc<BGPClient> {
462 let client = Arc::new(BGPClient {
463 routes: Mutex::new(RoutingTable::new()),
464 shutdown: AtomicBool::new(false),
466 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));