uts46.rs 10 KB

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