1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::{ops::Deref, str::FromStr, sync::Arc};
use arc_swap::{ArcSwap, ArcSwapOption};
use async_trait::async_trait;
use hyper::{Body, Method, Request, Response};
use inetnum::{addr::Prefix, asn::Asn};
use log::{debug, trace};
use rotonda_store::match_options::{self, IncludeHistory, MatchOptions};
use routecore::bgp::communities::HumanReadableCommunity as Community;
use tokio::sync::oneshot;
use uuid::Uuid;
use crate::{
comms::{Link, TriggerData},
http::{
extract_params, get_all_params, get_param, MatchedParam,
PercentDecodedPath, ProcessRequest, QueryParams,
},
ingress,
units::{
rib_unit::{
http::types::{FilterKind, FilterOp},
rib::Rib,
unit::{PendingVirtualRibQueryResults, QueryLimits},
},
RibType,
},
};
use super::types::{Details, Filter, FilterMode, Filters, Includes, SortKey};
pub struct PrefixesApi {
rib: Arc<ArcSwap<Rib>>,
http_api_path: Arc<String>,
query_limits: Arc<ArcSwap<QueryLimits>>,
rib_type: RibType,
vrib_upstream: Arc<ArcSwapOption<Link>>,
pending_vrib_query_results: Arc<PendingVirtualRibQueryResults>,
ingress_register: Arc<ingress::Register>,
}
impl PrefixesApi {
pub fn new(
rib: Arc<ArcSwap<Rib>>,
http_api_path: Arc<String>,
query_limits: Arc<ArcSwap<QueryLimits>>,
rib_type: RibType,
vrib_upstream: Option<Link>,
pending_vrib_query_results: Arc<PendingVirtualRibQueryResults>,
ingress_register: Arc<ingress::Register>,
) -> Self {
Self {
rib,
http_api_path,
query_limits,
rib_type,
vrib_upstream: Arc::new(ArcSwapOption::from_pointee(
vrib_upstream,
)),
pending_vrib_query_results,
ingress_register,
}
}
pub fn http_api_path(&self) -> &String {
self.http_api_path.as_ref()
}
pub fn set_vrib_upstream(&self, vrib_upstream: Option<Link>) {
self.vrib_upstream.store(vrib_upstream.map(Arc::new));
}
}
#[async_trait]
impl ProcessRequest for PrefixesApi {
async fn process_request(
&self,
request: &Request<Body>,
) -> Option<Response<Body>> {
// Percent decoding the path shouldn't be necessary for the requests
// we support at the moment, but later it may matter, and it shouldn't
// hurt, and it's been demonstrated that there are clients that encode
// the URL path component when perhaps (not that clear from RFC 3986)
// they don't have to (e.g. when the path component contains a ':' as
// in an IPv6 address). Let's be lenient about the UTF-8 decoding as
// well while we are at it...
let req_path = &request.uri().decoded_path();
debug!("RibUnit ProcessRequest {:?}", &req_path);
// e.g. req_path = "/prefixes/2804:1398:100::/48"
if request.method() == Method::GET
&& req_path.starts_with(self.http_api_path.deref())
{
let res = match request.uri().path().split("/").count() {
3 => self.handle_ingress_id_query(req_path, request).await,
_ => self.handle_prefix_query(req_path, request).await,
};
match res {
Ok(res) => Some(res),
Err(err) => Some(
Response::builder()
.status(hyper::StatusCode::BAD_REQUEST)
.header("Content-Type", "text/plain")
.body(err.into())
.unwrap(),
),
}
} else {
// Start of HTTP relative URL did not match the one defined for
// this processor
None
}
}
}
impl PrefixesApi {
async fn handle_prefix_query(
&self,
req_path: &str,
request: &Request<Body>,
) -> Result<Response<Body>, String> {
debug!("in handle_prefix_query");
let prefix = Prefix::from_str(
req_path.strip_prefix(self.http_api_path.as_str()).unwrap(),
) // SAFETY: unwrap() safe due to starts_with() check above
.map_err(|err| err.to_string())?;
//
// Handle query parameters
//
let params = extract_params(request);
let includes = Self::parse_include_param(
¶ms,
self.query_limits.clone(),
prefix,
)?;
let details = Self::parse_details_param(¶ms)?;
let filters = Self::parse_filter_params(¶ms)?;
let sort = Self::parse_sort_params(¶ms)?;
let format = get_param(¶ms, "format");
//
// Check for unused params
//
let unused_params: Vec<&str> = params
.iter()
.filter(|param| !param.used())
.map(|param| param.name())
.collect();
if !unused_params.is_empty() {
return Err(format!(
"Unrecognized query parameters: {}",
unused_params.join(",")
));
}
//
// Query the prefix store
//
// For a physical RIB we own the store and can query it directly. For
// a virtual RIB we must send a query command to store nearest to our
// Western edge, which we've been given a Link to so we can send it
// commands. Once we've sent it the query command we then have to wait
// to receive the query result back.
//
let options = MatchOptions {
match_type: match_options::MatchType::ExactMatch,
include_less_specifics: includes.less_specifics,
include_more_specifics: includes.more_specifics,
include_withdrawn: true,
mui: None,
include_history: IncludeHistory::None,
};
// XXX res: QueryResult will be different
let res = match self.rib_type {
RibType::Physical => {
// XXX res: QueryResult will be different
match self.rib.load().match_prefix(&prefix, &options) {
Ok(res) => res,
Err(e) => {
let res = Response::builder()
.status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
.header("Content-Type", "text/plain")
.body(
"Cannot query non-existent RIB store"
.to_string()
.into(),
)
.unwrap();
return Ok(res);
}
}
/*
if let Ok(store) = self.rib.load().store() {
store.match_prefix(&prefix, &options, guard)
} else {
let res = Response::builder()
.status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
.header("Content-Type", "text/plain")
.body(
"Cannot query non-existent RIB store"
.to_string()
.into(),
)
.unwrap();
return Ok(res);
}
*/
}
RibType::GeneratedVirtual(_) | RibType::Virtual => {
trace!("Handling virtual RIB query");
// Generate a unique query ID to tie the request and later
// response together.
let uuid = Uuid::new_v4();
// XXX LH: eventually, this should be broadened to carry NLRI
// other than simple prefixes.
let data = TriggerData::MatchPrefix(uuid, prefix, options);
// Create a oneshot channel and store the sender to it by the
// query ID we generated.
let (tx, rx) = oneshot::channel();
self.pending_vrib_query_results.insert(uuid, Arc::new(tx));
// Send a command asynchronously to the upstream physical RIB
// unit to perform the desired query on its store and to send
// the result back to us through the pipeline (being operated
// on as necessary by any intermediate virtual RIB roto
// scripts). This command includes the query ID that we
// generated.
trace!("Triggering upstream physical RIB {} to do the actual query", self.vrib_upstream.load().as_ref().unwrap().id());
self.vrib_upstream
.load()
.as_ref()
.unwrap()
.trigger(data)
.await;
// Wait for the main unit which operates the Gate to receive a
// Query Result that matches the query ID we just generated,
// and to pick the oneshot channel by query ID and use it to
// pass the results to us.
trace!("Waiting for physical RIB query result to arrive");
match rx.await {
Ok(Ok(query_result)) => {
trace!("Physical RIB query result received");
query_result
}
Ok(Err(err)) => {
trace!("Internal error: {}", err);
let res = Response::builder()
.status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
.header("Content-Type", "text/plain")
.body(err.into())
.unwrap();
return Ok(res);
}
Err(err) => {
trace!("Internal error: {}", err);
let res = Response::builder()
.status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
.header("Content-Type", "text/plain")
.body(err.to_string().into())
.unwrap();
return Ok(res);
}
}
}
};
//
// Format the response
//
let res = match format {
None => {
// default format
Self::mk_json_response(
res,
includes,
details,
filters,
sort,
&self.ingress_register,
)
}
Some(format) if format.value() == "dump" => {
// internal diagnostic dump format
Self::mk_dump_response(&res)
}
Some(other) => {
// unknown format
Response::builder()
.status(hyper::StatusCode::BAD_REQUEST)
.header("Content-Type", "text/plain")
.body(
format!("Unsupported value '{}' for query parameter 'format'", other)
.into(),
)
.unwrap()
}
};
Ok(res)
}
async fn handle_ingress_id_query(
&self,
req_path: &str,
_request: &Request<Body>,
) -> Result<Response<Body>, String> {
debug!("in handle_ingress_id_query");
let ingress_id = req_path
.strip_prefix(self.http_api_path.as_str())
.unwrap()
.parse::<ingress::IngressId>()
.map_err(|e| e.to_string())?;
if self.rib_type != RibType::Physical {
return Err("unsupported on virtual rib".to_string());
}
let store = self.rib.load();
let mut res = String::new();
let records = store
.match_ingress_id(ingress_id)
.map_err(|e| e.to_string())?;
for pubrec in records {
res += &pubrec.prefix.to_string();
res.push('\n');
for m in pubrec.meta {
res.push('\t');
res += &serde_json::to_string(&m.meta).unwrap();
res.push('\n');
}
}
Ok(Response::builder()
.header("Content-Type", "text/plain")
.body(res.into())
.unwrap())
}
fn parse_include_param(
params: &QueryParams,
query_limits: Arc<ArcSwap<QueryLimits>>,
prefix: Prefix,
) -> Result<Includes, String> {
let mut includes = Includes::default();
if let Some(requested_includes) = get_param(params, "include") {
for include in requested_includes.value().split(',') {
match include {
"lessSpecifics" => includes.less_specifics = true,
"moreSpecifics" => includes.more_specifics = true,
_ => {
return Err(format!(
"'{}' is not a valid value for query parameter 'include'",
include
))
}
}
}
}
if includes.more_specifics {
let query_limits = query_limits.load();
let shortest_prefix_permitted = query_limits
.more_specifics
.shortest_prefix_permitted(&prefix);
if prefix.len() < shortest_prefix_permitted {
let err = if prefix.is_v4() {
format!(
"Query prefix '{}' is shorter than the allowed minimum allowed ({}) when including more specifics",
prefix,
query_limits.more_specifics.shortest_prefix_ipv4
)
} else if prefix.is_v6() {
format!(
"Query prefix '{}' is shorter than the allowed minimum allowed ({}) when including more specifics",
prefix,
query_limits.more_specifics.shortest_prefix_ipv6
)
} else {
format!(
"Internal error: prefix '{}' is neither IPv4 nor IPv6",
prefix
)
};
return Err(err);
}
}
Ok(includes)
}
fn parse_details_param(params: &QueryParams) -> Result<Details, String> {
let mut details = Details::default();
if let Some(requested_details) = get_param(params, "details") {
for detail in requested_details.value().split(',') {
match detail {
"communities" => details.communities = true,
_ => {
return Err(format!(
"'{}' is not a valid value for query parameter 'details'",
detail
))
}
}
}
}
Ok(details)
}
fn parse_filter_params(params: &QueryParams) -> Result<Filters, String> {
let mut filters = vec![];
for filter in get_all_params(params, "select") {
let filter_kind = extract_filter_kind(filter)?;
filters.push(Filter::new(filter_kind, FilterMode::Select));
}
for filter in get_all_params(params, "discard") {
let filter_kind = extract_filter_kind(filter)?;
filters.push(Filter::new(filter_kind, FilterMode::Discard));
}
let op = match get_param(params, "filter_op")
.as_ref()
.map(MatchedParam::value)
{
Some("any") => FilterOp::Any,
Some("all") => FilterOp::All,
Some(other) => {
return Err(format!("Unknown filter_op value '{}'", other))
}
None => FilterOp::default(),
};
Ok(Filters::new(op, filters))
}
fn parse_sort_params(params: &QueryParams) -> Result<SortKey, String> {
match get_param(params, "sort").as_ref().map(MatchedParam::value) {
Some(json_pointer) => Ok(SortKey::Some(json_pointer.into())),
_ => Ok(SortKey::None),
}
}
}
fn extract_filter_kind(filter: MatchedParam) -> Result<FilterKind, String> {
let extracted_filter = match filter {
MatchedParam::Family("as_path", v) => {
let mut asns = Vec::new();
for asn_str in v.split(',') {
let asn = Asn::from_str(asn_str).map_err(|err| {
format!(
"Invalid ASN value '{}' in 'as_path' filter: {}",
asn_str, err
)
})?;
asns.push(asn);
}
Ok(FilterKind::AsPath(asns))
}
MatchedParam::Family("peer_as", v) => match Asn::from_str(v) {
Ok(asn) => Ok(FilterKind::PeerAs(asn)),
Err(err) => Err(format!(
"Invalid value '{}' for 'peer_as' filter: {}",
v, err
)),
},
MatchedParam::Family("community", v) => {
match Community::from_str(v) {
Ok(community) => Ok(FilterKind::Community(community)),
Err(err) => Err(format!(
"Invalid value '{}' for 'community' filter: {}",
v, err
)),
}
}
other => Err(format!("Unrecognized filter family '{}'", other)),
}?;
Ok(extracted_filter)
}