-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathdns_parser.rs
2192 lines (1873 loc) · 67.3 KB
/
dns_parser.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
//! DNS parsing utility.
//!
//! [DnsIncoming] is the logic representation of an incoming DNS packet.
//! [DnsOutgoing] is the logic representation of an outgoing DNS message of one or more packets.
//! [DnsOutPacket] is the encoded one packet for [DnsOutgoing].
#[cfg(feature = "logging")]
use crate::log::trace;
use crate::error::{e_fmt, Error, Result};
use std::{
any::Any,
cmp,
collections::HashMap,
convert::TryInto,
fmt,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
str,
time::SystemTime,
};
/// DNS resource record types, stored as `u16`. Can do `as u16` when needed.
///
/// See [RFC 1035 section 3.2.2](https://datatracker.ietf.org/doc/html/rfc1035#section-3.2.2)
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
#[non_exhaustive]
#[repr(u16)]
pub enum RRType {
/// DNS record type for IPv4 address
A = 1,
/// DNS record type for Canonical Name
CNAME = 5,
/// DNS record type for Pointer
PTR = 12,
/// DNS record type for Host Info
HINFO = 13,
/// DNS record type for Text (properties)
TXT = 16,
/// DNS record type for IPv6 address
AAAA = 28,
/// DNS record type for Service
SRV = 33,
/// DNS record type for Negative Responses
NSEC = 47,
/// DNS record type for any records (wildcard)
ANY = 255,
}
impl RRType {
/// Converts `u16` into `RRType` if possible.
pub const fn from_u16(value: u16) -> Option<RRType> {
match value {
1 => Some(RRType::A),
5 => Some(RRType::CNAME),
12 => Some(RRType::PTR),
13 => Some(RRType::HINFO),
16 => Some(RRType::TXT),
28 => Some(RRType::AAAA),
33 => Some(RRType::SRV),
47 => Some(RRType::NSEC),
255 => Some(RRType::ANY),
_ => None,
}
}
}
impl fmt::Display for RRType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RRType::A => write!(f, "TYPE_A"),
RRType::CNAME => write!(f, "TYPE_CNAME"),
RRType::PTR => write!(f, "TYPE_PTR"),
RRType::HINFO => write!(f, "TYPE_HINFO"),
RRType::TXT => write!(f, "TYPE_TXT"),
RRType::AAAA => write!(f, "TYPE_AAAA"),
RRType::SRV => write!(f, "TYPE_SRV"),
RRType::NSEC => write!(f, "TYPE_NSEC"),
RRType::ANY => write!(f, "TYPE_ANY"),
}
}
}
/// The class value for the Internet.
pub const CLASS_IN: u16 = 1;
pub const CLASS_MASK: u16 = 0x7FFF;
/// Cache-flush bit: the most significant bit of the rrclass field of the resource record.
pub const CLASS_CACHE_FLUSH: u16 = 0x8000;
/// Max size of UDP datagram payload.
///
/// It is calculated as: 9000 bytes - IP header 20 bytes - UDP header 8 bytes.
/// Reference: [RFC6762 section 17](https://datatracker.ietf.org/doc/html/rfc6762#section-17)
pub const MAX_MSG_ABSOLUTE: usize = 8972;
const MSG_HEADER_LEN: usize = 12;
// Definitions for DNS message header "flags" field
//
// The "flags" field is 16-bit long, in this format:
// (RFC 1035 section 4.1.1)
//
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
//
pub const FLAGS_QR_MASK: u16 = 0x8000; // mask for query/response bit
/// Flag bit to indicate a query
pub const FLAGS_QR_QUERY: u16 = 0x0000;
/// Flag bit to indicate a response
pub const FLAGS_QR_RESPONSE: u16 = 0x8000;
/// Flag bit for Authoritative Answer
pub const FLAGS_AA: u16 = 0x0400;
/// mask for TC(Truncated) bit
///
/// 2024-08-10: currently this flag is only supported on the querier side,
/// not supported on the responder side. I.e. the responder only
/// handles the first packet and ignore this bit. Since the
/// additional packets have 0 questions, the processing of them
/// is no-op.
/// In practice, this means the responder supports Known-Answer
/// only with single packet, not multi-packet. The querier supports
/// both single packet and multi-packet.
pub const FLAGS_TC: u16 = 0x0200;
/// A convenience type alias for DNS record trait objects.
pub type DnsRecordBox = Box<dyn DnsRecordExt>;
impl Clone for DnsRecordBox {
fn clone(&self) -> Self {
self.clone_box()
}
}
const U16_SIZE: usize = 2;
/// Returns `RRType` for a given IP address.
#[inline]
pub const fn ip_address_rr_type(address: &IpAddr) -> RRType {
match address {
IpAddr::V4(_) => RRType::A,
IpAddr::V6(_) => RRType::AAAA,
}
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct DnsEntry {
pub(crate) name: String, // always lower case.
pub(crate) ty: RRType,
class: u16,
cache_flush: bool,
}
impl DnsEntry {
const fn new(name: String, ty: RRType, class: u16) -> Self {
Self {
name,
ty,
class: class & CLASS_MASK,
cache_flush: (class & CLASS_CACHE_FLUSH) != 0,
}
}
}
/// Common methods for all DNS entries: questions and resource records.
pub trait DnsEntryExt: fmt::Debug {
fn entry_name(&self) -> &str;
fn entry_type(&self) -> RRType;
}
/// A DNS question entry
#[derive(Debug)]
pub struct DnsQuestion {
pub(crate) entry: DnsEntry,
}
impl DnsEntryExt for DnsQuestion {
fn entry_name(&self) -> &str {
&self.entry.name
}
fn entry_type(&self) -> RRType {
self.entry.ty
}
}
/// A DNS Resource Record - like a DNS entry, but has a TTL.
/// RFC: https://www.rfc-editor.org/rfc/rfc1035#section-3.2.1
/// https://www.rfc-editor.org/rfc/rfc1035#section-4.1.3
#[derive(Debug, Clone)]
pub struct DnsRecord {
pub(crate) entry: DnsEntry,
ttl: u32, // in seconds, 0 means this record should not be cached
created: u64, // UNIX time in millis
expires: u64, // expires at this UNIX time in millis
/// Support re-query an instance before its PTR record expires.
/// See https://datatracker.ietf.org/doc/html/rfc6762#section-5.2
refresh: u64, // UNIX time in millis
/// If conflict resolution decides to change the name, this is the new one.
new_name: Option<String>,
}
impl DnsRecord {
fn new(name: &str, ty: RRType, class: u16, ttl: u32) -> Self {
let created = current_time_millis();
// From RFC 6762 section 5.2:
// "... The querier should plan to issue a query at 80% of the record
// lifetime, and then if no answer is received, at 85%, 90%, and 95%."
let refresh = get_expiration_time(created, ttl, 80);
let expires = get_expiration_time(created, ttl, 100);
Self {
entry: DnsEntry::new(name.to_string(), ty, class),
ttl,
created,
expires,
refresh,
new_name: None,
}
}
pub const fn get_ttl(&self) -> u32 {
self.ttl
}
pub const fn get_expire_time(&self) -> u64 {
self.expires
}
pub const fn get_refresh_time(&self) -> u64 {
self.refresh
}
pub const fn is_expired(&self, now: u64) -> bool {
now >= self.expires
}
pub const fn refresh_due(&self, now: u64) -> bool {
now >= self.refresh
}
/// Returns whether `now` (in millis) has passed half of TTL.
pub fn halflife_passed(&self, now: u64) -> bool {
let halflife = get_expiration_time(self.created, self.ttl, 50);
now > halflife
}
pub fn is_unique(&self) -> bool {
self.entry.cache_flush
}
/// Updates the refresh time to be the same as the expire time so that
/// this record will not refresh again and will just expire.
pub fn refresh_no_more(&mut self) {
self.refresh = get_expiration_time(self.created, self.ttl, 100);
}
/// Returns if this record is due for refresh. If yes, `refresh` time is updated.
pub fn refresh_maybe(&mut self, now: u64) -> bool {
if self.is_expired(now) || !self.refresh_due(now) {
return false;
}
trace!(
"{} qtype {} is due to refresh",
&self.entry.name,
self.entry.ty
);
// From RFC 6762 section 5.2:
// "... The querier should plan to issue a query at 80% of the record
// lifetime, and then if no answer is received, at 85%, 90%, and 95%."
//
// If the answer is received in time, 'refresh' will be reset outside
// this function, back to 80% of the new TTL.
if self.refresh == get_expiration_time(self.created, self.ttl, 80) {
self.refresh = get_expiration_time(self.created, self.ttl, 85);
} else if self.refresh == get_expiration_time(self.created, self.ttl, 85) {
self.refresh = get_expiration_time(self.created, self.ttl, 90);
} else if self.refresh == get_expiration_time(self.created, self.ttl, 90) {
self.refresh = get_expiration_time(self.created, self.ttl, 95);
} else {
self.refresh_no_more();
}
true
}
/// Returns the remaining TTL in seconds
fn get_remaining_ttl(&self, now: u64) -> u32 {
let remaining_millis = get_expiration_time(self.created, self.ttl, 100) - now;
cmp::max(0, remaining_millis / 1000) as u32
}
/// Return the absolute time for this record being created
pub const fn get_created(&self) -> u64 {
self.created
}
/// Set the absolute expiration time in millis
fn set_expire(&mut self, expire_at: u64) {
self.expires = expire_at;
}
fn reset_ttl(&mut self, other: &Self) {
self.ttl = other.ttl;
self.created = other.created;
self.refresh = get_expiration_time(self.created, self.ttl, 80);
self.expires = get_expiration_time(self.created, self.ttl, 100);
}
/// Modify TTL to reflect the remaining life time from `now`.
pub fn update_ttl(&mut self, now: u64) {
if now > self.created {
let elapsed = now - self.created;
self.ttl -= (elapsed / 1000) as u32;
}
}
pub fn set_new_name(&mut self, new_name: String) {
if new_name == self.entry.name {
self.new_name = None;
} else {
self.new_name = Some(new_name);
}
}
pub fn get_new_name(&self) -> Option<&str> {
self.new_name.as_deref()
}
/// Return the new name if exists, otherwise the regular name in DnsEntry.
pub(crate) fn get_name(&self) -> &str {
self.new_name.as_deref().unwrap_or(&self.entry.name)
}
pub fn get_original_name(&self) -> &str {
&self.entry.name
}
}
impl PartialEq for DnsRecord {
fn eq(&self, other: &Self) -> bool {
self.entry == other.entry
}
}
/// Common methods for DNS resource records.
pub trait DnsRecordExt: fmt::Debug {
fn get_record(&self) -> &DnsRecord;
fn get_record_mut(&mut self) -> &mut DnsRecord;
fn write(&self, packet: &mut DnsOutPacket);
fn any(&self) -> &dyn Any;
/// Returns whether `other` record is considered the same except TTL.
fn matches(&self, other: &dyn DnsRecordExt) -> bool;
/// Returns whether `other` record has the same rdata.
fn rrdata_match(&self, other: &dyn DnsRecordExt) -> bool;
/// Returns the result based on a byte-level comparison of `rdata`.
/// If `other` is not valid, returns `Greater`.
fn compare_rdata(&self, other: &dyn DnsRecordExt) -> cmp::Ordering;
/// Returns the result based on "lexicographically later" defined below.
fn compare(&self, other: &dyn DnsRecordExt) -> cmp::Ordering {
/*
RFC 6762: https://datatracker.ietf.org/doc/html/rfc6762#section-8.2
... The determination of "lexicographically later" is performed by first
comparing the record class (excluding the cache-flush bit described
in Section 10.2), then the record type, then raw comparison of the
binary content of the rdata without regard for meaning or structure.
If the record classes differ, then the numerically greater class is
considered "lexicographically later". Otherwise, if the record types
differ, then the numerically greater type is considered
"lexicographically later". If the rrtype and rrclass both match,
then the rdata is compared. ...
*/
match self.get_class().cmp(&other.get_class()) {
cmp::Ordering::Equal => match self.get_type().cmp(&other.get_type()) {
cmp::Ordering::Equal => self.compare_rdata(other),
not_equal => not_equal,
},
not_equal => not_equal,
}
}
/// Returns a human-readable string of rdata.
fn rdata_print(&self) -> String;
/// Returns the class only, excluding class_flush / unique bit.
fn get_class(&self) -> u16 {
self.get_record().entry.class
}
fn get_cache_flush(&self) -> bool {
self.get_record().entry.cache_flush
}
/// Return the new name if exists, otherwise the regular name in DnsEntry.
fn get_name(&self) -> &str {
self.get_record().get_name()
}
fn get_type(&self) -> RRType {
self.get_record().entry.ty
}
/// Resets TTL using `other` record.
/// `self.refresh` and `self.expires` are also reset.
fn reset_ttl(&mut self, other: &dyn DnsRecordExt) {
self.get_record_mut().reset_ttl(other.get_record());
}
fn get_created(&self) -> u64 {
self.get_record().get_created()
}
fn get_expire(&self) -> u64 {
self.get_record().get_expire_time()
}
fn set_expire(&mut self, expire_at: u64) {
self.get_record_mut().set_expire(expire_at);
}
/// Set expire as `expire_at` if it is sooner than the current `expire`.
fn set_expire_sooner(&mut self, expire_at: u64) {
if expire_at < self.get_expire() {
self.get_record_mut().set_expire(expire_at);
}
}
/// Given `now`, if the record is due to refresh, this method updates the refresh time
/// and returns the new refresh time. Otherwise, returns None.
fn updated_refresh_time(&mut self, now: u64) -> Option<u64> {
if self.get_record_mut().refresh_maybe(now) {
Some(self.get_record().get_refresh_time())
} else {
None
}
}
/// Returns true if another record has matched content,
/// and if its TTL is at least half of this record's.
fn suppressed_by_answer(&self, other: &dyn DnsRecordExt) -> bool {
self.matches(other) && (other.get_record().ttl > self.get_record().ttl / 2)
}
/// Required by RFC 6762 Section 7.1: Known-Answer Suppression.
fn suppressed_by(&self, msg: &DnsIncoming) -> bool {
for answer in msg.answers.iter() {
if self.suppressed_by_answer(answer.as_ref()) {
return true;
}
}
false
}
fn clone_box(&self) -> DnsRecordBox;
}
/// Resource Record for IPv4 address or IPv6 address.
#[derive(Debug, Clone)]
pub struct DnsAddress {
pub(crate) record: DnsRecord,
address: IpAddr,
}
impl DnsAddress {
pub fn new(name: &str, ty: RRType, class: u16, ttl: u32, address: IpAddr) -> Self {
let record = DnsRecord::new(name, ty, class, ttl);
Self { record, address }
}
pub fn address(&self) -> IpAddr {
self.address
}
}
impl DnsRecordExt for DnsAddress {
fn get_record(&self) -> &DnsRecord {
&self.record
}
fn get_record_mut(&mut self) -> &mut DnsRecord {
&mut self.record
}
fn write(&self, packet: &mut DnsOutPacket) {
match self.address {
IpAddr::V4(addr) => packet.write_bytes(addr.octets().as_ref()),
IpAddr::V6(addr) => packet.write_bytes(addr.octets().as_ref()),
};
}
fn any(&self) -> &dyn Any {
self
}
fn matches(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_a) = other.any().downcast_ref::<Self>() {
return self.address == other_a.address && self.record.entry == other_a.record.entry;
}
false
}
fn rrdata_match(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_a) = other.any().downcast_ref::<Self>() {
return self.address == other_a.address;
}
false
}
fn compare_rdata(&self, other: &dyn DnsRecordExt) -> cmp::Ordering {
if let Some(other_a) = other.any().downcast_ref::<Self>() {
self.address.cmp(&other_a.address)
} else {
cmp::Ordering::Greater
}
}
fn rdata_print(&self) -> String {
format!("{}", self.address)
}
fn clone_box(&self) -> DnsRecordBox {
Box::new(self.clone())
}
}
/// Resource Record for a DNS pointer
#[derive(Debug, Clone)]
pub struct DnsPointer {
record: DnsRecord,
alias: String, // the full name of Service Instance
}
impl DnsPointer {
pub fn new(name: &str, ty: RRType, class: u16, ttl: u32, alias: String) -> Self {
let record = DnsRecord::new(name, ty, class, ttl);
Self { record, alias }
}
pub fn alias(&self) -> &str {
&self.alias
}
}
impl DnsRecordExt for DnsPointer {
fn get_record(&self) -> &DnsRecord {
&self.record
}
fn get_record_mut(&mut self) -> &mut DnsRecord {
&mut self.record
}
fn write(&self, packet: &mut DnsOutPacket) {
packet.write_name(&self.alias);
}
fn any(&self) -> &dyn Any {
self
}
fn matches(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_ptr) = other.any().downcast_ref::<Self>() {
return self.alias == other_ptr.alias && self.record.entry == other_ptr.record.entry;
}
false
}
fn rrdata_match(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_ptr) = other.any().downcast_ref::<Self>() {
return self.alias == other_ptr.alias;
}
false
}
fn compare_rdata(&self, other: &dyn DnsRecordExt) -> cmp::Ordering {
if let Some(other_ptr) = other.any().downcast_ref::<Self>() {
self.alias.cmp(&other_ptr.alias)
} else {
cmp::Ordering::Greater
}
}
fn rdata_print(&self) -> String {
self.alias.clone()
}
fn clone_box(&self) -> DnsRecordBox {
Box::new(self.clone())
}
}
/// Resource Record for a DNS service.
#[derive(Debug, Clone)]
pub struct DnsSrv {
pub(crate) record: DnsRecord,
pub(crate) priority: u16, // lower number means higher priority. Should be 0 in common cases.
pub(crate) weight: u16, // Should be 0 in common cases
host: String,
port: u16,
}
impl DnsSrv {
pub fn new(
name: &str,
class: u16,
ttl: u32,
priority: u16,
weight: u16,
port: u16,
host: String,
) -> Self {
let record = DnsRecord::new(name, RRType::SRV, class, ttl);
Self {
record,
priority,
weight,
host,
port,
}
}
pub fn host(&self) -> &str {
&self.host
}
pub fn port(&self) -> u16 {
self.port
}
pub fn set_host(&mut self, host: String) {
self.host = host;
}
}
impl DnsRecordExt for DnsSrv {
fn get_record(&self) -> &DnsRecord {
&self.record
}
fn get_record_mut(&mut self) -> &mut DnsRecord {
&mut self.record
}
fn write(&self, packet: &mut DnsOutPacket) {
packet.write_short(self.priority);
packet.write_short(self.weight);
packet.write_short(self.port);
packet.write_name(&self.host);
}
fn any(&self) -> &dyn Any {
self
}
fn matches(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_svc) = other.any().downcast_ref::<Self>() {
return self.host == other_svc.host
&& self.port == other_svc.port
&& self.weight == other_svc.weight
&& self.priority == other_svc.priority
&& self.record.entry == other_svc.record.entry;
}
false
}
fn rrdata_match(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_srv) = other.any().downcast_ref::<Self>() {
return self.host == other_srv.host
&& self.port == other_srv.port
&& self.weight == other_srv.weight
&& self.priority == other_srv.priority;
}
false
}
fn compare_rdata(&self, other: &dyn DnsRecordExt) -> cmp::Ordering {
let Some(other_srv) = other.any().downcast_ref::<Self>() else {
return cmp::Ordering::Greater;
};
// 1. compare `priority`
match self
.priority
.to_be_bytes()
.cmp(&other_srv.priority.to_be_bytes())
{
cmp::Ordering::Equal => {
// 2. compare `weight`
match self
.weight
.to_be_bytes()
.cmp(&other_srv.weight.to_be_bytes())
{
cmp::Ordering::Equal => {
// 3. compare `port`.
match self.port.to_be_bytes().cmp(&other_srv.port.to_be_bytes()) {
cmp::Ordering::Equal => self.host.cmp(&other_srv.host),
not_equal => not_equal,
}
}
not_equal => not_equal,
}
}
not_equal => not_equal,
}
}
fn rdata_print(&self) -> String {
format!(
"priority: {}, weight: {}, port: {}, host: {}",
self.priority, self.weight, self.port, self.host
)
}
fn clone_box(&self) -> DnsRecordBox {
Box::new(self.clone())
}
}
/// Resource Record for a DNS TXT record.
///
/// From [RFC 6763 section 6]:
///
/// The format of each constituent string within the DNS TXT record is a
/// single length byte, followed by 0-255 bytes of text data.
///
/// DNS-SD uses DNS TXT records to store arbitrary key/value pairs
/// conveying additional information about the named service. Each
/// key/value pair is encoded as its own constituent string within the
/// DNS TXT record, in the form "key=value" (without the quotation
/// marks). Everything up to the first '=' character is the key (Section
/// 6.4). Everything after the first '=' character to the end of the
/// string (including subsequent '=' characters, if any) is the value
#[derive(Clone)]
pub struct DnsTxt {
pub(crate) record: DnsRecord,
text: Vec<u8>,
}
impl DnsTxt {
pub fn new(name: &str, class: u16, ttl: u32, text: Vec<u8>) -> Self {
let record = DnsRecord::new(name, RRType::TXT, class, ttl);
Self { record, text }
}
pub fn text(&self) -> &[u8] {
&self.text
}
}
impl DnsRecordExt for DnsTxt {
fn get_record(&self) -> &DnsRecord {
&self.record
}
fn get_record_mut(&mut self) -> &mut DnsRecord {
&mut self.record
}
fn write(&self, packet: &mut DnsOutPacket) {
packet.write_bytes(&self.text);
}
fn any(&self) -> &dyn Any {
self
}
fn matches(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_txt) = other.any().downcast_ref::<Self>() {
return self.text == other_txt.text && self.record.entry == other_txt.record.entry;
}
false
}
fn rrdata_match(&self, other: &dyn DnsRecordExt) -> bool {
if let Some(other_txt) = other.any().downcast_ref::<Self>() {
return self.text == other_txt.text;
}
false
}
fn compare_rdata(&self, other: &dyn DnsRecordExt) -> cmp::Ordering {
if let Some(other_txt) = other.any().downcast_ref::<Self>() {
self.text.cmp(&other_txt.text)
} else {
cmp::Ordering::Greater
}
}
fn rdata_print(&self) -> String {
format!("{:?}", decode_txt(&self.text))
}
fn clone_box(&self) -> DnsRecordBox {
Box::new(self.clone())
}
}
impl fmt::Debug for DnsTxt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let properties = decode_txt(&self.text);
write!(
f,
"DnsTxt {{ record: {:?}, text: {:?} }}",
self.record, properties
)
}
}
// Convert from DNS TXT record content to key/value pairs
fn decode_txt(txt: &[u8]) -> Vec<TxtProperty> {
let mut properties = Vec::new();
let mut offset = 0;
while offset < txt.len() {
let length = txt[offset] as usize;
if length == 0 {
break; // reached the end
}
offset += 1; // move over the length byte
let offset_end = offset + length;
if offset_end > txt.len() {
trace!("ERROR: DNS TXT: size given for property is out of range. (offset={}, length={}, offset_end={}, record length={})", offset, length, offset_end, txt.len());
break; // Skipping the rest of the record content, as the size for this property would already be out of range.
}
let kv_bytes = &txt[offset..offset_end];
// split key and val using the first `=`
let (k, v) = kv_bytes.iter().position(|&x| x == b'=').map_or_else(
|| (kv_bytes.to_vec(), None),
|idx| (kv_bytes[..idx].to_vec(), Some(kv_bytes[idx + 1..].to_vec())),
);
// Make sure the key can be stored in UTF-8.
match String::from_utf8(k) {
Ok(k_string) => {
properties.push(TxtProperty {
key: k_string,
val: v,
});
}
Err(e) => trace!("ERROR: convert to String from key: {}", e),
}
offset += length;
}
properties
}
/// Represents a property in a TXT record.
#[derive(Clone, PartialEq, Eq)]
pub struct TxtProperty {
/// The name of the property. The original cases are kept.
key: String,
/// RFC 6763 says values are bytes, not necessarily UTF-8.
/// It is also possible that there is no value, in which case
/// the key is a boolean key.
val: Option<Vec<u8>>,
}
impl TxtProperty {
/// Returns the value of a property as str.
pub fn val_str(&self) -> &str {
self.val
.as_ref()
.map_or("", |v| std::str::from_utf8(&v[..]).unwrap_or_default())
}
}
/// Supports constructing from a tuple.
impl<K, V> From<&(K, V)> for TxtProperty
where
K: ToString,
V: ToString,
{
fn from(prop: &(K, V)) -> Self {
Self {
key: prop.0.to_string(),
val: Some(prop.1.to_string().into_bytes()),
}
}
}
impl<K, V> From<(K, V)> for TxtProperty
where
K: ToString,
V: AsRef<[u8]>,
{
fn from(prop: (K, V)) -> Self {
Self {
key: prop.0.to_string(),
val: Some(prop.1.as_ref().into()),
}
}
}
/// Support a property that has no value.
impl From<&str> for TxtProperty {
fn from(key: &str) -> Self {
Self {
key: key.to_string(),
val: None,
}
}
}
impl fmt::Display for TxtProperty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}={}", self.key, self.val_str())
}
}
/// Mimic the default debug output for a struct, with a twist:
/// - If self.var is UTF-8, will output it as a string in double quotes.
/// - If self.var is not UTF-8, will output its bytes as in hex.
impl fmt::Debug for TxtProperty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_string = self.val.as_ref().map_or_else(
|| "None".to_string(),
|v| {
std::str::from_utf8(&v[..]).map_or_else(
|_| format!("Some({})", u8_slice_to_hex(&v[..])),
|s| format!("Some(\"{}\")", s),
)
},
);
write!(
f,
"TxtProperty {{key: \"{}\", val: {}}}",
&self.key, &val_string,
)
}
}
const HEX_TABLE: [char; 16] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];
/// Create a hex string from `slice`, with a "0x" prefix.
///
/// For example, [1u8, 2u8] -> "0x0102"
fn u8_slice_to_hex(slice: &[u8]) -> String {
let mut hex = String::with_capacity(slice.len() * 2 + 2);
hex.push_str("0x");
for b in slice {
hex.push(HEX_TABLE[(b >> 4) as usize]);
hex.push(HEX_TABLE[(b & 0x0F) as usize]);
}
hex
}
/// A DNS host information record
#[derive(Debug, Clone)]
struct DnsHostInfo {
record: DnsRecord,
cpu: String,
os: String,
}
impl DnsHostInfo {
fn new(name: &str, ty: RRType, class: u16, ttl: u32, cpu: String, os: String) -> Self {
let record = DnsRecord::new(name, ty, class, ttl);
Self { record, cpu, os }
}
}
impl DnsRecordExt for DnsHostInfo {
fn get_record(&self) -> &DnsRecord {
&self.record
}
fn get_record_mut(&mut self) -> &mut DnsRecord {
&mut self.record