1 // Copyright 2013-2014 The rust-url developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 //! [*Unicode IDNA Compatibility Processing*
10 //! (Unicode Technical Standard #46)](http://www.unicode.org/reports/tr46/)
11 
12 use self::Mapping::*;
13 use crate::punycode;
14 use std::{error::Error as StdError, fmt};
15 use unicode_bidi::{bidi_class, BidiClass};
16 use unicode_normalization::char::is_combining_mark;
17 use unicode_normalization::{is_nfc, UnicodeNormalization};
18 
19 include!("uts46_mapping_table.rs");
20 
21 const PUNYCODE_PREFIX: &str = "xn--";
22 
23 #[derive(Debug)]
24 struct StringTableSlice {
25     // Store these as separate fields so the structure will have an
26     // alignment of 1 and thus pack better into the Mapping enum, below.
27     byte_start_lo: u8,
28     byte_start_hi: u8,
29     byte_len: u8,
30 }
31 
decode_slice(slice: &StringTableSlice) -> &'static str32 fn decode_slice(slice: &StringTableSlice) -> &'static str {
33     let lo = slice.byte_start_lo as usize;
34     let hi = slice.byte_start_hi as usize;
35     let start = (hi << 8) | lo;
36     let len = slice.byte_len as usize;
37     &STRING_TABLE[start..(start + len)]
38 }
39 
40 #[repr(u8)]
41 #[derive(Debug)]
42 enum Mapping {
43     Valid,
44     Ignored,
45     Mapped(StringTableSlice),
46     Deviation(StringTableSlice),
47     Disallowed,
48     DisallowedStd3Valid,
49     DisallowedStd3Mapped(StringTableSlice),
50     DisallowedIdna2008,
51 }
52 
find_char(codepoint: char) -> &'static Mapping53 fn find_char(codepoint: char) -> &'static Mapping {
54     let idx = match TABLE.binary_search_by_key(&codepoint, |&val| val.0) {
55         Ok(idx) => idx,
56         Err(idx) => idx - 1,
57     };
58 
59     const SINGLE_MARKER: u16 = 1 << 15;
60 
61     let (base, x) = TABLE[idx];
62     let single = (x & SINGLE_MARKER) != 0;
63     let offset = !SINGLE_MARKER & x;
64 
65     if single {
66         &MAPPING_TABLE[offset as usize]
67     } else {
68         &MAPPING_TABLE[(offset + (codepoint as u16 - base as u16)) as usize]
69     }
70 }
71 
72 struct Mapper<'a> {
73     chars: std::str::Chars<'a>,
74     config: Config,
75     errors: &'a mut Errors,
76     slice: Option<std::str::Chars<'static>>,
77 }
78 
79 impl<'a> Iterator for Mapper<'a> {
80     type Item = char;
81 
next(&mut self) -> Option<Self::Item>82     fn next(&mut self) -> Option<Self::Item> {
83         loop {
84             if let Some(s) = &mut self.slice {
85                 match s.next() {
86                     Some(c) => return Some(c),
87                     None => {
88                         self.slice = None;
89                     }
90                 }
91             }
92 
93             let codepoint = self.chars.next()?;
94             if let '.' | '-' | 'a'..='z' | '0'..='9' = codepoint {
95                 return Some(codepoint);
96             }
97 
98             return Some(match *find_char(codepoint) {
99                 Mapping::Valid => codepoint,
100                 Mapping::Ignored => continue,
101                 Mapping::Mapped(ref slice) => {
102                     self.slice = Some(decode_slice(slice).chars());
103                     continue;
104                 }
105                 Mapping::Deviation(ref slice) => {
106                     if self.config.transitional_processing {
107                         self.slice = Some(decode_slice(slice).chars());
108                         continue;
109                     } else {
110                         codepoint
111                     }
112                 }
113                 Mapping::Disallowed => {
114                     self.errors.disallowed_character = true;
115                     codepoint
116                 }
117                 Mapping::DisallowedStd3Valid => {
118                     if self.config.use_std3_ascii_rules {
119                         self.errors.disallowed_by_std3_ascii_rules = true;
120                     };
121                     codepoint
122                 }
123                 Mapping::DisallowedStd3Mapped(ref slice) => {
124                     if self.config.use_std3_ascii_rules {
125                         self.errors.disallowed_mapped_in_std3 = true;
126                     };
127                     self.slice = Some(decode_slice(slice).chars());
128                     continue;
129                 }
130                 Mapping::DisallowedIdna2008 => {
131                     if self.config.use_idna_2008_rules {
132                         self.errors.disallowed_in_idna_2008 = true;
133                     }
134                     codepoint
135                 }
136             });
137         }
138     }
139 }
140 
141 // http://tools.ietf.org/html/rfc5893#section-2
passes_bidi(label: &str, is_bidi_domain: bool) -> bool142 fn passes_bidi(label: &str, is_bidi_domain: bool) -> bool {
143     // Rule 0: Bidi Rules apply to Bidi Domain Names: a name with at least one RTL label.  A label
144     // is RTL if it contains at least one character of bidi class R, AL or AN.
145     if !is_bidi_domain {
146         return true;
147     }
148 
149     let mut chars = label.chars();
150     let first_char_class = match chars.next() {
151         Some(c) => bidi_class(c),
152         None => return true, // empty string
153     };
154 
155     match first_char_class {
156         // LTR label
157         BidiClass::L => {
158             // Rule 5
159             while let Some(c) = chars.next() {
160                 if !matches!(
161                     bidi_class(c),
162                     BidiClass::L
163                         | BidiClass::EN
164                         | BidiClass::ES
165                         | BidiClass::CS
166                         | BidiClass::ET
167                         | BidiClass::ON
168                         | BidiClass::BN
169                         | BidiClass::NSM
170                 ) {
171                     return false;
172                 }
173             }
174 
175             // Rule 6
176             // must end in L or EN followed by 0 or more NSM
177             let mut rev_chars = label.chars().rev();
178             let mut last_non_nsm = rev_chars.next();
179             loop {
180                 match last_non_nsm {
181                     Some(c) if bidi_class(c) == BidiClass::NSM => {
182                         last_non_nsm = rev_chars.next();
183                         continue;
184                     }
185                     _ => {
186                         break;
187                     }
188                 }
189             }
190             match last_non_nsm {
191                 Some(c) if bidi_class(c) == BidiClass::L || bidi_class(c) == BidiClass::EN => {}
192                 Some(_) => {
193                     return false;
194                 }
195                 _ => {}
196             }
197         }
198 
199         // RTL label
200         BidiClass::R | BidiClass::AL => {
201             let mut found_en = false;
202             let mut found_an = false;
203 
204             // Rule 2
205             for c in chars {
206                 let char_class = bidi_class(c);
207                 if char_class == BidiClass::EN {
208                     found_en = true;
209                 } else if char_class == BidiClass::AN {
210                     found_an = true;
211                 }
212 
213                 if !matches!(
214                     char_class,
215                     BidiClass::R
216                         | BidiClass::AL
217                         | BidiClass::AN
218                         | BidiClass::EN
219                         | BidiClass::ES
220                         | BidiClass::CS
221                         | BidiClass::ET
222                         | BidiClass::ON
223                         | BidiClass::BN
224                         | BidiClass::NSM
225                 ) {
226                     return false;
227                 }
228             }
229             // Rule 3
230             let mut rev_chars = label.chars().rev();
231             let mut last = rev_chars.next();
232             loop {
233                 // must end in L or EN followed by 0 or more NSM
234                 match last {
235                     Some(c) if bidi_class(c) == BidiClass::NSM => {
236                         last = rev_chars.next();
237                         continue;
238                     }
239                     _ => {
240                         break;
241                     }
242                 }
243             }
244             match last {
245                 Some(c)
246                     if matches!(
247                         bidi_class(c),
248                         BidiClass::R | BidiClass::AL | BidiClass::EN | BidiClass::AN
249                     ) => {}
250                 _ => {
251                     return false;
252                 }
253             }
254 
255             // Rule 4
256             if found_an && found_en {
257                 return false;
258             }
259         }
260 
261         // Rule 1: Should start with L or R/AL
262         _ => {
263             return false;
264         }
265     }
266 
267     true
268 }
269 
270 /// Check the validity criteria for the given label
271 ///
272 /// V1 (NFC) and V8 (Bidi) are checked inside `processing()` to prevent doing duplicate work.
273 ///
274 /// http://www.unicode.org/reports/tr46/#Validity_Criteria
check_validity(label: &str, config: Config, errors: &mut Errors)275 fn check_validity(label: &str, config: Config, errors: &mut Errors) {
276     let first_char = label.chars().next();
277     if first_char == None {
278         // Empty string, pass
279         return;
280     }
281 
282     // V2: No U+002D HYPHEN-MINUS in both third and fourth positions.
283     //
284     // NOTE: Spec says that the label must not contain a HYPHEN-MINUS character in both the
285     // third and fourth positions. But nobody follows this criteria. See the spec issue below:
286     // https://github.com/whatwg/url/issues/53
287 
288     // V3: neither begin nor end with a U+002D HYPHEN-MINUS
289     if config.check_hyphens && (label.starts_with('-') || label.ends_with('-')) {
290         errors.check_hyphens = true;
291         return;
292     }
293 
294     // V4: not contain a U+002E FULL STOP
295     //
296     // Here, label can't contain '.' since the input is from .split('.')
297 
298     // V5: not begin with a GC=Mark
299     if is_combining_mark(first_char.unwrap()) {
300         errors.start_combining_mark = true;
301         return;
302     }
303 
304     // V6: Check against Mapping Table
305     if label.chars().any(|c| match *find_char(c) {
306         Mapping::Valid | Mapping::DisallowedIdna2008 => false,
307         Mapping::Deviation(_) => config.transitional_processing,
308         Mapping::DisallowedStd3Valid => config.use_std3_ascii_rules,
309         _ => true,
310     }) {
311         errors.invalid_mapping = true;
312     }
313 
314     // V7: ContextJ rules
315     //
316     // TODO: Implement rules and add *CheckJoiners* flag.
317 
318     // V8: Bidi rules are checked inside `processing()`
319 }
320 
321 /// http://www.unicode.org/reports/tr46/#Processing
322 #[allow(clippy::manual_strip)] // introduced in 1.45, MSRV is 1.36
processing( domain: &str, config: Config, normalized: &mut String, output: &mut String, ) -> Errors323 fn processing(
324     domain: &str,
325     config: Config,
326     normalized: &mut String,
327     output: &mut String,
328 ) -> Errors {
329     // Weed out the simple cases: only allow all lowercase ASCII characters and digits where none
330     // of the labels start with PUNYCODE_PREFIX and labels don't start or end with hyphen.
331     let (mut prev, mut simple, mut puny_prefix) = ('?', !domain.is_empty(), 0);
332     for c in domain.chars() {
333         if c == '.' {
334             if prev == '-' {
335                 simple = false;
336                 break;
337             }
338             puny_prefix = 0;
339             continue;
340         } else if puny_prefix == 0 && c == '-' {
341             simple = false;
342             break;
343         } else if puny_prefix < 5 {
344             if c == ['x', 'n', '-', '-'][puny_prefix] {
345                 puny_prefix += 1;
346                 if puny_prefix == 4 {
347                     simple = false;
348                     break;
349                 }
350             } else {
351                 puny_prefix = 5;
352             }
353         }
354         if !c.is_ascii_lowercase() && !c.is_ascii_digit() {
355             simple = false;
356             break;
357         }
358         prev = c;
359     }
360 
361     if simple {
362         output.push_str(domain);
363         return Errors::default();
364     }
365 
366     normalized.clear();
367     let mut errors = Errors::default();
368     let offset = output.len();
369 
370     let iter = Mapper {
371         chars: domain.chars(),
372         config,
373         errors: &mut errors,
374         slice: None,
375     };
376 
377     normalized.extend(iter.nfc());
378 
379     let mut decoder = punycode::Decoder::default();
380     let non_transitional = config.transitional_processing(false);
381     let (mut first, mut has_bidi_labels) = (true, false);
382     for label in normalized.split('.') {
383         if !first {
384             output.push('.');
385         }
386         first = false;
387         if label.starts_with(PUNYCODE_PREFIX) {
388             match decoder.decode(&label[PUNYCODE_PREFIX.len()..]) {
389                 Ok(decode) => {
390                     let start = output.len();
391                     output.extend(decode);
392                     let decoded_label = &output[start..];
393 
394                     if !has_bidi_labels {
395                         has_bidi_labels |= is_bidi_domain(decoded_label);
396                     }
397 
398                     if !errors.is_err() {
399                         if !is_nfc(&decoded_label) {
400                             errors.nfc = true;
401                         } else {
402                             check_validity(decoded_label, non_transitional, &mut errors);
403                         }
404                     }
405                 }
406                 Err(()) => {
407                     has_bidi_labels = true;
408                     errors.punycode = true;
409                 }
410             }
411         } else {
412             if !has_bidi_labels {
413                 has_bidi_labels |= is_bidi_domain(label);
414             }
415 
416             // `normalized` is already `NFC` so we can skip that check
417             check_validity(label, config, &mut errors);
418             output.push_str(label)
419         }
420     }
421 
422     for label in output[offset..].split('.') {
423         // V8: Bidi rules
424         //
425         // TODO: Add *CheckBidi* flag
426         if !passes_bidi(label, has_bidi_labels) {
427             errors.check_bidi = true;
428             break;
429         }
430     }
431 
432     errors
433 }
434 
435 #[derive(Default)]
436 pub struct Idna {
437     config: Config,
438     normalized: String,
439     output: String,
440 }
441 
442 impl Idna {
new(config: Config) -> Self443     pub fn new(config: Config) -> Self {
444         Self {
445             config,
446             normalized: String::new(),
447             output: String::new(),
448         }
449     }
450 
451     /// http://www.unicode.org/reports/tr46/#ToASCII
452     #[allow(clippy::wrong_self_convention)]
to_ascii<'a>(&'a mut self, domain: &str, out: &mut String) -> Result<(), Errors>453     pub fn to_ascii<'a>(&'a mut self, domain: &str, out: &mut String) -> Result<(), Errors> {
454         let mut errors = processing(domain, self.config, &mut self.normalized, &mut self.output);
455 
456         let mut first = true;
457         for label in self.output.split('.') {
458             if !first {
459                 out.push('.');
460             }
461             first = false;
462 
463             if label.is_ascii() {
464                 out.push_str(label);
465             } else {
466                 let offset = out.len();
467                 out.push_str(PUNYCODE_PREFIX);
468                 if let Err(()) = punycode::encode_into(label.chars(), out) {
469                     errors.punycode = true;
470                     out.truncate(offset);
471                 }
472             }
473         }
474 
475         if self.config.verify_dns_length {
476             let domain = if out.ends_with('.') {
477                 &out[..out.len() - 1]
478             } else {
479                 &*out
480             };
481             if domain.is_empty() || domain.split('.').any(|label| label.is_empty()) {
482                 errors.too_short_for_dns = true;
483             }
484             if domain.len() > 253 || domain.split('.').any(|label| label.len() > 63) {
485                 errors.too_long_for_dns = true;
486             }
487         }
488 
489         errors.into()
490     }
491 
492     /// http://www.unicode.org/reports/tr46/#ToUnicode
493     #[allow(clippy::wrong_self_convention)]
to_unicode<'a>(&'a mut self, domain: &str, out: &mut String) -> Result<(), Errors>494     pub fn to_unicode<'a>(&'a mut self, domain: &str, out: &mut String) -> Result<(), Errors> {
495         processing(domain, self.config, &mut self.normalized, out).into()
496     }
497 }
498 
499 #[derive(Clone, Copy)]
500 pub struct Config {
501     use_std3_ascii_rules: bool,
502     transitional_processing: bool,
503     verify_dns_length: bool,
504     check_hyphens: bool,
505     use_idna_2008_rules: bool,
506 }
507 
508 /// The defaults are that of https://url.spec.whatwg.org/#idna
509 impl Default for Config {
default() -> Self510     fn default() -> Self {
511         Config {
512             use_std3_ascii_rules: false,
513             transitional_processing: false,
514             check_hyphens: false,
515             // check_bidi: true,
516             // check_joiners: true,
517 
518             // Only use for to_ascii, not to_unicode
519             verify_dns_length: false,
520             use_idna_2008_rules: false,
521         }
522     }
523 }
524 
525 impl Config {
526     #[inline]
use_std3_ascii_rules(mut self, value: bool) -> Self527     pub fn use_std3_ascii_rules(mut self, value: bool) -> Self {
528         self.use_std3_ascii_rules = value;
529         self
530     }
531 
532     #[inline]
transitional_processing(mut self, value: bool) -> Self533     pub fn transitional_processing(mut self, value: bool) -> Self {
534         self.transitional_processing = value;
535         self
536     }
537 
538     #[inline]
verify_dns_length(mut self, value: bool) -> Self539     pub fn verify_dns_length(mut self, value: bool) -> Self {
540         self.verify_dns_length = value;
541         self
542     }
543 
544     #[inline]
check_hyphens(mut self, value: bool) -> Self545     pub fn check_hyphens(mut self, value: bool) -> Self {
546         self.check_hyphens = value;
547         self
548     }
549 
550     #[inline]
use_idna_2008_rules(mut self, value: bool) -> Self551     pub fn use_idna_2008_rules(mut self, value: bool) -> Self {
552         self.use_idna_2008_rules = value;
553         self
554     }
555 
556     /// http://www.unicode.org/reports/tr46/#ToASCII
to_ascii(self, domain: &str) -> Result<String, Errors>557     pub fn to_ascii(self, domain: &str) -> Result<String, Errors> {
558         let mut result = String::new();
559         let mut codec = Idna::new(self);
560         codec.to_ascii(domain, &mut result).map(|()| result)
561     }
562 
563     /// http://www.unicode.org/reports/tr46/#ToUnicode
to_unicode(self, domain: &str) -> (String, Result<(), Errors>)564     pub fn to_unicode(self, domain: &str) -> (String, Result<(), Errors>) {
565         let mut codec = Idna::new(self);
566         let mut out = String::with_capacity(domain.len());
567         let result = codec.to_unicode(domain, &mut out);
568         (out, result)
569     }
570 }
571 
is_bidi_domain(s: &str) -> bool572 fn is_bidi_domain(s: &str) -> bool {
573     for c in s.chars() {
574         if c.is_ascii_graphic() {
575             continue;
576         }
577         match bidi_class(c) {
578             BidiClass::R | BidiClass::AL | BidiClass::AN => return true,
579             _ => {}
580         }
581     }
582     false
583 }
584 
585 /// Errors recorded during UTS #46 processing.
586 ///
587 /// This is opaque for now, indicating what types of errors have been encountered at least once.
588 /// More details may be exposed in the future.
589 #[derive(Default)]
590 pub struct Errors {
591     punycode: bool,
592     check_hyphens: bool,
593     check_bidi: bool,
594     start_combining_mark: bool,
595     invalid_mapping: bool,
596     nfc: bool,
597     disallowed_by_std3_ascii_rules: bool,
598     disallowed_mapped_in_std3: bool,
599     disallowed_character: bool,
600     too_long_for_dns: bool,
601     too_short_for_dns: bool,
602     disallowed_in_idna_2008: bool,
603 }
604 
605 impl Errors {
is_err(&self) -> bool606     fn is_err(&self) -> bool {
607         let Errors {
608             punycode,
609             check_hyphens,
610             check_bidi,
611             start_combining_mark,
612             invalid_mapping,
613             nfc,
614             disallowed_by_std3_ascii_rules,
615             disallowed_mapped_in_std3,
616             disallowed_character,
617             too_long_for_dns,
618             too_short_for_dns,
619             disallowed_in_idna_2008,
620         } = *self;
621         punycode
622             || check_hyphens
623             || check_bidi
624             || start_combining_mark
625             || invalid_mapping
626             || nfc
627             || disallowed_by_std3_ascii_rules
628             || disallowed_mapped_in_std3
629             || disallowed_character
630             || too_long_for_dns
631             || too_short_for_dns
632             || disallowed_in_idna_2008
633     }
634 }
635 
636 impl fmt::Debug for Errors {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result637     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638         let Errors {
639             punycode,
640             check_hyphens,
641             check_bidi,
642             start_combining_mark,
643             invalid_mapping,
644             nfc,
645             disallowed_by_std3_ascii_rules,
646             disallowed_mapped_in_std3,
647             disallowed_character,
648             too_long_for_dns,
649             too_short_for_dns,
650             disallowed_in_idna_2008,
651         } = *self;
652 
653         let fields = [
654             ("punycode", punycode),
655             ("check_hyphens", check_hyphens),
656             ("check_bidi", check_bidi),
657             ("start_combining_mark", start_combining_mark),
658             ("invalid_mapping", invalid_mapping),
659             ("nfc", nfc),
660             (
661                 "disallowed_by_std3_ascii_rules",
662                 disallowed_by_std3_ascii_rules,
663             ),
664             ("disallowed_mapped_in_std3", disallowed_mapped_in_std3),
665             ("disallowed_character", disallowed_character),
666             ("too_long_for_dns", too_long_for_dns),
667             ("too_short_for_dns", too_short_for_dns),
668             ("disallowed_in_idna_2008", disallowed_in_idna_2008),
669         ];
670 
671         let mut empty = true;
672         f.write_str("Errors { ")?;
673         for (name, val) in &fields {
674             if *val {
675                 if !empty {
676                     f.write_str(", ")?;
677                 }
678                 f.write_str(*name)?;
679                 empty = false;
680             }
681         }
682 
683         if !empty {
684             f.write_str(" }")
685         } else {
686             f.write_str("}")
687         }
688     }
689 }
690 
691 impl From<Errors> for Result<(), Errors> {
from(e: Errors) -> Result<(), Errors>692     fn from(e: Errors) -> Result<(), Errors> {
693         if !e.is_err() {
694             Ok(())
695         } else {
696             Err(e)
697         }
698     }
699 }
700 
701 impl StdError for Errors {}
702 
703 impl fmt::Display for Errors {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result704     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705         fmt::Debug::fmt(self, f)
706     }
707 }
708 
709 #[cfg(test)]
710 mod tests {
711     use super::{find_char, Mapping};
712 
713     #[test]
mapping_fast_path()714     fn mapping_fast_path() {
715         assert_matches!(find_char('-'), &Mapping::Valid);
716         assert_matches!(find_char('.'), &Mapping::Valid);
717         for c in &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] {
718             assert_matches!(find_char(*c), &Mapping::Valid);
719         }
720         for c in &[
721             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
722             'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
723         ] {
724             assert_matches!(find_char(*c), &Mapping::Valid);
725         }
726     }
727 }
728