uts46.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. //! [*Unicode IDNA Compatibility Processing*
  9. //! (Unicode Technical Standard #46)](http://www.unicode.org/reports/tr46/)
  10. use self::Mapping::*;
  11. use punycode;
  12. use std::ascii::AsciiExt;
  13. use std::cmp::Ordering::{Equal, Less, Greater};
  14. use unicode_normalization::UnicodeNormalization;
  15. use unicode_normalization::char::is_combining_mark;
  16. use unicode_bidi::{BidiClass, bidi_class};
  17. include!("uts46_mapping_table.rs");
  18. #[derive(Debug)]
  19. struct StringTableSlice {
  20. // Store these as separate fields so the structure will have an
  21. // alignment of 1 and thus pack better into the Mapping enum, below.
  22. byte_start_lo: u8,
  23. byte_start_hi: u8,
  24. byte_len: u8,
  25. }
  26. fn decode_slice(slice: &StringTableSlice) -> &'static str {
  27. let lo = slice.byte_start_lo as usize;
  28. let hi = slice.byte_start_hi as usize;
  29. let start = (hi << 8) | lo;
  30. let len = slice.byte_len as usize;
  31. &STRING_TABLE[start..(start + len)]
  32. }
  33. #[repr(u8)]
  34. #[derive(Debug)]
  35. enum Mapping {
  36. Valid,
  37. Ignored,
  38. Mapped(StringTableSlice),
  39. Deviation(StringTableSlice),
  40. Disallowed,
  41. DisallowedStd3Valid,
  42. DisallowedStd3Mapped(StringTableSlice),
  43. }
  44. struct Range {
  45. from: char,
  46. to: char,
  47. mapping: Mapping,
  48. }
  49. fn find_char(codepoint: char) -> &'static Mapping {
  50. let r = TABLE.binary_search_by(|ref range| {
  51. if codepoint > range.to {
  52. Less
  53. } else if codepoint < range.from {
  54. Greater
  55. } else {
  56. Equal
  57. }
  58. });
  59. r.ok().map(|i| &TABLE[i].mapping).unwrap()
  60. }
  61. fn map_char(codepoint: char, flags: Flags, output: &mut String, errors: &mut Vec<Error>) {
  62. match *find_char(codepoint) {
  63. Mapping::Valid => output.push(codepoint),
  64. Mapping::Ignored => {},
  65. Mapping::Mapped(ref slice) => output.push_str(decode_slice(slice)),
  66. Mapping::Deviation(ref slice) => {
  67. if flags.transitional_processing {
  68. output.push_str(decode_slice(slice))
  69. } else {
  70. output.push(codepoint)
  71. }
  72. }
  73. Mapping::Disallowed => {
  74. errors.push(Error::DissallowedCharacter);
  75. output.push(codepoint);
  76. }
  77. Mapping::DisallowedStd3Valid => {
  78. if flags.use_std3_ascii_rules {
  79. errors.push(Error::DissallowedByStd3AsciiRules);
  80. }
  81. output.push(codepoint)
  82. }
  83. Mapping::DisallowedStd3Mapped(ref slice) => {
  84. if flags.use_std3_ascii_rules {
  85. errors.push(Error::DissallowedMappedInStd3);
  86. }
  87. output.push_str(decode_slice(slice))
  88. }
  89. }
  90. }
  91. // http://tools.ietf.org/html/rfc5893#section-2
  92. fn passes_bidi(label: &str, transitional_processing: bool) -> bool {
  93. let mut chars = label.chars();
  94. let class = match chars.next() {
  95. Some(c) => bidi_class(c),
  96. None => return true, // empty string
  97. };
  98. if class == BidiClass::L
  99. || (class == BidiClass::ON && transitional_processing) // starts with \u200D
  100. || (class == BidiClass::ES && transitional_processing) // hack: 1.35.+33.49
  101. || class == BidiClass::EN // hack: starts with number 0à.\u05D0
  102. { // LTR
  103. // Rule 5
  104. loop {
  105. match chars.next() {
  106. Some(c) => {
  107. let c = bidi_class(c);
  108. if !matches!(c, BidiClass::L | BidiClass::EN |
  109. BidiClass::ES | BidiClass::CS |
  110. BidiClass::ET | BidiClass::ON |
  111. BidiClass::BN | BidiClass::NSM) {
  112. return false;
  113. }
  114. },
  115. None => { break; },
  116. }
  117. }
  118. // Rule 6
  119. let mut rev_chars = label.chars().rev();
  120. let mut last = rev_chars.next();
  121. loop { // must end in L or EN followed by 0 or more NSM
  122. match last {
  123. Some(c) if bidi_class(c) == BidiClass::NSM => {
  124. last = rev_chars.next();
  125. continue;
  126. }
  127. _ => { break; },
  128. }
  129. }
  130. // TODO: does not pass for àˇ.\u05D0
  131. // match last {
  132. // Some(c) if bidi_class(c) == BidiClass::L
  133. // || bidi_class(c) == BidiClass::EN => {},
  134. // Some(c) => { return false; },
  135. // _ => {}
  136. // }
  137. } else if class == BidiClass::R || class == BidiClass::AL { // RTL
  138. let mut found_en = false;
  139. let mut found_an = false;
  140. // Rule 2
  141. loop {
  142. match chars.next() {
  143. Some(c) => {
  144. let char_class = bidi_class(c);
  145. if char_class == BidiClass::EN {
  146. found_en = true;
  147. }
  148. if char_class == BidiClass::AN {
  149. found_an = true;
  150. }
  151. if !matches!(char_class, BidiClass::R | BidiClass::AL |
  152. BidiClass::AN | BidiClass::EN |
  153. BidiClass::ES | BidiClass::CS |
  154. BidiClass::ET | BidiClass::ON |
  155. BidiClass::BN | BidiClass::NSM) {
  156. return false;
  157. }
  158. },
  159. None => { break; },
  160. }
  161. }
  162. // Rule 3
  163. let mut rev_chars = label.chars().rev();
  164. let mut last = rev_chars.next();
  165. loop { // must end in L or EN followed by 0 or more NSM
  166. match last {
  167. Some(c) if bidi_class(c) == BidiClass::NSM => {
  168. last = rev_chars.next();
  169. continue;
  170. }
  171. _ => { break; },
  172. }
  173. }
  174. match last {
  175. Some(c) if matches!(bidi_class(c), BidiClass::R | BidiClass::AL |
  176. BidiClass::EN | BidiClass::AN) => {},
  177. _ => { return false; }
  178. }
  179. // Rule 4
  180. if found_an && found_en {
  181. return false;
  182. }
  183. } else {
  184. // Rule 2: Should start with L or R/AL
  185. return false;
  186. }
  187. return true;
  188. }
  189. /// http://www.unicode.org/reports/tr46/#Validity_Criteria
  190. fn validate(label: &str, flags: Flags, errors: &mut Vec<Error>) {
  191. if label.nfc().ne(label.chars()) {
  192. errors.push(Error::ValidityCriteria);
  193. }
  194. // Can not contain '.' since the input is from .split('.')
  195. // Spec says that the label must not contain a HYPHEN-MINUS character in both the
  196. // third and fourth positions. But nobody follows this criteria. See the spec issue below:
  197. // https://github.com/whatwg/url/issues/53
  198. if label.starts_with("-")
  199. || label.ends_with("-")
  200. || label.chars().next().map_or(false, is_combining_mark)
  201. || label.chars().any(|c| match *find_char(c) {
  202. Mapping::Valid => false,
  203. Mapping::Deviation(_) => flags.transitional_processing,
  204. Mapping::DisallowedStd3Valid => flags.use_std3_ascii_rules,
  205. _ => true,
  206. })
  207. || !passes_bidi(label, flags.transitional_processing)
  208. {
  209. errors.push(Error::ValidityCriteria)
  210. }
  211. }
  212. /// http://www.unicode.org/reports/tr46/#Processing
  213. fn processing(domain: &str, flags: Flags, errors: &mut Vec<Error>) -> String {
  214. let mut mapped = String::new();
  215. for c in domain.chars() {
  216. map_char(c, flags, &mut mapped, errors)
  217. }
  218. let normalized: String = mapped.nfc().collect();
  219. let mut validated = String::new();
  220. for label in normalized.split('.') {
  221. if validated.len() > 0 {
  222. validated.push('.');
  223. }
  224. if label.starts_with("xn--") {
  225. match punycode::decode_to_string(&label["xn--".len()..]) {
  226. Some(decoded_label) => {
  227. let flags = Flags { transitional_processing: false, ..flags };
  228. validate(&decoded_label, flags, errors);
  229. validated.push_str(&decoded_label)
  230. }
  231. None => errors.push(Error::PunycodeError)
  232. }
  233. } else {
  234. validate(label, flags, errors);
  235. validated.push_str(label)
  236. }
  237. }
  238. validated
  239. }
  240. #[derive(Copy, Clone)]
  241. pub struct Flags {
  242. pub use_std3_ascii_rules: bool,
  243. pub transitional_processing: bool,
  244. pub verify_dns_length: bool,
  245. }
  246. #[derive(PartialEq, Eq, Clone, Copy, Debug)]
  247. enum Error {
  248. PunycodeError,
  249. ValidityCriteria,
  250. DissallowedByStd3AsciiRules,
  251. DissallowedMappedInStd3,
  252. DissallowedCharacter,
  253. TooLongForDns,
  254. }
  255. /// Errors recorded during UTS #46 processing.
  256. ///
  257. /// This is opaque for now, only indicating the presence of at least one error.
  258. /// More details may be exposed in the future.
  259. #[derive(Debug)]
  260. pub struct Errors(Vec<Error>);
  261. /// http://www.unicode.org/reports/tr46/#ToASCII
  262. pub fn to_ascii(domain: &str, flags: Flags) -> Result<String, Errors> {
  263. let mut errors = Vec::new();
  264. let mut result = String::new();
  265. for label in processing(domain, flags, &mut errors).split('.') {
  266. if result.len() > 0 {
  267. result.push('.');
  268. }
  269. if label.is_ascii() {
  270. result.push_str(label);
  271. } else {
  272. match punycode::encode_str(label) {
  273. Some(x) => {
  274. result.push_str("xn--");
  275. result.push_str(&x);
  276. },
  277. None => errors.push(Error::PunycodeError)
  278. }
  279. }
  280. }
  281. if flags.verify_dns_length {
  282. let domain = if result.ends_with(".") { &result[..result.len()-1] } else { &*result };
  283. if domain.len() < 1 || domain.len() > 253 ||
  284. domain.split('.').any(|label| label.len() < 1 || label.len() > 63) {
  285. errors.push(Error::TooLongForDns)
  286. }
  287. }
  288. if errors.is_empty() {
  289. Ok(result)
  290. } else {
  291. Err(Errors(errors))
  292. }
  293. }
  294. /// http://www.unicode.org/reports/tr46/#ToUnicode
  295. ///
  296. /// Only `use_std3_ascii_rules` is used in `flags`.
  297. pub fn to_unicode(domain: &str, mut flags: Flags) -> (String, Result<(), Errors>) {
  298. flags.transitional_processing = false;
  299. let mut errors = Vec::new();
  300. let domain = processing(domain, flags, &mut errors);
  301. let errors = if errors.is_empty() {
  302. Ok(())
  303. } else {
  304. Err(Errors(errors))
  305. };
  306. (domain, errors)
  307. }