uts46.rs 10 KB

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