Update to upstream bgp-rs
[dnsseed-rust] / src / bgp_client.rs
1 use std::sync::{Arc, Mutex};
2 use std::sync::atomic::{AtomicBool, Ordering};
3 use std::cmp;
4 use std::collections::{HashMap, hash_map};
5 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
6 use std::time::{Duration, Instant};
7
8 use bgp_rs::{AFI, SAFI, AddPathDirection, Open, OpenCapability, OpenParameter, NLRIEncoding, PathAttribute};
9 use bgp_rs::Capabilities;
10 use bgp_rs::Segment;
11 use bgp_rs::Message;
12 use bgp_rs::Reader;
13
14 use tokio::prelude::*;
15 use tokio::codec;
16 use tokio::codec::Framed;
17 use tokio::net::TcpStream;
18 use tokio::timer::Delay;
19
20 use futures::sync::mpsc;
21
22 use crate::printer::{Printer, Stat};
23 use crate::timeout_stream::TimeoutStream;
24
25 const PATH_SUFFIX_LEN: usize = 2;
26 #[derive(Clone)]
27 struct Route { // 32 bytes with a path id u32
28         path_suffix: [u32; PATH_SUFFIX_LEN],
29         path_len: u32,
30         pref: u32,
31         med: u32,
32 }
33 #[allow(dead_code)]
34 const ROUTE_LEN: usize = 32 - std::mem::size_of::<(u32, Route)>();
35
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.
38
39 #[repr(packed)]
40 #[derive(PartialEq, Eq, Hash)]
41 struct V4Addr {
42         addr: [u8; 4],
43         pfxlen: u8,
44 }
45 impl From<(Ipv4Addr, u8)> for V4Addr {
46         fn from(p: (Ipv4Addr, u8)) -> Self {
47                 Self {
48                         addr: p.0.octets(),
49                         pfxlen: p.1,
50                 }
51         }
52 }
53 #[allow(dead_code)]
54 const V4_ALIGN: usize = 1 - std::mem::align_of::<V4Addr>();
55 #[allow(dead_code)]
56 const V4_SIZE: usize = 5 - std::mem::size_of::<V4Addr>();
57
58 #[repr(packed)]
59 #[derive(PartialEq, Eq, Hash)]
60 struct V6Addr {
61         addr: [u8; 16],
62         pfxlen: u8,
63 }
64 impl From<(Ipv6Addr, u8)> for V6Addr {
65         fn from(p: (Ipv6Addr, u8)) -> Self {
66                 Self {
67                         addr: p.0.octets(),
68                         pfxlen: p.1,
69                 }
70         }
71 }
72 #[allow(dead_code)]
73 const V6_ALIGN: usize = 1 - std::mem::align_of::<V6Addr>();
74 #[allow(dead_code)]
75 const V6_SIZE: usize = 17 - std::mem::size_of::<V6Addr>();
76
77 struct RoutingTable {
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)>>,
82 }
83
84 impl RoutingTable {
85         fn new() -> Self {
86                 Self {
87                         v4_table: HashMap::new(),
88                         v6_table: HashMap::new(),
89                 }
90         }
91
92         fn get_route_attrs(&self, ip: IpAddr) -> (u8, Vec<&Route>) {
93                 macro_rules! lookup_res {
94                         ($addrty: ty, $addr: expr, $table: expr, $addr_bits: expr) => { {
95                                 //TODO: Optimize this (probably means making the tables btrees)!
96                                 let mut lookup = <$addrty>::from(($addr, $addr_bits));
97                                 for i in 0..$addr_bits {
98                                         if let Some(routes) = $table.get(&lookup) {
99                                                 if routes.len() > 0 {
100                                                         return (lookup.pfxlen, routes.iter().map(|v| &v.1).collect());
101                                                 }
102                                         }
103                                         lookup.addr[lookup.addr.len() - (i/8) - 1] &= !(1u8 << (i % 8));
104                                         lookup.pfxlen -= 1;
105                                 }
106                                 (0, vec![])
107                         } }
108                 }
109                 match ip {
110                         IpAddr::V4(v4a) => lookup_res!(V4Addr, v4a, self.v4_table, 32),
111                         IpAddr::V6(v6a) => lookup_res!(V6Addr, v6a, self.v6_table, 128)
112                 }
113         }
114
115         fn withdraw(&mut self, route: NLRIEncoding) {
116                 macro_rules! remove {
117                         ($rt: expr, $v: expr, $id: expr) => { {
118                                 match $rt.entry($v.into()) {
119                                         hash_map::Entry::Occupied(mut entry) => {
120                                                 entry.get_mut().retain(|e| e.0 != $id);
121                                                 if entry.get_mut().is_empty() {
122                                                         entry.remove();
123                                                 }
124                                         },
125                                         _ => {},
126                                 }
127                         } }
128                 }
129                 match route {
130                         NLRIEncoding::IP(p) => {
131                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
132                                 match ip {
133                                         IpAddr::V4(v4a) => remove!(self.v4_table, (v4a, len), 0),
134                                         IpAddr::V6(v6a) => remove!(self.v6_table, (v6a, len), 0),
135                                 }
136                         },
137                         NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
138                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
139                                 match ip {
140                                         IpAddr::V4(v4a) => remove!(self.v4_table, (v4a, len), id),
141                                         IpAddr::V6(v6a) => remove!(self.v6_table, (v6a, len), id),
142                                 }
143                         },
144                         NLRIEncoding::IP_MPLS(_) => (),
145                         NLRIEncoding::IP_MPLS_WITH_PATH_ID(_) => (),
146                         NLRIEncoding::IP_VPN_MPLS(_) => (),
147                         NLRIEncoding::L2VPN(_) => (),
148                         NLRIEncoding::FLOWSPEC(_) => (),
149                 };
150         }
151
152         fn announce(&mut self, prefix: NLRIEncoding, route: Route) {
153                 macro_rules! insert {
154                         ($rt: expr, $v: expr, $id: expr) => { {
155                                 let entry = $rt.entry($v.into()).or_insert(Vec::new());
156                                 entry.retain(|e| e.0 != $id);
157                                 entry.push(($id, route));
158                         } }
159                 }
160                 match prefix {
161                         NLRIEncoding::IP(p) => {
162                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
163                                 match ip {
164                                         IpAddr::V4(v4a) => insert!(self.v4_table, (v4a, len), 0),
165                                         IpAddr::V6(v6a) => insert!(self.v6_table, (v6a, len), 0),
166                                 }
167                         },
168                         NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
169                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
170                                 match ip {
171                                         IpAddr::V4(v4a) => insert!(self.v4_table, (v4a, len), id),
172                                         IpAddr::V6(v6a) => insert!(self.v6_table, (v6a, len), id),
173                                 }
174                         },
175                         NLRIEncoding::IP_MPLS(_) => (),
176                         NLRIEncoding::IP_MPLS_WITH_PATH_ID(_) => (),
177                         NLRIEncoding::IP_VPN_MPLS(_) => (),
178                         NLRIEncoding::L2VPN(_) => (),
179                         NLRIEncoding::FLOWSPEC(_) => (),
180                 };
181         }
182 }
183
184 struct BytesCoder<'a>(&'a mut bytes::BytesMut);
185 impl<'a> std::io::Write for BytesCoder<'a> {
186         fn write(&mut self, b: &[u8]) -> Result<usize, std::io::Error> {
187                 self.0.extend_from_slice(&b);
188                 Ok(b.len())
189         }
190         fn flush(&mut self) -> Result<(), std::io::Error> {
191                 Ok(())
192         }
193 }
194 struct BytesDecoder<'a> {
195         buf: &'a mut bytes::BytesMut,
196         pos: usize,
197 }
198 impl<'a> std::io::Read for BytesDecoder<'a> {
199         fn read(&mut self, b: &mut [u8]) -> Result<usize, std::io::Error> {
200                 let copy_len = cmp::min(b.len(), self.buf.len() - self.pos);
201                 b[..copy_len].copy_from_slice(&self.buf[self.pos..self.pos + copy_len]);
202                 self.pos += copy_len;
203                 Ok(copy_len)
204         }
205 }
206
207 struct MsgCoder(Option<Capabilities>);
208 impl codec::Decoder for MsgCoder {
209         type Item = Message;
210         type Error = std::io::Error;
211
212         fn decode(&mut self, bytes: &mut bytes::BytesMut) -> Result<Option<Message>, std::io::Error> {
213                 let mut decoder = BytesDecoder {
214                         buf: bytes,
215                         pos: 0
216                 };
217                 let def_cap = Default::default();
218                 let mut reader = Reader {
219                         stream: &mut decoder,
220                         capabilities: if let Some(cap) = &self.0 { cap } else { &def_cap },
221                 };
222                 match reader.read() {
223                         Ok((_header, msg)) => {
224                                 decoder.buf.advance(decoder.pos);
225                                 Ok(Some(msg))
226                         },
227                         Err(e) => match e.kind() {
228                                 std::io::ErrorKind::UnexpectedEof => Ok(None),
229                                 _ => Err(e),
230                         },
231                 }
232         }
233 }
234 impl codec::Encoder for MsgCoder {
235         type Item = Message;
236         type Error = std::io::Error;
237
238         fn encode(&mut self, msg: Message, res: &mut bytes::BytesMut) -> Result<(), std::io::Error> {
239                 msg.encode(&mut BytesCoder(res))?;
240                 Ok(())
241         }
242 }
243
244 pub struct BGPClient {
245         routes: Mutex<RoutingTable>,
246         shutdown: AtomicBool,
247 }
248 impl BGPClient {
249         pub fn get_asn(&self, addr: IpAddr) -> u32 {
250                 let lock = self.routes.lock().unwrap();
251                 let mut path_vecs = lock.get_route_attrs(addr).1;
252                 if path_vecs.is_empty() { return 0; }
253
254                 path_vecs.sort_unstable_by(|path_a, path_b| {
255                         path_a.pref.cmp(&path_b.pref)
256                                 .then(path_b.path_len.cmp(&path_a.path_len))
257                                 .then(path_b.med.cmp(&path_a.med))
258                 });
259
260                 let primary_route = path_vecs.pop().unwrap();
261                 'asn_candidates: for asn in primary_route.path_suffix.iter().rev() {
262                         if *asn == 0 { continue 'asn_candidates; }
263                         for secondary_route in path_vecs.iter() {
264                                 if !secondary_route.path_suffix.contains(asn) {
265                                         continue 'asn_candidates;
266                                 }
267                         }
268                         return *asn;
269                 }
270
271                 for asn in primary_route.path_suffix.iter().rev() {
272                         if *asn != 0 {
273                                 return *asn;
274                         }
275                 }
276                 0
277         }
278
279         pub fn get_path(&self, addr: IpAddr) -> (u8, [u32; PATH_SUFFIX_LEN]) {
280                 let lock = self.routes.lock().unwrap();
281                 let (prefixlen, mut path_vecs) = lock.get_route_attrs(addr);
282                 if path_vecs.is_empty() { return (0, [0; PATH_SUFFIX_LEN]); }
283
284                 path_vecs.sort_unstable_by(|path_a, path_b| {
285                         path_a.pref.cmp(&path_b.pref)
286                                 .then(path_b.path_len.cmp(&path_a.path_len))
287                                 .then(path_b.med.cmp(&path_a.med))
288                 });
289
290                 let primary_route = path_vecs.pop().unwrap();
291                 (prefixlen, primary_route.path_suffix)
292         }
293
294         pub fn disconnect(&self) {
295                 self.shutdown.store(true, Ordering::Relaxed);
296         }
297
298         fn map_attrs(mut attrs: Vec<PathAttribute>) -> Option<Route> {
299                 let mut as4_path = None;
300                 let mut as_path = None;
301                 let mut pref = 100;
302                 let mut med = 0;
303                 for attr in attrs.drain(..) {
304                         match attr {
305                                 PathAttribute::AS4_PATH(path) => as4_path = Some(path),
306                                 PathAttribute::AS_PATH(path) => as_path = Some(path),
307                                 PathAttribute::LOCAL_PREF(p) => pref = p,
308                                 PathAttribute::MULTI_EXIT_DISC(m) => med = m,
309                                 _ => {},
310                         }
311                 }
312                 if let Some(mut aspath) = as4_path.or(as_path) {
313                         let mut pathvec = Vec::new();
314                         for seg in aspath.segments.drain(..) {
315                                 match seg {
316                                         Segment::AS_SEQUENCE(mut asn) => pathvec.append(&mut asn),
317                                         Segment::AS_SET(_) => {}, // Ignore sets for now, they're not that common anyway
318                                 }
319                         }
320                         let path_len = pathvec.len() as u32;
321                         pathvec.dedup_by(|a, b| (*a).eq(b)); // Drop prepends, cause we don't care in this case
322
323                         let mut path_suffix = [0; PATH_SUFFIX_LEN];
324                         for (idx, asn) in pathvec.iter().rev().enumerate() {
325                                 path_suffix[PATH_SUFFIX_LEN - idx - 1] = *asn;
326                                 if idx == PATH_SUFFIX_LEN - 1 { break; }
327                         }
328
329                         return Some(Route {
330                                 path_suffix,
331                                 path_len,
332                                 pref,
333                                 med,
334                         })
335                 } else { None }
336         }
337
338         fn connect_given_client(addr: SocketAddr, timeout: Duration, printer: &'static Printer, client: Arc<BGPClient>) {
339                 tokio::spawn(Delay::new(Instant::now() + timeout / 4).then(move |_| {
340                         let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
341                                 future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
342                         });
343                         let client_reconn = Arc::clone(&client);
344                         TcpStream::connect(&addr).select(connect_timeout)
345                                 .or_else(move |_| {
346                                         Delay::new(Instant::now() + timeout / 2).then(|_| {
347                                                 future::err(())
348                                         })
349                                 }).and_then(move |stream| {
350                                         let (write, read) = Framed::new(stream.0, MsgCoder(None)).split();
351                                         let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
352                                         tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
353                                                 .then(|_| {
354                                                         future::err(())
355                                                 }));
356                                         let _ = sender.try_send(Message::Open(Open {
357                                                 version: 4,
358                                                 peer_asn: 23456,
359                                                 hold_timer: timeout.as_secs() as u16,
360                                                 identifier: 0x453b1215, // 69.59.18.21
361                                                 parameters: vec![OpenParameter::Capabilities(vec![
362                                                         OpenCapability::MultiProtocol((AFI::IPV4, SAFI::Unicast)),
363                                                         OpenCapability::MultiProtocol((AFI::IPV6, SAFI::Unicast)),
364                                                         OpenCapability::FourByteASN(397444),
365                                                         OpenCapability::RouteRefresh,
366                                                         OpenCapability::AddPath(vec![
367                                                                 (AFI::IPV4, SAFI::Unicast, AddPathDirection::ReceivePaths),
368                                                                 (AFI::IPV6, SAFI::Unicast, AddPathDirection::ReceivePaths)]),
369                                                 ])],
370                                         }));
371                                         TimeoutStream::new_persistent(read, timeout).for_each(move |bgp_msg| {
372                                                 if client.shutdown.load(Ordering::Relaxed) {
373                                                         return future::err(std::io::Error::new(std::io::ErrorKind::Other, "Shutting Down"));
374                                                 }
375                                                 match bgp_msg {
376                                                         Message::Open(_) => {
377                                                                 client.routes.lock().unwrap().v4_table.clear();
378                                                                 client.routes.lock().unwrap().v6_table.clear();
379                                                                 printer.add_line("Connected to BGP route provider".to_string(), false);
380                                                         },
381                                                         Message::KeepAlive => {
382                                                                 let _ = sender.try_send(Message::KeepAlive);
383                                                         },
384                                                         Message::Update(mut upd) => {
385                                                                 upd.normalize();
386                                                                 let mut route_table = client.routes.lock().unwrap();
387                                                                 for r in upd.withdrawn_routes {
388                                                                         route_table.withdraw(r);
389                                                                 }
390                                                                 if let Some(path) = Self::map_attrs(upd.attributes) {
391                                                                         for r in upd.announced_routes {
392                                                                                 route_table.announce(r, path.clone());
393                                                                         }
394                                                                 }
395                                                                 printer.set_stat(Stat::V4RoutingTableSize(route_table.v4_table.len()));
396                                                                 printer.set_stat(Stat::V6RoutingTableSize(route_table.v6_table.len()));
397                                                         },
398                                                         _ => {}
399                                                 }
400                                                 future::ok(())
401                                         }).or_else(move |e| {
402                                                 printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
403                                                 future::ok(())
404                                         })
405                                 }).then(move |_| {
406                                         if !client_reconn.shutdown.load(Ordering::Relaxed) {
407                                                 BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
408                                         }
409                                         future::ok(())
410                                 })
411                         })
412                 );
413         }
414
415         pub fn new(addr: SocketAddr, timeout: Duration, printer: &'static Printer) -> Arc<BGPClient> {
416                 let client = Arc::new(BGPClient {
417                         routes: Mutex::new(RoutingTable::new()),
418                         shutdown: AtomicBool::new(false),
419                 });
420                 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));
421                 client
422         }
423 }