04be1360c930cc6d01f65bd57f5f44340c4777a9
[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;
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 struct Route {
26         path: Vec<u32>,
27         pref: u32,
28         med: u32,
29 }
30
31 struct RoutingTable {
32         v4_table: HashMap<(Ipv4Addr, u8), HashMap<u32, Arc<Route>>>,
33         v6_table: HashMap<(Ipv6Addr, u8), HashMap<u32, Arc<Route>>>,
34 }
35
36 impl RoutingTable {
37         fn new() -> Self {
38                 Self {
39                         v4_table: HashMap::new(),
40                         v6_table: HashMap::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                                 //TODO: Optimize this (probably means making the tables btrees)!
48                                 for i in (0..$addr_bits).rev() {
49                                         let mut lookup = $addr.octets();
50                                         for b in 0..(i / 8) {
51                                                 lookup[lookup.len() - b - 1] = 0;
52                                         }
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()) {
56                                                 if routes.len() > 0 {
57                                                         return routes.map(|x| Arc::clone(&x)).collect();
58                                                 }
59                                         }
60                                 }
61                                 vec![]
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.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)),
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.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)),
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.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),
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.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),
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                 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"))
237                         });
238                         let client_reconn = Arc::clone(&client);
239                         TcpStream::connect(&addr).select(connect_timeout)
240                                 .or_else(move |_| {
241                                         Delay::new(Instant::now() + timeout / 2).then(|_| {
242                                                 future::err(())
243                                         })
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)
248                                                 .then(|_| {
249                                                         future::err(())
250                                                 }));
251                                         let _ = sender.try_send(Message::Open(Open {
252                                                 version: 4,
253                                                 peer_asn: 23456,
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)]),
264                                                 ])]
265                                         }));
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"));
269                                                 }
270                                                 match bgp_msg {
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);
275                                                         },
276                                                         Message::KeepAlive => {
277                                                                 let _ = sender.try_send(Message::KeepAlive);
278                                                         },
279                                                         Message::Update(mut upd) => {
280                                                                 upd.normalize();
281                                                                 let mut route_table = client.routes.lock().unwrap();
282                                                                 for r in upd.withdrawn_routes {
283                                                                         route_table.withdraw(r);
284                                                                 }
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));
289                                                                         }
290                                                                 }
291                                                                 printer.set_stat(Stat::V4RoutingTableSize(route_table.v4_table.len()));
292                                                                 printer.set_stat(Stat::V6RoutingTableSize(route_table.v6_table.len()));
293                                                         },
294                                                         _ => {}
295                                                 }
296                                                 future::ok(())
297                                         }).or_else(move |e| {
298                                                 printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
299                                                 future::ok(())
300                                         })
301                                 }).then(move |_| {
302                                         if !client_reconn.shutdown.load(Ordering::Relaxed) {
303                                                 BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
304                                         }
305                                         future::ok(())
306                                 })
307                         })
308                 );
309         }
310
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),
315                 });
316                 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));
317                 client
318         }
319 }