Avoid storing unused attrs
[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 + 1)).rev() {
50                                         let mut lookup = $addr.octets();
51                                         for b in 0..(i / 8) {
52                                                 lookup[lookup.len() - b] = 0;
53                                         }
54                                         lookup[lookup.len() - (i/8)] &= !(((1u16 << (i % 8)) - 1) as u8);
55                                         let lookup_addr = <$addrty>::from(lookup);
56                                         for attrs in $table.range((Included((lookup_addr, $addr_bits, 0)), Included((lookup_addr, $addr_bits, 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                 path_vecs.sort_unstable_by(|path_a, path_b| {
180                         path_a.pref.cmp(&path_b.pref)
181                                 .then(path_b.path.len().cmp(&path_a.path.len()))
182                                 .then(path_b.med.cmp(&path_a.med))
183                 });
184                 // TODO: Find last common ASN among all paths
185                 *path_vecs[0].path.last().unwrap_or(&0)
186         }
187
188         pub fn disconnect(&self) {
189                 self.shutdown.store(true, Ordering::Relaxed);
190         }
191
192         fn map_attrs(mut attrs: Vec<PathAttribute>) -> Option<Route> {
193                 let mut as4_path = None;
194                 let mut as_path = None;
195                 let mut pref = 100;
196                 let mut med = 0;
197                 for attr in attrs.drain(..) {
198                         match attr {
199                                 PathAttribute::AS4_PATH(path) => as4_path = Some(path),
200                                 PathAttribute::AS_PATH(path) => as_path = Some(path),
201                                 PathAttribute::LOCAL_PREF(p) => pref = p,
202                                 PathAttribute::MULTI_EXIT_DISC(m) => med = m,
203                                 _ => {},
204                         }
205                 }
206                 if let Some(mut aspath) = as4_path.or(as_path) {
207                         let mut path = Vec::new();
208                         for seg in aspath.segments.drain(..) {
209                                 match seg {
210                                         Segment::AS_SEQUENCE(mut asn) => path.append(&mut asn),
211                                         Segment::AS_SET(_) => {}, // Ignore sets for now, they're not that common anyway
212                                 }
213                         }
214                         return Some(Route {
215                                 path: path.clone(),
216                                 pref,
217                                 med,
218                         })
219                 } else { None }
220         }
221
222         fn connect_given_client(addr: SocketAddr, timeout: Duration, printer: &'static Printer, client: Arc<BGPClient>) {
223                 let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
224                         future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
225                 });
226                 let client_reconn = Arc::clone(&client);
227                 tokio::spawn(TcpStream::connect(&addr).select(connect_timeout)
228                         .or_else(move |_| {
229                                 Delay::new(Instant::now() + timeout / 10).then(|_| {
230                                         future::err(())
231                                 })
232                         }).and_then(move |stream| {
233                                 let (write, read) = Framed::new(stream.0, MsgCoder(printer)).split();
234                                 let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
235                                 tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
236                                         .then(|_| {
237                                                 future::err(())
238                                         }));
239                                 let _ = sender.try_send(Message::Open(Open {
240                                         version: 4,
241                                         peer_asn: 23456,
242                                         hold_timer: 120,
243                                         identifier: 0x453b1215, // 69.59.18.21
244                                         parameters: vec![OpenParameter::Capabilities(vec![
245                                                 OpenCapability::MultiProtocol((AFI::IPV4, SAFI::Unicast)),
246                                                 OpenCapability::MultiProtocol((AFI::IPV6, SAFI::Unicast)),
247                                                 OpenCapability::FourByteASN(397444),
248                                                 OpenCapability::RouteRefresh,
249                                                 OpenCapability::AddPath(vec![
250                                                         (AFI::IPV4, SAFI::Unicast, AddPathDirection::ReceivePaths),
251                                                         (AFI::IPV6, SAFI::Unicast, AddPathDirection::ReceivePaths)]),
252                                         ])]
253                                 }));
254                                 read.for_each(move |bgp_msg| {
255                                         if client.shutdown.load(Ordering::Relaxed) {
256                                                 return future::err(std::io::Error::new(std::io::ErrorKind::Other, "Shutting Down"));
257                                         }
258                                         match bgp_msg {
259                                                 Message::Open(_) => {
260                                                         printer.add_line("Connected to BGP route provider".to_string(), true);
261                                                 },
262                                                 Message::KeepAlive => {
263                                                         let _ = sender.try_send(Message::KeepAlive);
264                                                 },
265                                                 Message::Update(mut upd) => {
266                                                         upd.normalize();
267                                                         let mut route_table = client.routes.lock().unwrap();
268                                                         for r in upd.withdrawn_routes {
269                                                                 route_table.withdraw(r);
270                                                         }
271                                                         if let Some(path) = Self::map_attrs(upd.attributes) {
272                                                                 let path_arc = Arc::new(path);
273                                                                 for r in upd.announced_routes {
274                                                                         route_table.announce(r, Arc::clone(&path_arc));
275                                                                 }
276                                                         }
277                                                 },
278                                                 _ => {}
279                                         }
280                                         future::ok(())
281                                 }).or_else(move |e| {
282                                         printer.add_line(format!("Got error from BGP stream: {:?}", e), true);
283                                         future::ok(())
284                                 })
285                         }).then(move |_| {
286                                 if !client_reconn.shutdown.load(Ordering::Relaxed) {
287                                         BGPClient::connect_given_client(addr, timeout, printer, client_reconn);
288                                 }
289                                 future::ok(())
290                         })
291                 );
292         }
293
294         pub fn new(addr: SocketAddr, timeout: Duration, printer: &'static Printer) -> Arc<BGPClient> {
295                 let client = Arc::new(BGPClient {
296                         routes: Mutex::new(RoutingTable::new()),
297                         shutdown: AtomicBool::new(false),
298                 });
299                 BGPClient::connect_given_client(addr, timeout, printer, Arc::clone(&client));
300                 client
301         }
302 }