-
Notifications
You must be signed in to change notification settings - Fork 424
/
catalog.rs
1017 lines (917 loc) · 38.3 KB
/
catalog.rs
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO, I've implemented this as a separate entity from the cache, but I wonder if the cache
// should be the only "front-end" for lookups, where if that misses, then we go to the catalog
// then, if requested, do a recursive lookup... i.e. the catalog would only point to files.
use std::borrow::Borrow;
use std::collections::HashMap;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, RwLock};
use std::task::{Context, Poll};
use futures::{ready, Future, FutureExt, TryFutureExt};
use log::warn;
use trust_dns_client::op::{Edns, Header, LowerQuery, MessageType, OpCode, ResponseCode};
use trust_dns_client::rr::dnssec::{Algorithm, SupportedAlgorithms};
use trust_dns_client::rr::rdata::opt::{EdnsCode, EdnsOption};
use trust_dns_client::rr::{LowerName, RecordType};
use crate::authority::{
AuthLookup, MessageRequest, MessageResponse, MessageResponseBuilder, ZoneType,
};
use crate::authority::{
AuthorityObject, BoxedLookupFuture, EmptyLookup, LookupError, LookupObject,
};
use crate::server::{Request, RequestHandler, ResponseHandler};
/// Set of authorities, zones, available to this server.
#[derive(Default)]
pub struct Catalog {
authorities: HashMap<LowerName, Arc<RwLock<Box<dyn AuthorityObject>>>>,
}
fn send_response<R: ResponseHandler>(
response_edns: Option<Edns>,
mut response: MessageResponse,
response_handle: R,
) -> io::Result<()> {
if let Some(mut resp_edns) = response_edns {
// set edns DAU and DHU
// send along the algorithms which are supported by this authority
let mut algorithms = SupportedAlgorithms::new();
algorithms.set(Algorithm::RSASHA256);
algorithms.set(Algorithm::ECDSAP256SHA256);
algorithms.set(Algorithm::ECDSAP384SHA384);
algorithms.set(Algorithm::ED25519);
let dau = EdnsOption::DAU(algorithms);
let dhu = EdnsOption::DHU(algorithms);
resp_edns.set_option(dau);
resp_edns.set_option(dhu);
response.set_edns(resp_edns);
}
response_handle.send_response(response)
}
impl RequestHandler for Catalog {
type ResponseFuture = HandleRequest;
/// Determines what needs to happen given the type of request, i.e. Query or Update.
///
/// # Arguments
///
/// * `request` - the requested action to perform.
/// * `response_handle` - sink for the response message to be sent
fn handle_request<R: ResponseHandler>(
&self,
request: Request,
response_handle: R,
) -> Self::ResponseFuture {
let request_message = request.message;
trace!("request: {:?}", request_message);
let response_edns: Option<Edns>;
// check if it's edns
if let Some(req_edns) = request_message.edns() {
let mut response = MessageResponseBuilder::new(Some(request_message.raw_queries()));
let mut response_header = Header::default();
response_header.set_id(request_message.id());
let mut resp_edns: Edns = Edns::new();
// check our version against the request
// TODO: what version are we?
let our_version = 0;
resp_edns.set_dnssec_ok(true);
resp_edns.set_max_payload(req_edns.max_payload().max(512));
resp_edns.set_version(our_version);
if req_edns.version() > our_version {
warn!(
"request edns version greater than {}: {}",
our_version,
req_edns.version()
);
response_header.set_response_code(ResponseCode::BADVERS);
response.edns(resp_edns);
// TODO: should ResponseHandle consume self?
let result =
response_handle.send_response(response.build_no_records(response_header));
return HandleRequest::result(result);
}
response_edns = Some(resp_edns);
} else {
response_edns = None;
}
match request_message.message_type() {
// TODO think about threading query lookups for multiple lookups, this could be a huge improvement
// especially for recursive lookups
MessageType::Query => match request_message.op_code() {
OpCode::Query => {
debug!("query received: {}", request_message.id());
let lookup = self.lookup(request_message, response_edns, response_handle);
HandleRequest::lookup(lookup)
}
OpCode::Update => {
debug!("update received: {}", request_message.id());
// TODO: this should be a future
let result = self.update(&request_message, response_edns, response_handle);
HandleRequest::result(result)
}
c => {
warn!("unimplemented op_code: {:?}", c);
let response = MessageResponseBuilder::new(Some(request_message.raw_queries()));
let result = response_handle.send_response(response.error_msg(
request_message.id(),
request_message.op_code(),
ResponseCode::NotImp,
));
HandleRequest::result(result)
}
},
MessageType::Response => {
warn!(
"got a response as a request from id: {}",
request_message.id()
);
let response = MessageResponseBuilder::new(Some(request_message.raw_queries()));
let result = response_handle.send_response(response.error_msg(
request_message.id(),
request_message.op_code(),
ResponseCode::FormErr,
));
HandleRequest::result(result)
}
}
}
}
/// Future response to handle a request
#[must_use = "futures do nothing unless polled"]
pub enum HandleRequest {
LookupFuture(Pin<Box<dyn Future<Output = ()> + Send>>),
Result(io::Result<()>),
}
impl HandleRequest {
fn lookup<R: ResponseHandler + Unpin>(lookup_future: LookupFuture<R>) -> Self {
let lookup = Box::pin(lookup_future) as Pin<Box<dyn Future<Output = ()> + Send>>;
HandleRequest::LookupFuture(lookup)
}
fn result(result: io::Result<()>) -> Self {
HandleRequest::Result(result)
}
}
impl Future for HandleRequest {
// TODO: return ()
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
match *self {
HandleRequest::LookupFuture(ref mut lookup) => lookup.as_mut().poll(cx),
HandleRequest::Result(Ok(_)) => Poll::Ready(()),
HandleRequest::Result(Err(ref res)) => {
error!("update failed: {}", res);
Poll::Ready(())
}
}
}
}
impl Catalog {
/// Constructs a new Catalog
pub fn new() -> Self {
Catalog {
authorities: HashMap::new(),
}
}
/// Insert or update a zone authority
///
/// # Arguments
///
/// * `name` - zone name, e.g. example.com.
/// * `authority` - the zone data
pub fn upsert(&mut self, name: LowerName, authority: Box<dyn AuthorityObject>) {
// self.authorities.insert(name, Arc::new(RwLock::new(authority)));
self.authorities
.insert(name, Arc::new(RwLock::new(authority)));
}
/// Remove a zone from the catalog
pub fn remove(&mut self, name: &LowerName) -> Option<Arc<RwLock<Box<dyn AuthorityObject>>>> {
self.authorities.remove(name)
}
/// Update the zone given the Update request.
///
/// [RFC 2136](https://tools.ietf.org/html/rfc2136), DNS Update, April 1997
///
/// ```text
/// 3.1 - Process Zone Section
///
/// 3.1.1. The Zone Section is checked to see that there is exactly one
/// RR therein and that the RR's ZTYPE is SOA, else signal FORMERR to the
/// requestor. Next, the ZNAME and ZCLASS are checked to see if the zone
/// so named is one of this server's authority zones, else signal NOTAUTH
/// to the requestor. If the server is a zone Secondary, the request will be
/// forwarded toward the Primary Zone Server.
///
/// 3.1.2 - Pseudocode For Zone Section Processing
///
/// if (zcount != 1 || ztype != SOA)
/// return (FORMERR)
/// if (zone_type(zname, zclass) == SECONDARY)
/// return forward()
/// if (zone_type(zname, zclass) == PRIMARY)
/// return update()
/// return (NOTAUTH)
///
/// Sections 3.2 through 3.8 describe the primary's behaviour,
/// whereas Section 6 describes a forwarder's behaviour.
///
/// 3.8 - Response
///
/// At the end of UPDATE processing, a response code will be known. A
/// response message is generated by copying the ID and Opcode fields
/// from the request, and either copying the ZOCOUNT, PRCOUNT, UPCOUNT,
/// and ADCOUNT fields and associated sections, or placing zeros (0) in
/// the these "count" fields and not including any part of the original
/// update. The QR bit is set to one (1), and the response is sent back
/// to the requestor. If the requestor used UDP, then the response will
/// be sent to the requestor's source UDP port. If the requestor used
/// TCP, then the response will be sent back on the requestor's open TCP
/// connection.
/// ```
///
/// The "request" should be an update formatted message.
/// The response will be in the alternate, all 0's format described in RFC 2136 section 3.8
/// as this is more efficient.
///
/// # Arguments
///
/// * `request` - an update message
/// * `response_handle` - sink for the response message to be sent
pub fn update<'q, R: ResponseHandler + 'static>(
&self,
update: &'q MessageRequest,
response_edns: Option<Edns>,
response_handle: R,
) -> io::Result<()> {
let response = MessageResponseBuilder::new(None);
let mut response_header = Header::default();
response_header.set_id(update.id());
response_header.set_op_code(OpCode::Update);
response_header.set_message_type(MessageType::Response);
let zones: &[LowerQuery] = update.queries();
// 2.3 - Zone Section
//
// All records to be updated must be in the same zone, and
// therefore the Zone Section is allowed to contain exactly one record.
// The ZNAME is the zone name, the ZTYPE must be SOA, and the ZCLASS is
// the zone's class.
let ztype = zones
.first()
.map(LowerQuery::query_type)
.unwrap_or(RecordType::Unknown(0));
if zones.len() != 1 || ztype != RecordType::SOA {
warn!(
"invalid update request zones must be 1 and not SOA records, zones: {} ztype: {}",
zones.len(),
ztype
);
response_header.set_response_code(ResponseCode::FormErr);
return send_response(
response_edns,
response.build_no_records(response_header),
response_handle,
);
}
if let Some(authority) = zones
.first()
.map(LowerQuery::name)
.and_then(|name| self.find(name))
{
let mut authority = authority.write().unwrap(); // poison errors should panic...
// Ask for Master/Slave terms to be replaced
#[allow(deprecated)]
match authority.zone_type() {
ZoneType::Slave | ZoneType::Master => {
warn!("Consider replacing the usage of master/slave with primary/secondary, see Juneteenth.");
}
_ => (),
}
#[allow(deprecated)]
match authority.zone_type() {
ZoneType::Secondary | ZoneType::Slave => {
error!("secondary forwarding for update not yet implemented");
response_header.set_response_code(ResponseCode::NotImp);
send_response(
response_edns,
response.build_no_records(response_header),
response_handle,
)
}
ZoneType::Primary | ZoneType::Master => {
let update_result = authority.update(update);
match update_result {
// successful update
Ok(..) => {
response_header.set_response_code(ResponseCode::NoError);
}
Err(response_code) => {
response_header.set_response_code(response_code);
}
}
send_response(
response_edns,
response.build_no_records(response_header),
response_handle,
)
}
_ => {
response_header.set_response_code(ResponseCode::NotAuth);
send_response(
response_edns,
response.build_no_records(response_header),
response_handle,
)
}
}
} else {
response_header.set_response_code(ResponseCode::Refused);
send_response(
response_edns,
response.build_no_records(response_header),
response_handle,
)
}
}
/// Checks whether the `Catalog` contains DNS records for `name`
///
/// Use this when you know the exact `LowerName` that was used when
/// adding an authority and you don't care about the authority it
/// contains. For public domain names, `LowerName` is usually the
/// top level domain name like `example.com.`.
///
/// If you do not know the exact domain name to use or you actually
/// want to use the authority it contains, use `find` instead.
pub fn contains(&self, name: &LowerName) -> bool {
self.authorities.contains_key(name)
}
/// Given the requested query, lookup and return any matching results.
///
/// # Arguments
///
/// * `request` - the query message.
/// * `response_handle` - sink for the response message to be sent
pub fn lookup<R: ResponseHandler>(
&self,
request: MessageRequest,
response_edns: Option<Edns>,
response_handle: R,
) -> LookupFuture<R> {
let request = Arc::new(request);
let response_edns = response_edns.map(Arc::new);
// TODO: the spec is very unclear on what to do with multiple queries
// we will search for each, in the future, maybe make this threaded to respond even faster.
// the current impl will return on the first query result
// collect all the queries and lookups
let queries_and_authorities = request
.queries()
.iter()
.enumerate()
.filter_map(|(idx, q)| {
self.find(q.name())
.map(|authority| (idx, Arc::clone(authority)))
})
.collect::<Vec<_>>();
let found_authority = !queries_and_authorities.is_empty();
if !found_authority {
let response = MessageResponseBuilder::new(Some(request.raw_queries()));
send_response(
response_edns
.as_ref()
.map(|arc| Borrow::<Edns>::borrow(arc).clone()),
response.error_msg(request.id(), request.op_code(), ResponseCode::NXDomain),
response_handle.clone(),
)
.map_err(|e| error!("failed to send response: {}", e))
.ok();
}
LookupFuture::new(
request,
response_edns,
response_handle,
queries_and_authorities,
)
}
/// Recursively searches the catalog for a matching authority
pub fn find(&self, name: &LowerName) -> Option<&Arc<RwLock<Box<dyn AuthorityObject>>>> {
debug!("searching authorities for: {}", name);
self.authorities.get(name).or_else(|| {
if !name.is_root() {
let name = name.base_name();
self.find(&name)
} else {
None
}
})
}
}
/// A Future that runs the lookups and responds to the requests
#[allow(clippy::type_complexity)]
#[must_use = "futures do nothing unless polled"]
pub struct LookupFuture<R: ResponseHandler + Unpin> {
request: Arc<MessageRequest>,
response_edns: Option<Arc<Edns>>,
response_handle: R,
queries_and_authorities: Vec<(usize, Arc<RwLock<Box<dyn AuthorityObject>>>)>,
lookup: Option<AuthorityLookup<R>>,
}
impl<R: ResponseHandler + Unpin> LookupFuture<R> {
#[allow(clippy::type_complexity)]
fn new(
request: Arc<MessageRequest>,
response_edns: Option<Arc<Edns>>,
response_handle: R,
queries_and_authorities: Vec<(usize, Arc<RwLock<Box<dyn AuthorityObject>>>)>,
) -> Self {
LookupFuture {
request,
response_edns,
response_handle,
queries_and_authorities,
lookup: None,
}
}
}
impl<R: ResponseHandler + Unpin> Future for LookupFuture<R> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
loop {
// See if the lookup had anything
match self.lookup.as_mut().map(|f| f.poll_unpin(cx)) {
Some(Poll::Pending) => return Poll::Pending,
Some(Poll::Ready(())) => (),
None => (),
}
// lookup is complete, make sure it is None at this point
self.lookup = None;
// get next query
let (query_idx, ref_authority) = if let Some(q_a) = self.queries_and_authorities.pop() {
q_a
} else {
// all lookups are complete, finish request
return Poll::Ready(());
};
let query = if let Some(query) = self.request.queries().get(query_idx) {
query
} else {
// bad state, could just panic
error!("query_idx out of bounds? {}", query_idx);
continue;
};
let authority = &ref_authority.read().unwrap(); // poison errors should panic
info!(
"request: {} found authority: {}",
self.request.id(),
authority.origin()
);
let mut response_header = Header::new();
response_header.set_id(self.request.id());
response_header.set_op_code(OpCode::Query);
response_header.set_message_type(MessageType::Response);
response_header.set_authoritative(authority.zone_type().is_authoritative());
let (is_dnssec, supported_algorithms) =
self.request
.edns()
.map_or((false, SupportedAlgorithms::new()), |edns| {
let supported_algorithms =
if let Some(&EdnsOption::DAU(algs)) = edns.option(EdnsCode::DAU) {
algs
} else {
debug!("no DAU in request, used default SupportAlgorithms");
Default::default()
};
(edns.dnssec_ok(), supported_algorithms)
});
// log algorithms being requested
if is_dnssec {
info!(
"request: {} supported_algs: {}",
self.request.id(),
supported_algorithms
);
}
debug!("performing {} on {}", query, authority.origin());
let lookup_future = authority.search(query, is_dnssec, supported_algorithms);
let request_params = RequestParams {
is_dnssec,
supported_algorithms,
query: query.clone(),
request: Arc::clone(&self.request),
};
let response_params = ResponseParams {
response_edns: self.response_edns.clone(),
response_header,
response_handle: self.response_handle.clone(),
};
#[allow(deprecated)]
match authority.zone_type() {
ZoneType::Primary | ZoneType::Secondary | ZoneType::Master | ZoneType::Slave => {
self.lookup = Some(AuthorityLookup::authority(
self.request.id(),
response_params,
request_params,
lookup_future,
Arc::clone(&ref_authority),
));
}
ZoneType::Forward | ZoneType::Hint => {
self.lookup = Some(AuthorityLookup::resolve(
self.request.id(),
response_params,
request_params,
lookup_future,
Arc::clone(&ref_authority),
));
}
}
}
}
}
struct RequestParams {
is_dnssec: bool,
supported_algorithms: SupportedAlgorithms,
query: LowerQuery,
request: Arc<MessageRequest>,
}
struct ResponseParams<R: ResponseHandler> {
response_edns: Option<Arc<Edns>>,
response_header: Header,
response_handle: R,
}
/// Authority Lookup future to perform all actions for authoritative responses.
#[must_use = "futures do nothing unless polled"]
struct AuthorityLookup<R: ResponseHandler> {
response_params: Option<ResponseParams<R>>,
request_params: RequestParams,
authority: Arc<RwLock<Box<dyn AuthorityObject>>>,
state: AuthOrResolve,
}
impl<R: ResponseHandler> AuthorityLookup<R> {
fn authority(
request_id: u16,
response_params: ResponseParams<R>,
request_params: RequestParams,
record_lookup: BoxedLookupFuture,
authority: Arc<RwLock<Box<dyn AuthorityObject>>>,
) -> Self {
debug!("handling authoritative request: {}", request_id);
AuthorityLookup {
response_params: Some(response_params),
request_params,
authority,
state: AuthOrResolve::AuthorityLookupState(AuthorityLookupState::Records {
record_lookup,
}),
}
}
fn resolve(
request_id: u16,
response_params: ResponseParams<R>,
request_params: RequestParams,
record_lookup: BoxedLookupFuture,
authority: Arc<RwLock<Box<dyn AuthorityObject>>>,
) -> Self {
debug!("handling forwarded resolve: {}", request_id);
AuthorityLookup {
response_params: Some(response_params),
request_params,
authority,
state: AuthOrResolve::ResolveLookupState(ResolveLookupState::Records { record_lookup }),
}
}
}
impl<R: ResponseHandler> AuthorityLookup<R> {
#[allow(clippy::type_complexity)]
fn split(
&mut self,
) -> (
&mut ResponseParams<R>,
&RequestParams,
&Arc<RwLock<Box<dyn AuthorityObject>>>,
&mut AuthOrResolve,
) {
(
self.response_params
.as_mut()
.expect("bad state, response_params should not be none here"),
&self.request_params,
&self.authority,
&mut self.state,
)
}
}
impl<R: ResponseHandler> Future for AuthorityLookup<R> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let (response_params, request_params, authority, state) = self.split();
let sections = ready!(state.poll(cx, request_params, response_params, authority));
let records = sections.answers;
let soa = sections.soa;
let ns = sections.ns;
let additionals = sections.additionals;
let response_params = self
.response_params
.take()
.expect("AuthorityLookup already complete");
let response_edns = response_params.response_edns;
let response = MessageResponseBuilder::new(Some(self.request_params.request.raw_queries()));
let response_header = response_params.response_header;
let response_handle = response_params.response_handle;
send_response(
response_edns
.as_ref()
.map(|arc| Borrow::<Edns>::borrow(arc).clone()),
response.build(
response_header,
records.iter(),
ns.iter(),
soa.iter(),
additionals.iter(),
),
response_handle,
)
.map_err(|e| error!("error sending response: {}", e))
.ok();
Poll::Ready(())
}
}
struct LookupSections {
answers: Box<dyn LookupObject>,
soa: Box<dyn LookupObject>,
ns: Box<dyn LookupObject>,
additionals: Box<dyn LookupObject>,
}
#[must_use = "futures do nothing unless polled"]
enum AuthOrResolve {
AuthorityLookupState(AuthorityLookupState),
ResolveLookupState(ResolveLookupState),
}
impl AuthOrResolve {
#[allow(clippy::type_complexity)]
fn poll<R: ResponseHandler>(
&mut self,
cx: &mut Context,
request_params: &RequestParams,
response_params: &mut ResponseParams<R>,
authority: &Arc<RwLock<Box<dyn AuthorityObject>>>,
) -> Poll<LookupSections> {
match self {
AuthOrResolve::AuthorityLookupState(a) => {
a.poll(cx, request_params, response_params, authority)
}
AuthOrResolve::ResolveLookupState(r) => {
r.poll(cx, request_params, response_params, authority)
}
}
}
}
/// state machine for handling the response to the request
#[must_use = "futures do nothing unless polled"]
enum AuthorityLookupState {
/// This is the initial lookup for the Records
Records { record_lookup: BoxedLookupFuture },
/// This performs the lookup for NS records, transitions to complete after
LookupNs {
ns_lookup: BoxedLookupFuture,
records: Option<Box<dyn LookupObject>>,
},
/// In a negative response case, we need to return the NSEC records
NxLookupNsec { nsec_lookup: BoxedLookupFuture },
/// In a negative response case, we need to return the NSEC records
NxLookupSoa {
soa_lookup: BoxedLookupFuture,
nsecs: Option<Box<dyn LookupObject>>,
},
/// The Completion state
Complete {
// TODO: convert to a single Option with all Boxes
records: Option<Box<dyn LookupObject>>,
soa: Option<Box<dyn LookupObject>>,
ns: Option<Box<dyn LookupObject>>,
},
}
// TODO: turn this into a real future
impl AuthorityLookupState {
#[allow(clippy::type_complexity)]
fn poll<R: ResponseHandler>(
&mut self,
cx: &mut Context,
request_params: &RequestParams,
response_params: &mut ResponseParams<R>,
authority: &Arc<RwLock<Box<dyn AuthorityObject>>>,
) -> Poll<LookupSections> {
loop {
*self = match self {
// In this state we await the records, on success we transition to getting
// NS records, which indicate an authoritative response.
//
// On Errors, the transition depends on the type of error.
AuthorityLookupState::Records { record_lookup } => {
match record_lookup.poll_unpin(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(records)) => {
response_params
.response_header
.set_response_code(ResponseCode::NoError);
response_params.response_header.set_authoritative(true);
// This was a successful authoritative lookup:
// get the NS records
let ns_lookup = authority.read().expect("authority poisoned").ns(
request_params.is_dnssec,
request_params.supported_algorithms,
);
AuthorityLookupState::LookupNs {
ns_lookup,
records: Some(records),
}
}
// This request was refused
// TODO: there are probably other error cases that should just drop through (FormErr, ServFail)
Poll::Ready(Err(LookupError::ResponseCode(ResponseCode::Refused))) => {
response_params
.response_header
.set_response_code(ResponseCode::Refused);
let ns = Box::new(AuthLookup::default()) as Box<dyn LookupObject>;
let soa = Box::new(AuthLookup::default()) as Box<dyn LookupObject>;
let records = Box::new(AuthLookup::default()) as Box<dyn LookupObject>;
AuthorityLookupState::Complete {
records: Some(records),
soa: Some(soa),
ns: Some(ns),
}
}
// in the not found case it's standard to return the SOA in the authority section
// if the name is in this zone, etc.
// see https://tools.ietf.org/html/rfc2308 for proper response construct
Poll::Ready(Err(e)) => {
if e.is_nx_domain() {
response_params
.response_header
.set_response_code(ResponseCode::NXDomain);
} else if e.is_name_exists() {
response_params
.response_header
.set_response_code(ResponseCode::NoError);
};
// in the dnssec case, nsec records should exist, we return NoError + NoData + NSec...
let nsec_lookup = if request_params.is_dnssec {
debug!(
"request: {} non-existent adding nsecs",
request_params.request.id()
);
// get NSEC records
let nsecs = authority
.read()
.expect("authority poisoned")
.get_nsec_records(
request_params.query.name(),
true,
request_params.supported_algorithms,
);
BoxedLookupFuture::from(nsecs)
} else {
// place holder...
debug!("request: {} non-existent", request_params.request.id());
BoxedLookupFuture::empty()
};
AuthorityLookupState::NxLookupNsec { nsec_lookup }
}
}
}
// This is still a successful path, getting the ns records,
// which represent an Authoritative answer
AuthorityLookupState::LookupNs { ns_lookup, records } => {
// ns is allowed to fail
let ns = match ns_lookup.poll_unpin(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(ns)) => ns,
Poll::Ready(Err(e)) => {
warn!("ns_lookup errored: {}", e);
Box::new(AuthLookup::default()) as Box<dyn LookupObject>
}
};
let soa = Box::new(AuthLookup::default()) as Box<dyn LookupObject>;
AuthorityLookupState::Complete {
records: records.take(),
soa: Some(soa),
ns: Some(ns),
}
}
// run the nsec lookup future, and then transition to get soa
AuthorityLookupState::NxLookupNsec { nsec_lookup } => {
let nsecs = match nsec_lookup.poll_unpin(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(nsecs)) => nsecs,
Poll::Ready(Err(e)) => {
warn!("failed to lookup nsecs: {}", e);
Box::new(AuthLookup::default()) as Box<dyn LookupObject>
}
};
let soa_lookup = authority.read().expect("authority poisoned").soa_secure(
request_params.is_dnssec,
request_params.supported_algorithms,
);
AuthorityLookupState::NxLookupSoa {
soa_lookup,
nsecs: Some(nsecs),
}
}
// run the soa lookup, and then transition to complete
AuthorityLookupState::NxLookupSoa { soa_lookup, nsecs } => {
let soa = match soa_lookup.poll_unpin(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(soa)) => soa,
Poll::Ready(Err(e)) => {
warn!("failed to lookup soa: {}", e);
Box::new(AuthLookup::default()) as Box<dyn LookupObject>
}
};
let records = Box::new(AuthLookup::default()) as Box<dyn LookupObject>;
AuthorityLookupState::Complete {
records: Some(records),
soa: Some(soa),
ns: nsecs.take(),
}
}
// everything is done, return results.
AuthorityLookupState::Complete { records, soa, ns } => {
let mut records = records
.take()
.expect("AuthorityLookupState already complete");
let additionals = records.take_additionals();
let sections = LookupSections {
answers: records,
soa: soa.take().expect("AuthorityLookupState already complete"),
ns: ns.take().expect("AuthorityLookupState already complete"),
additionals: additionals.unwrap_or_else(|| {
Box::new(AuthLookup::default()) as Box<dyn LookupObject>
}),
};
return Poll::Ready(sections);
}
}
}
}
}
/// state machine for handling the response to the request
#[must_use = "futures do nothing unless polled"]
enum ResolveLookupState {
/// This is the initial lookup for the Records
Records { record_lookup: BoxedLookupFuture },
}
impl ResolveLookupState {
#[allow(clippy::type_complexity)]
fn poll<R: ResponseHandler>(
&mut self,
cx: &mut Context,
_request_params: &RequestParams,
response_params: &mut ResponseParams<R>,
_authority: &Arc<RwLock<Box<dyn AuthorityObject>>>,
) -> Poll<LookupSections> {
#[allow(clippy::never_loop)]
loop {
// TODO: way more states to consider.
/* *self = */
match self {
// In this state we await the records.
//
// On Errors, the transition depends on the type of error.
ResolveLookupState::Records { record_lookup } => {
let records = ready!(record_lookup
.map_err(|e| {
if e.is_nx_domain() {
response_params
.response_header
.set_response_code(ResponseCode::NXDomain);
};
error!("error resolving: {}", e)
})
.map(|r: Result<_, ()>| match r {
Ok(r) => r,
Err(()) => Box::new(EmptyLookup),
})
.poll_unpin(cx));