/
name.rs
1884 lines (1690 loc) · 62.2 KB
/
name.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 2015-2017 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! domain name, aka labels, implementation
use std::char;
use std::cmp::{Ordering, PartialEq};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use crate::error::*;
use crate::rr::domain::label::{CaseInsensitive, CaseSensitive, IntoLabel, Label, LabelCmp};
use crate::rr::domain::usage::LOCALHOST as LOCALHOST_usage;
use crate::serialize::binary::*;
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
#[cfg(feature = "serde-config")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use tinyvec::TinyVec;
/// A domain name
#[derive(Clone, Default, Debug, Eq)]
pub struct Name {
is_fqdn: bool,
label_data: TinyVec<[u8; 32]>,
label_ends: TinyVec<[u8; 16]>,
}
impl Name {
/// Create a new domain::Name, i.e. label
pub fn new() -> Self {
Default::default()
}
/// Returns the root label, i.e. no labels, can probably make this better in the future.
pub fn root() -> Self {
let mut this = Self::new();
this.is_fqdn = true;
this
}
/// Returns true if there are no labels, i.e. it's empty.
///
/// In DNS the root is represented by `.`
///
/// # Examples
///
/// ```
/// use trust_dns_proto::rr::domain::Name;
///
/// let root = Name::root();
/// assert_eq!(&root.to_string(), ".");
/// ```
pub fn is_root(&self) -> bool {
self.label_ends.is_empty() && self.is_fqdn()
}
/// Returns true if the name is a fully qualified domain name.
///
/// If this is true, it has effects like only querying for this single name, as opposed to building
/// up a search list in resolvers.
///
/// *warning: this interface is unstable and may change in the future*
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let name = Name::from_str("www").unwrap();
/// assert!(!name.is_fqdn());
///
/// let name = Name::from_str("www.example.com").unwrap();
/// assert!(!name.is_fqdn());
///
/// let name = Name::from_str("www.example.com.").unwrap();
/// assert!(name.is_fqdn());
/// ```
pub fn is_fqdn(&self) -> bool {
self.is_fqdn
}
/// Specifies this name is a fully qualified domain name
///
/// *warning: this interface is unstable and may change in the future*
pub fn set_fqdn(&mut self, val: bool) {
self.is_fqdn = val
}
/// Returns an iterator over the labels
pub fn iter(&self) -> LabelIter<'_> {
LabelIter {
name: self,
index: 0,
started: false,
finished: false,
}
}
/// Appends the label to the end of this name
///
/// # Example
///
/// ```rust
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let name = Name::from_str("www.example").unwrap();
/// let name = name.append_label("com").unwrap();
/// assert_eq!(name, Name::from_str("www.example.com").unwrap());
/// ```
pub fn append_label<L: IntoLabel>(mut self, label: L) -> ProtoResult<Self> {
self.label_data
.extend_from_slice(label.into_label()?.as_bytes());
self.label_ends.push(self.label_data.len() as u8);
if self.len() > 255 {
return Err("labels exceed maximum length of 255".into());
};
Ok(self)
}
/// Creates a new Name from the specified labels
///
/// # Arguments
///
/// * `labels` - vector of items which will be stored as Strings.
///
/// # Examples
///
/// ```rust
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// // From strings, uses utf8 conversion
/// let from_labels = Name::from_labels(vec!["www", "example", "com"]).unwrap();
/// assert_eq!(from_labels, Name::from_str("www.example.com").unwrap());
///
/// // Force a set of bytes into labels (this is none-standard and potentially dangerous)
/// let from_labels = Name::from_labels(vec!["bad chars".as_bytes(), "example".as_bytes(), "com".as_bytes()]).unwrap();
/// assert_eq!(from_labels.iter().next(), Some(&b"bad chars"[..]));
///
/// let root = Name::from_labels(Vec::<&str>::new()).unwrap();
/// assert!(root.is_root());
/// ```
pub fn from_labels<I, L>(labels: I) -> ProtoResult<Self>
where
I: IntoIterator<Item = L>,
L: IntoLabel,
{
let (labels, errors): (Vec<_>, Vec<_>) = labels
.into_iter()
.map(IntoLabel::into_label)
.partition(Result::is_ok);
let labels: Vec<_> = labels.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
if labels.len() > 255 {
return Err("labels exceed maximum length of 255".into());
};
if !errors.is_empty() {
return Err(format!("error converting some labels: {:?}", errors).into());
};
let mut label_ends = TinyVec::new();
let mut label_data = TinyVec::new();
for label in labels {
label_data.extend_from_slice(label.as_bytes());
label_ends.push(label_data.len() as u8);
}
Ok(Name {
is_fqdn: true,
label_data,
label_ends,
})
}
/// Appends `other` to `self`, returning a new `Name`
///
/// Carries forward `is_fqdn` from `other`.
///
/// # Examples
///
/// ```rust
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let local = Name::from_str("www").unwrap();
/// let domain = Name::from_str("example.com").unwrap();
/// assert!(!domain.is_fqdn());
///
/// let name = local.clone().append_name(&domain);
/// assert_eq!(name, Name::from_str("www.example.com").unwrap());
/// assert!(!name.is_fqdn());
///
/// // see also `Name::append_domain`
/// let domain = Name::from_str("example.com.").unwrap();
/// assert!(domain.is_fqdn());
/// let name = local.append_name(&domain);
/// assert_eq!(name, Name::from_str("www.example.com.").unwrap());
/// assert!(name.is_fqdn());
/// ```
pub fn append_name(mut self, other: &Self) -> Self {
for label in other.iter() {
self.label_data.extend_from_slice(label);
self.label_ends.push(self.label_data.len() as u8);
}
self.is_fqdn = other.is_fqdn;
self
}
/// Appends the `domain` to `self`, making the new `Name` an FQDN
///
/// This is an alias for `append_name` with the added effect of marking the new `Name` as
/// a fully-qualified-domain-name.
///
/// # Examples
///
/// ```rust
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let local = Name::from_str("www").unwrap();
/// let domain = Name::from_str("example.com").unwrap();
/// let name = local.append_domain(&domain);
/// assert_eq!(name, Name::from_str("www.example.com").unwrap());
/// assert!(name.is_fqdn())
/// ```
pub fn append_domain(self, domain: &Self) -> Self {
let mut this = self.append_name(domain);
this.set_fqdn(true);
this
}
/// Creates a new Name with all labels lowercased
///
/// # Examples
///
/// ```
/// use std::cmp::Ordering;
/// use std::str::FromStr;
///
/// use trust_dns_proto::rr::domain::{Label, Name};
///
/// let example_com = Name::from_ascii("Example.Com").unwrap();
/// assert_eq!(example_com.cmp_case(&Name::from_str("example.com").unwrap()), Ordering::Less);
/// assert!(example_com.to_lowercase().eq_case(&Name::from_str("example.com").unwrap()));
/// ```
pub fn to_lowercase(&self) -> Self {
let new_label_data = self
.label_data
.iter()
.map(|c| c.to_ascii_lowercase())
.collect();
Name {
is_fqdn: self.is_fqdn,
label_data: new_label_data,
label_ends: self.label_ends.clone(),
}
}
/// Trims off the first part of the name, to help with searching for the domain piece
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let example_com = Name::from_str("example.com.").unwrap();
/// assert_eq!(example_com.base_name(), Name::from_str("com.").unwrap());
/// assert_eq!(Name::from_str("com.").unwrap().base_name(), Name::root());
/// assert_eq!(Name::root().base_name(), Name::root());
/// ```
pub fn base_name(&self) -> Name {
let length = self.label_ends.len();
if length > 0 {
return self.trim_to(length - 1);
}
self.clone()
}
/// Trims to the number of labels specified
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let example_com = Name::from_str("example.com.").unwrap();
/// assert_eq!(example_com.trim_to(2), Name::from_str("example.com.").unwrap());
/// assert_eq!(example_com.trim_to(1), Name::from_str("com.").unwrap());
/// assert_eq!(example_com.trim_to(0), Name::root());
/// assert_eq!(example_com.trim_to(3), Name::from_str("example.com.").unwrap());
/// ```
pub fn trim_to(&self, num_labels: usize) -> Name {
if num_labels > self.label_ends.len() {
self.clone()
} else {
Name::from_labels(self.iter().skip(self.label_ends.len() - num_labels)).unwrap()
}
}
/// same as `zone_of` allows for case sensitive call
pub fn zone_of_case(&self, name: &Self) -> bool {
let self_len = self.label_ends.len();
let name_len = name.label_ends.len();
if self_len == 0 {
return true;
}
if name_len == 0 {
// self_len != 0
return false;
}
if self_len > name_len {
return false;
}
let self_iter = self.iter().rev();
let name_iter = name.iter().rev();
let zip_iter = self_iter.zip(name_iter);
for (self_label, name_label) in zip_iter {
if self_label != name_label {
return false;
}
}
true
}
/// returns true if the name components of self are all present at the end of name
///
/// # Example
///
/// ```rust
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let name = Name::from_str("www.example.com").unwrap();
/// let name = Name::from_str("www.example.com").unwrap();
/// let zone = Name::from_str("example.com").unwrap();
/// let another = Name::from_str("example.net").unwrap();
/// assert!(zone.zone_of(&name));
/// assert!(!name.zone_of(&zone));
/// assert!(!another.zone_of(&name));
/// ```
pub fn zone_of(&self, name: &Self) -> bool {
let self_lower = self.to_lowercase();
let name_lower = name.to_lowercase();
self_lower.zone_of_case(&name_lower)
}
/// Returns the number of labels in the name, discounting `*`.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let root = Name::root();
/// assert_eq!(root.num_labels(), 0);
///
/// let example_com = Name::from_str("example.com").unwrap();
/// assert_eq!(example_com.num_labels(), 2);
///
/// let star_example_com = Name::from_str("*.example.com.").unwrap();
/// assert_eq!(star_example_com.num_labels(), 2);
/// ```
pub fn num_labels(&self) -> u8 {
// it is illegal to have more than 256 labels.
let num = self.label_ends.len() as u8;
self.iter()
.next()
.map(|l| if l == b"*" { num - 1 } else { num })
.unwrap_or(num)
}
/// returns the length in bytes of the labels. '.' counts as 1
///
/// This can be used as an estimate, when serializing labels, they will often be compressed
/// and/or escaped causing the exact length to be different.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// assert_eq!(Name::from_str("www.example.com.").unwrap().len(), 16);
/// assert_eq!(Name::from_str(".").unwrap().len(), 1);
/// assert_eq!(Name::root().len(), 1);
/// ```
pub fn len(&self) -> usize {
let dots = if !self.label_ends.is_empty() {
self.label_ends.len()
} else {
1
};
dots + self.label_data.len()
}
/// Returns whether the length of the labels, in bytes is 0. In practice, since '.' counts as
/// 1, this is never the case so the method returns false.
pub fn is_empty(&self) -> bool {
false
}
/// attempts to parse a name such as `"example.com."` or `"subdomain.example.com."`
///
/// # Examples
///
/// ```rust
/// use std::str::FromStr;
/// use trust_dns_proto::rr::domain::Name;
///
/// let name = Name::from_str("example.com.").unwrap();
/// assert_eq!(name.base_name(), Name::from_str("com.").unwrap());
/// assert_eq!(name.iter().next(), Some(&b"example"[..]));
/// ```
pub fn parse(local: &str, origin: Option<&Self>) -> ProtoResult<Self> {
Self::from_encoded_str::<LabelEncUtf8>(local, origin)
}
/// Will convert the string to a name only allowing ascii as valid input
///
/// This method will also preserve the case of the name where that's desirable
///
/// # Examples
///
/// ```
/// use trust_dns_proto::rr::Name;
///
/// let bytes_name = Name::from_labels(vec!["WWW".as_bytes(), "example".as_bytes(), "COM".as_bytes()]).unwrap();
/// let ascii_name = Name::from_ascii("WWW.example.COM.").unwrap();
/// let lower_name = Name::from_ascii("www.example.com.").unwrap();
///
/// assert!(bytes_name.eq_case(&ascii_name));
/// assert!(!lower_name.eq_case(&ascii_name));
///
/// // escaped values
/// let bytes_name = Name::from_labels(vec!["email.name".as_bytes(), "example".as_bytes(), "com".as_bytes()]).unwrap();
/// let name = Name::from_ascii("email\\.name.example.com.").unwrap();
///
/// assert_eq!(bytes_name, name);
///
/// let bytes_name = Name::from_labels(vec!["bad.char".as_bytes(), "example".as_bytes(), "com".as_bytes()]).unwrap();
/// let name = Name::from_ascii("bad\\056char.example.com.").unwrap();
///
/// assert_eq!(bytes_name, name);
/// ```
pub fn from_ascii<S: AsRef<str>>(name: S) -> ProtoResult<Self> {
Self::from_encoded_str::<LabelEncAscii>(name.as_ref(), None)
}
// TODO: currently reserved to be private to the crate, due to confusion of IDNA vs. utf8 in https://tools.ietf.org/html/rfc6762#appendix-F
/// Will convert the string to a name using IDNA, punycode, to encode the UTF8 as necessary
///
/// When making names IDNA compatible, there is a side-effect of lowercasing the name.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::Name;
///
/// let bytes_name = Name::from_labels(vec!["WWW".as_bytes(), "example".as_bytes(), "COM".as_bytes()]).unwrap();
///
/// // from_str calls through to from_utf8
/// let utf8_name = Name::from_str("WWW.example.COM.").unwrap();
/// let lower_name = Name::from_str("www.example.com.").unwrap();
///
/// assert!(!bytes_name.eq_case(&utf8_name));
/// assert!(lower_name.eq_case(&utf8_name));
/// ```
pub fn from_utf8<S: AsRef<str>>(name: S) -> ProtoResult<Self> {
Self::from_encoded_str::<LabelEncUtf8>(name.as_ref(), None)
}
/// First attempts to decode via `from_utf8`, if that fails IDNA checks, then falls back to
/// ascii decoding.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::Name;
///
/// // Ok, underscore in the beginning of a name
/// assert!(Name::from_utf8("_allows.example.com.").is_ok());
///
/// // Error, underscore in the end
/// assert!(Name::from_utf8("dis_allowed.example.com.").is_err());
///
/// // Ok, relaxed mode
/// assert!(Name::from_str_relaxed("allow_in_.example.com.").is_ok());
/// ```
pub fn from_str_relaxed<S: AsRef<str>>(name: S) -> ProtoResult<Self> {
let name = name.as_ref();
Self::from_utf8(name).or_else(|_| Self::from_ascii(name))
}
fn from_encoded_str<E: LabelEnc>(local: &str, origin: Option<&Self>) -> ProtoResult<Self> {
let mut name = Name::new();
let mut label = String::new();
let mut state = ParseState::Label;
// short circuit root parse
if local == "." {
name.set_fqdn(true);
return Ok(name);
}
// TODO: it would be nice to relocate this to Label, but that is hard because the label boundary can only be detected after processing escapes...
// evaluate all characters
for ch in local.chars() {
match state {
ParseState::Label => match ch {
'.' => {
name = name.append_label(E::to_label(&label)?)?;
label.clear();
}
'\\' => state = ParseState::Escape1,
ch if !ch.is_control() && !ch.is_whitespace() => label.push(ch),
_ => return Err(format!("unrecognized char: {}", ch).into()),
},
ParseState::Escape1 => {
if ch.is_numeric() {
state =
ParseState::Escape2(ch.to_digit(8).ok_or_else(|| {
ProtoError::from(format!("illegal char: {}", ch))
})?);
} else {
// it's a single escaped char
label.push(ch);
state = ParseState::Label;
}
}
ParseState::Escape2(i) => {
if ch.is_numeric() {
state = ParseState::Escape3(
i,
ch.to_digit(8)
.ok_or_else(|| ProtoError::from(format!("illegal char: {}", ch)))?,
);
} else {
return Err(ProtoError::from(format!("unrecognized char: {}", ch)));
}
}
ParseState::Escape3(i, ii) => {
if ch.is_numeric() {
// octal conversion
let val: u32 = (i * 8 * 8)
+ (ii * 8)
+ ch.to_digit(8)
.ok_or_else(|| ProtoError::from(format!("illegal char: {}", ch)))?;
let new: char = char::from_u32(val)
.ok_or_else(|| ProtoError::from(format!("illegal char: {}", ch)))?;
label.push(new);
state = ParseState::Label;
} else {
return Err(format!("unrecognized char: {}", ch).into());
}
}
}
}
if !label.is_empty() {
name = name.append_label(E::to_label(&label)?)?;
}
if local.ends_with('.') {
name.set_fqdn(true);
} else if let Some(other) = origin {
return Ok(name.append_domain(other));
}
Ok(name)
}
/// Emits the canonical version of the name to the encoder.
///
/// In canonical form, there will be no pointers written to the encoder (i.e. no compression).
pub fn emit_as_canonical(
&self,
encoder: &mut BinEncoder<'_>,
canonical: bool,
) -> ProtoResult<()> {
let buf_len = encoder.len(); // lazily assert the size is less than 255...
// lookup the label in the BinEncoder
// if it exists, write the Pointer
let labels = self.iter();
// start index of each label
let mut labels_written: Vec<usize> = Vec::with_capacity(self.label_ends.len());
if canonical {
for label in labels {
encoder.emit_character_data(label)?;
}
} else {
// we're going to write out each label, tracking the indexes of the start to each label
// then we'll look to see if we can remove them and recapture the capacity in the buffer...
for label in labels {
if label.len() > 63 {
return Err(ProtoErrorKind::LabelBytesTooLong(label.len()).into());
}
labels_written.push(encoder.offset());
encoder.emit_character_data(label)?;
}
// we've written all the labels to the buf, the current offset is the end
let last_index = encoder.offset();
// now search for other labels already stored matching from the beginning label, strip then to the end
// if it's not found, then store this as a new label
for label_idx in &labels_written {
let label_ptr: Option<u16> = encoder.get_label_pointer(*label_idx, last_index);
// before we write the label, let's look for the current set of labels.
if let Some(loc) = label_ptr {
// reset back to the beginning of this label, and then write the pointer...
encoder.set_offset(*label_idx);
encoder.trim();
// write out the pointer marker
// or'd with the location which shouldn't be larger than this 2^14 or 16k
encoder.emit_u16(0xC000u16 | (loc & 0x3FFFu16))?;
// we found a pointer don't write more, break
return Ok(());
} else {
// no existing label exists, store this new one.
encoder.store_label_pointer(*label_idx, last_index);
}
}
}
// if we're getting here, then we didn't write out a pointer and are ending the name
// the end of the list of names
encoder.emit(0)?;
// the entire name needs to be less than 256.
let length = encoder.len() - buf_len;
if length > 255 {
return Err(ProtoErrorKind::DomainNameTooLong(length).into());
}
Ok(())
}
/// Writes the labels, as lower case, to the encoder
///
/// # Arguments
///
/// * `encoder` - encoder for writing this name
/// * `lowercase` - if true the name will be lowercased, otherwise it will not be changed when writing
pub fn emit_with_lowercase(
&self,
encoder: &mut BinEncoder<'_>,
lowercase: bool,
) -> ProtoResult<()> {
let is_canonical_names = encoder.is_canonical_names();
if lowercase {
self.to_lowercase()
.emit_as_canonical(encoder, is_canonical_names)
} else {
self.emit_as_canonical(encoder, is_canonical_names)
}
}
/// compares with the other label, ignoring case
fn cmp_with_f<F: LabelCmp>(&self, other: &Self) -> Ordering {
if self.label_ends.is_empty() && other.label_ends.is_empty() {
return Ordering::Equal;
}
// we reverse the iters so that we are comparing from the root/domain to the local...
let self_labels = self.iter().rev();
let other_labels = other.iter().rev();
for (l, r) in self_labels.zip(other_labels) {
let l = Label::from_raw_bytes(l).unwrap();
let r = Label::from_raw_bytes(r).unwrap();
match l.cmp_with_f::<F>(&r) {
Ordering::Equal => continue,
not_eq => return not_eq,
}
}
self.label_ends.len().cmp(&other.label_ends.len())
}
/// Case sensitive comparison
pub fn cmp_case(&self, other: &Self) -> Ordering {
self.cmp_with_f::<CaseSensitive>(other)
}
/// Compares the Names, in a case sensitive manner
pub fn eq_case(&self, other: &Self) -> bool {
self.cmp_with_f::<CaseSensitive>(other) == Ordering::Equal
}
/// Converts this name into an ascii safe string.
///
/// If the name is an IDNA name, then the name labels will be returned with the `xn--` prefix.
/// see `to_utf8` or the `Display` impl for methods which convert labels to utf8.
pub fn to_ascii(&self) -> String {
let mut s = String::with_capacity(self.len());
self.write_labels::<String, LabelEncAscii>(&mut s)
.expect("string conversion of name should not fail");
s
}
/// Converts the Name labels to the utf8 String form.
///
/// This converts the name to an unescaped format, that could be used with parse. If, the name is
/// is followed by the final `.`, e.g. as in `www.example.com.`, which represents a fully
/// qualified Name.
pub fn to_utf8(&self) -> String {
format!("{}", self)
}
/// Converts a *.arpa Name in a PTR record back into an IpNet if possible.
pub fn parse_arpa_name(&self) -> Result<IpNet, ProtoError> {
if !self.is_fqdn() {
return Err("PQDN cannot be valid arpa name".into());
}
let mut iter = self.iter().rev();
let first = iter
.next()
.ok_or_else(|| ProtoError::from("not an arpa address"))?;
if !"arpa".eq_ignore_ascii_case(std::str::from_utf8(first)?) {
return Err("not an arpa address".into());
}
let second = iter
.next()
.ok_or_else(|| ProtoError::from("invalid arpa address"))?;
let mut prefix_len: u8 = 0;
match &std::str::from_utf8(second)?.to_ascii_lowercase()[..] {
"in-addr" => {
let mut octets: [u8; 4] = [0; 4];
for octet in octets.iter_mut() {
match iter.next() {
Some(label) => *octet = std::str::from_utf8(label)?.parse()?,
None => break,
}
prefix_len += 8;
}
if iter.next().is_some() {
return Err("unrecognized in-addr.arpa.".into());
}
Ok(IpNet::V4(
Ipv4Net::new(octets.into(), prefix_len).expect("Ipv4Net::new"),
))
}
"ip6" => {
let mut address: u128 = 0;
while prefix_len < 128 {
match iter.next() {
Some(label) => {
if label.len() == 1 {
prefix_len += 4;
let hex = u8::from_str_radix(std::str::from_utf8(label)?, 16)?;
address |= u128::from(hex) << (128 - prefix_len);
} else {
return Err("invalid label length for ip6.arpa".into());
}
}
None => break,
}
}
if iter.next().is_some() {
return Err("unrecognized ip6.arpa.".into());
}
Ok(IpNet::V6(
Ipv6Net::new(address.into(), prefix_len).expect("Ipv6Net::new"),
))
}
_ => Err("unrecognized arpa address".into()),
}
}
fn write_labels<W: Write, E: LabelEnc>(&self, f: &mut W) -> Result<(), fmt::Error> {
let mut iter = self.iter().map(|b| Label::from_raw_bytes(b).unwrap());
if let Some(label) = iter.next() {
E::write_label(f, &label)?;
}
for label in iter {
write!(f, ".")?;
E::write_label(f, &label)?;
}
// if it was the root name
if self.is_root() || self.is_fqdn() {
write!(f, ".")?;
}
Ok(())
}
/// Returns true if the `Name` is either localhost or in the localhost zone.
///
/// # Example
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::Name;
///
/// let name = Name::from_str("localhost").unwrap();
/// assert!(name.is_localhost());
///
/// let name = Name::from_str("localhost.").unwrap();
/// assert!(name.is_localhost());
///
/// let name = Name::from_str("my.localhost.").unwrap();
/// assert!(name.is_localhost());
/// ```
pub fn is_localhost(&self) -> bool {
LOCALHOST_usage.zone_of(self)
}
/// True if the first label of this name is the wildcard, i.e. '*'
///
/// # Example
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::Name;
///
/// let name = Name::from_str("www.example.com").unwrap();
/// assert!(!name.is_wildcard());
///
/// let name = Name::from_str("*.example.com").unwrap();
/// assert!(name.is_wildcard());
///
/// let name = Name::root();
/// assert!(!name.is_wildcard());
/// ```
pub fn is_wildcard(&self) -> bool {
self.iter().next().map_or(false, |l| l == b"*")
}
/// Converts a name to a wildcard, by replacing the first label with `*`
///
/// # Example
///
/// ```
/// use std::str::FromStr;
/// use trust_dns_proto::rr::Name;
///
/// let name = Name::from_str("www.example.com").unwrap().into_wildcard();
/// assert_eq!(name, Name::from_str("*.example.com.").unwrap());
///
/// // does nothing if the root
/// let name = Name::root().into_wildcard();
/// assert_eq!(name, Name::root());
/// ```
pub fn into_wildcard(self) -> Self {
if self.label_ends.is_empty() {
Name::root()
} else {
let mut label_data = TinyVec::new();
label_data.push(b'*');
let mut label_ends = TinyVec::new();
label_ends.push(1);
for label in self.iter().skip(1) {
label_data.extend_from_slice(label);
label_ends.push(label_data.len() as u8);
}
Name {
label_data,
label_ends,
is_fqdn: self.is_fqdn,
}
}
}
}
trait LabelEnc {
#[allow(clippy::wrong_self_convention)]
fn to_label(name: &str) -> ProtoResult<Label>;
fn write_label<W: Write>(f: &mut W, label: &Label) -> Result<(), fmt::Error>;
}
struct LabelEncAscii;
impl LabelEnc for LabelEncAscii {
#[allow(clippy::wrong_self_convention)]
fn to_label(name: &str) -> ProtoResult<Label> {
Label::from_ascii(name)
}
fn write_label<W: Write>(f: &mut W, label: &Label) -> Result<(), fmt::Error> {
label.write_ascii(f)
}
}
struct LabelEncUtf8;
impl LabelEnc for LabelEncUtf8 {
#[allow(clippy::wrong_self_convention)]
fn to_label(name: &str) -> ProtoResult<Label> {
Label::from_utf8(name)
}
fn write_label<W: Write>(f: &mut W, label: &Label) -> Result<(), fmt::Error> {
write!(f, "{}", label)
}
}
/// An iterator over labels in a name
pub struct LabelIter<'a> {
name: &'a Name,
index: usize,
started: bool,
finished: bool,
}
impl<'a> Iterator for LabelIter<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
if self.finished {
return None;
}
self.started = true;
let end = *self.name.label_ends.get(self.index)?;
let start = if self.index == 0 {
0
} else {
self.name.label_ends[self.index - 1]
};
self.index += 1;
if self.index == self.name.label_ends.len() {
self.finished = true;
}
Some(&self.name.label_data[start as usize..end as usize])
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.name.label_ends.len() - self.index;
(len, Some(len))
}
}
impl<'a> ExactSizeIterator for LabelIter<'a> {}
impl<'a> DoubleEndedIterator for LabelIter<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.finished {
return None;
}
if !self.started {
self.index = self.name.label_ends.len().checked_sub(1)?;
}
self.started = true;
let end = *self.name.label_ends.get(self.index)?;
let start = if self.index == 0 {
0
} else {
self.name.label_ends[self.index - 1]
};
if self.index == 0 {
self.finished = true;
} else {
self.index -= 1;
}
Some(&self.name.label_data[start as usize..end as usize])
}
}
impl<'a> IntoIterator for &'a Name {
type Item = &'a [u8];
type IntoIter = LabelIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl From<IpAddr> for Name {
fn from(addr: IpAddr) -> Name {
match addr {
IpAddr::V4(ip) => ip.into(),
IpAddr::V6(ip) => ip.into(),
}