1 use std::sync::{Arc, Mutex};
2 use std::sync::atomic::{AtomicBool, Ordering};
4 use std::collections::HashMap;
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;
32 v4_table: HashMap<(Ipv4Addr, u8), HashMap<u32, Arc<Route>>>,
33 v6_table: HashMap<(Ipv6Addr, u8), HashMap<u32, Arc<Route>>>,
39 v4_table: HashMap::new(),
40 v6_table: HashMap::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 //TODO: Optimize this (probably means making the tables btrees)!
48 for i in (0..$addr_bits).rev() {
49 let mut lookup = $addr.octets();
51 lookup[lookup.len() - b - 1] = 0;
53 lookup[lookup.len() - (i/8) - 1] &= !(((1u16 << (i % 8)) - 1) as u8);
54 let lookup_addr = <$addrty>::from(lookup);
55 if let Some(routes) = $table.get(&(lookup_addr, $addr_bits - i as u8)).map(|hm| hm.values()) {
57 return routes.map(|x| Arc::clone(&x)).collect();
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.get_mut(&(v4a, len)).and_then(|hm| hm.remove(&0)),
76 IpAddr::V6(v6a) => self.v6_table.get_mut(&(v6a, len)).and_then(|hm| hm.remove(&0)),
79 NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
80 let (ip, len) = <(IpAddr, u8)>::from(&p);
82 IpAddr::V4(v4a) => self.v4_table.get_mut(&(v4a, len)).and_then(|hm| hm.remove(&id)),
83 IpAddr::V6(v6a) => self.v6_table.get_mut(&(v6a, len)).and_then(|hm| hm.remove(&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.entry((v4a, len)).or_insert(HashMap::new()).insert(0, route),
96 IpAddr::V6(v6a) => self.v6_table.entry((v6a, len)).or_insert(HashMap::new()).insert(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.entry((v4a, len)).or_insert(HashMap::new()).insert(id, route),
103 IpAddr::V6(v6a) => self.v6_table.entry((v6a, len)).or_insert(HashMap::new()).insert(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 if path_vecs.is_empty() { return 0; }
181 path_vecs.sort_unstable_by(|path_a, path_b| {
182 path_a.pref.cmp(&path_b.pref)
183 .then(path_b.path.len().cmp(&path_a.path.len()))
184 .then(path_b.med.cmp(&path_a.med))
187 let primary_route = path_vecs.pop().unwrap();
188 'asn_candidates: for asn in primary_route.path.iter().rev() {
189 for secondary_route in path_vecs.iter() {
190 if !secondary_route.path.contains(asn) {
191 continue 'asn_candidates;
196 *primary_route.path.last().unwrap_or(&0)
199 pub fn disconnect(&self) {
200 self.shutdown.store(true, Ordering::Relaxed);
203 fn map_attrs(mut attrs: Vec<PathAttribute>) -> Option<Route> {
204 let mut as4_path = None;
205 let mut as_path = None;
208 for attr in attrs.drain(..) {
210 PathAttribute::AS4_PATH(path) => as4_path = Some(path),
211 PathAttribute::AS_PATH(path) => as_path = Some(path),
212 PathAttribute::LOCAL_PREF(p) => pref = p,
213 PathAttribute::MULTI_EXIT_DISC(m) => med = m,
217 if let Some(mut aspath) = as4_path.or(as_path) {
218 let mut path = Vec::new();
219 for seg in aspath.segments.drain(..) {
221 Segment::AS_SEQUENCE(mut asn) => path.append(&mut asn),
222 Segment::AS_SET(_) => {}, // Ignore sets for now, they're not that common anyway
233 fn connect_given_client(addr: SocketAddr, timeout: Duration, printer: &'static Printer, client: Arc<BGPClient>) {
234 tokio::spawn(Delay::new(Instant::now() + timeout / 4).then(move |_| {
235 let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
236 future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
238 let client_reconn = Arc::clone(&client);
239 TcpStream::connect(&addr).select(connect_timeout)
241 Delay::new(Instant::now() + timeout / 2).then(|_| {
244 }).and_then(move |stream| {
245 let (write, read) = Framed::new(stream.0, MsgCoder(printer)).split();
246 let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
247 tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
251 let _ = sender.try_send(Message::Open(Open {
254 hold_timer: timeout.as_secs() as u16,
255 identifier: 0x453b1215, // 69.59.18.21
256 parameters: vec![OpenParameter::Capabilities(vec![
257 OpenCapability::MultiProtocol((AFI::IPV4, SAFI::Unicast)),
258 OpenCapability::MultiProtocol((AFI::IPV6, SAFI::Unicast)),
259 OpenCapability::FourByteASN(397444),
260 OpenCapability::RouteRefresh,
261 OpenCapability::AddPath(vec![
262 (AFI::IPV4, SAFI::Unicast, AddPathDirection::ReceivePaths),
263 (AFI::IPV6, SAFI::Unicast, AddPathDirection::ReceivePaths)]),
266 TimeoutStream::new_persistent(read, timeout).for_each(move |bgp_msg| {
267 if client.shutdown.load(Ordering::Relaxed) {
268 return future::err(std::io::Error::new(std::io::ErrorKind::Other, "Shutting Down"));
271 Message::Open(_) => {
272 client.routes.lock().unwrap().v4_table.clear();
273 client.routes.lock().unwrap().v6_table.clear();
274 printer.add_line("Connected to BGP route provider".to_string(), false);
276 Message::KeepAlive => {
277 let _ = sender.try_send(Message::KeepAlive);
279 Message::Update(mut upd) => {
281 let mut route_table = client.routes.lock().unwrap();
282 for r in upd.withdrawn_routes {
283 route_table.withdraw(r);
285 if let Some(path) = Self::map_attrs(upd.attributes) {
286 let path_arc = Arc::new(path);
287 for r in upd.announced_routes {
288 route_table.announce(r, Arc::clone(&path_arc));
291 printer.set_stat(Stat::V4RoutingTableSize(route_table.v4_table.len()));
292 printer.set_stat(Stat::V6RoutingTableSize(route_table.v6_table.len()));
297 }).or_else(move |e| {
298 printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
302 if !client_reconn.shutdown.load(Ordering::Relaxed) {
303 BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
311 pub fn new(addr: SocketAddr, timeout: Duration, printer: &'static Printer) -> Arc<BGPClient> {
312 let client = Arc::new(BGPClient {
313 routes: Mutex::new(RoutingTable::new()),
314 shutdown: AtomicBool::new(false),
316 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));