Select only ASNs visible in all paths for an IP
[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::ops::Bound::Included;
5 use std::collections::BTreeMap;
6 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
7 use std::time::{Duration, Instant};
8
9 use bgp_rs::{AFI, SAFI, AddPathDirection, Open, OpenCapability, OpenParameter, NLRIEncoding, PathAttribute};
10 use bgp_rs::Capabilities;
11 use bgp_rs::Segment;
12 use bgp_rs::Message;
13 use bgp_rs::Reader;
14
15 use tokio::prelude::*;
16 use tokio::codec;
17 use tokio::codec::Framed;
18 use tokio::net::TcpStream;
19 use tokio::timer::Delay;
20
21 use futures::sync::mpsc;
22
23 use crate::printer::Printer;
24
25 struct Route {
26         path: Vec<u32>,
27         pref: u32,
28         med: u32,
29 }
30
31 struct RoutingTable {
32         v4_table: BTreeMap<(Ipv4Addr, u8, u32), Arc<Route>>,
33         v6_table: BTreeMap<(Ipv6Addr, u8, u32), Arc<Route>>,
34 }
35
36 impl RoutingTable {
37         fn new() -> Self {
38                 Self {
39                         v4_table: BTreeMap::new(),
40                         v6_table: BTreeMap::new(),
41                 }
42         }
43
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();
51                                         for b in 0..(i / 8) {
52                                                 lookup[lookup.len() - b - 1] = 0;
53                                         }
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));
58                                         }
59                                         if !res.is_empty() { break; }
60                                 }
61                                 res
62                         } }
63                 }
64                 match ip {
65                         IpAddr::V4(v4a) => lookup_res!(Ipv4Addr, v4a, self.v4_table, 32),
66                         IpAddr::V6(v6a) => lookup_res!(Ipv6Addr, v6a, self.v6_table, 128)
67                 }
68         }
69
70         fn withdraw(&mut self, route: NLRIEncoding) {
71                 match route {
72                         NLRIEncoding::IP(p) => {
73                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
74                                 match ip {
75                                         IpAddr::V4(v4a) => self.v4_table.remove(&(v4a, len, 0)),
76                                         IpAddr::V6(v6a) => self.v6_table.remove(&(v6a, len, 0)),
77                                 }
78                         },
79                         NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
80                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
81                                 match ip {
82                                         IpAddr::V4(v4a) => self.v4_table.remove(&(v4a, len, id)),
83                                         IpAddr::V6(v6a) => self.v6_table.remove(&(v6a, len, id)),
84                                 }
85                         },
86                         NLRIEncoding::IP_MPLS(_) => None,
87                 };
88         }
89
90         fn announce(&mut self, prefix: NLRIEncoding, route: Arc<Route>) {
91                 match prefix {
92                         NLRIEncoding::IP(p) => {
93                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
94                                 match ip {
95                                         IpAddr::V4(v4a) => self.v4_table.insert((v4a, len, 0), route),
96                                         IpAddr::V6(v6a) => self.v6_table.insert((v6a, len, 0), route),
97                                 }
98                         },
99                         NLRIEncoding::IP_WITH_PATH_ID((p, id)) => {
100                                 let (ip, len) = <(IpAddr, u8)>::from(&p);
101                                 match ip {
102                                         IpAddr::V4(v4a) => self.v4_table.insert((v4a, len, id), route),
103                                         IpAddr::V6(v6a) => self.v6_table.insert((v6a, len, id), route),
104                                 }
105                         },
106                         NLRIEncoding::IP_MPLS(_) => None,
107                 };
108         }
109 }
110
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);
115                 Ok(b.len())
116         }
117         fn flush(&mut self) -> Result<(), std::io::Error> {
118                 Ok(())
119         }
120 }
121 struct BytesDecoder<'a> {
122         buf: &'a mut bytes::BytesMut,
123         pos: usize,
124 }
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;
130                 Ok(copy_len)
131         }
132 }
133
134 struct MsgCoder<'a>(&'a Printer);
135 impl<'a> codec::Decoder for MsgCoder<'a> {
136         type Item = Message;
137         type Error = std::io::Error;
138
139         fn decode(&mut self, bytes: &mut bytes::BytesMut) -> Result<Option<Message>, std::io::Error> {
140                 let mut decoder = BytesDecoder {
141                         buf: bytes,
142                         pos: 0
143                 };
144                 match (Reader {
145                         stream: &mut decoder,
146                         capabilities: Capabilities {
147                                 FOUR_OCTET_ASN_SUPPORT: true,
148                                 EXTENDED_PATH_NLRI_SUPPORT: true,
149                         }
150                 }).read() {
151                         Ok((_header, msg)) => {
152                                 decoder.buf.advance(decoder.pos);
153                                 Ok(Some(msg))
154                         },
155                         Err(e) => match e.kind() {
156                                 std::io::ErrorKind::UnexpectedEof => Ok(None),
157                                 _ => Err(e),
158                         },
159                 }
160         }
161 }
162 impl<'a> codec::Encoder for MsgCoder<'a> {
163         type Item = Message;
164         type Error = std::io::Error;
165
166         fn encode(&mut self, msg: Message, res: &mut bytes::BytesMut) -> Result<(), std::io::Error> {
167                 msg.write(&mut BytesCoder(res))?;
168                 Ok(())
169         }
170 }
171
172 pub struct BGPClient {
173         routes: Mutex<RoutingTable>,
174         shutdown: AtomicBool,
175 }
176 impl BGPClient {
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; }
180
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))
185                 });
186
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;
192                                 }
193                         }
194                         return *asn;
195                 }
196                 *primary_route.path.last().unwrap_or(&0)
197         }
198
199         pub fn disconnect(&self) {
200                 self.shutdown.store(true, Ordering::Relaxed);
201         }
202
203         fn map_attrs(mut attrs: Vec<PathAttribute>) -> Option<Route> {
204                 let mut as4_path = None;
205                 let mut as_path = None;
206                 let mut pref = 100;
207                 let mut med = 0;
208                 for attr in attrs.drain(..) {
209                         match attr {
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,
214                                 _ => {},
215                         }
216                 }
217                 if let Some(mut aspath) = as4_path.or(as_path) {
218                         let mut path = Vec::new();
219                         for seg in aspath.segments.drain(..) {
220                                 match seg {
221                                         Segment::AS_SEQUENCE(mut asn) => path.append(&mut asn),
222                                         Segment::AS_SET(_) => {}, // Ignore sets for now, they're not that common anyway
223                                 }
224                         }
225                         return Some(Route {
226                                 path: path.clone(),
227                                 pref,
228                                 med,
229                         })
230                 } else { None }
231         }
232
233         fn connect_given_client(addr: SocketAddr, timeout: Duration, printer: &'static Printer, client: Arc<BGPClient>) {
234                 let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
235                         future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
236                 });
237                 let client_reconn = Arc::clone(&client);
238                 tokio::spawn(TcpStream::connect(&addr).select(connect_timeout)
239                         .or_else(move |_| {
240                                 Delay::new(Instant::now() + timeout / 10).then(|_| {
241                                         future::err(())
242                                 })
243                         }).and_then(move |stream| {
244                                 let (write, read) = Framed::new(stream.0, MsgCoder(printer)).split();
245                                 let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
246                                 tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
247                                         .then(|_| {
248                                                 future::err(())
249                                         }));
250                                 let _ = sender.try_send(Message::Open(Open {
251                                         version: 4,
252                                         peer_asn: 23456,
253                                         hold_timer: 120,
254                                         identifier: 0x453b1215, // 69.59.18.21
255                                         parameters: vec![OpenParameter::Capabilities(vec![
256                                                 OpenCapability::MultiProtocol((AFI::IPV4, SAFI::Unicast)),
257                                                 OpenCapability::MultiProtocol((AFI::IPV6, SAFI::Unicast)),
258                                                 OpenCapability::FourByteASN(397444),
259                                                 OpenCapability::RouteRefresh,
260                                                 OpenCapability::AddPath(vec![
261                                                         (AFI::IPV4, SAFI::Unicast, AddPathDirection::ReceivePaths),
262                                                         (AFI::IPV6, SAFI::Unicast, AddPathDirection::ReceivePaths)]),
263                                         ])]
264                                 }));
265                                 read.for_each(move |bgp_msg| {
266                                         if client.shutdown.load(Ordering::Relaxed) {
267                                                 return future::err(std::io::Error::new(std::io::ErrorKind::Other, "Shutting Down"));
268                                         }
269                                         match bgp_msg {
270                                                 Message::Open(_) => {
271                                                         client.routes.lock().unwrap().v4_table.clear();
272                                                         client.routes.lock().unwrap().v6_table.clear();
273                                                         printer.add_line("Connected to BGP route provider".to_string(), false);
274                                                 },
275                                                 Message::KeepAlive => {
276                                                         let _ = sender.try_send(Message::KeepAlive);
277                                                 },
278                                                 Message::Update(mut upd) => {
279                                                         upd.normalize();
280                                                         let mut route_table = client.routes.lock().unwrap();
281                                                         for r in upd.withdrawn_routes {
282                                                                 route_table.withdraw(r);
283                                                         }
284                                                         if let Some(path) = Self::map_attrs(upd.attributes) {
285                                                                 let path_arc = Arc::new(path);
286                                                                 for r in upd.announced_routes {
287                                                                         route_table.announce(r, Arc::clone(&path_arc));
288                                                                 }
289                                                         }
290                                                 },
291                                                 _ => {}
292                                         }
293                                         future::ok(())
294                                 }).or_else(move |e| {
295                                         printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
296                                         future::ok(())
297                                 })
298                         }).then(move |_| {
299                                 if !client_reconn.shutdown.load(Ordering::Relaxed) {
300                                         BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
301                                 }
302                                 future::ok(())
303                         })
304                 );
305         }
306
307         pub fn new(addr: SocketAddr, timeout: Duration, printer: &'static Printer) -> Arc<BGPClient> {
308                 let client = Arc::new(BGPClient {
309                         routes: Mutex::new(RoutingTable::new()),
310                         shutdown: AtomicBool::new(false),
311                 });
312                 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));
313                 client
314         }
315 }