uts46.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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_bidi::{BidiClass, bidi_class};
  15. use unicode_normalization::UnicodeNormalization;
  16. use unicode_normalization::char::is_combining_mark;
  17. include!("uts46_mapping_table.rs");
  18. pub static PUNYCODE_PREFIX: &'static str = "xn--";
  19. #[derive(Debug)]
  20. struct StringTableSlice {
  21. // Store these as separate fields so the structure will have an
  22. // alignment of 1 and thus pack better into the Mapping enum, below.
  23. byte_start_lo: u8,
  24. byte_start_hi: u8,
  25. byte_len: u8,
  26. }
  27. fn decode_slice(slice: &StringTableSlice) -> &'static str {
  28. let lo = slice.byte_start_lo as usize;
  29. let hi = slice.byte_start_hi as usize;
  30. let start = (hi << 8) | lo;
  31. let len = slice.byte_len as usize;
  32. &STRING_TABLE[start..(start + len)]
  33. }
  34. #[repr(u8)]
  35. #[derive(Debug)]
  36. enum Mapping {
  37. Valid,
  38. Ignored,
  39. Mapped(StringTableSlice),
  40. Deviation(StringTableSlice),
  41. Disallowed,
  42. DisallowedStd3Valid,
  43. DisallowedStd3Mapped(StringTableSlice),
  44. }
  45. struct Range {
  46. from: char,
  47. to: char,
  48. mapping: Mapping,
  49. }
  50. fn find_char(codepoint: char) -> &'static Mapping {
  51. let r = TABLE.binary_search_by(|ref range| {
  52. if codepoint > range.to {
  53. Less
  54. } else if codepoint < range.from {
  55. Greater
  56. } else {
  57. Equal
  58. }
  59. });
  60. r.ok().map(|i| &TABLE[i].mapping).unwrap()
  61. }
  62. fn map_char(codepoint: char, flags: Flags, output: &mut String, errors: &mut Vec<Error>) {
  63. match *find_char(codepoint) {
  64. Mapping::Valid => output.push(codepoint),
  65. Mapping::Ignored => {},
  66. Mapping::Mapped(ref slice) => output.push_str(decode_slice(slice)),
  67. Mapping::Deviation(ref slice) => {
  68. if flags.transitional_processing {
  69. output.push_str(decode_slice(slice))
  70. } else {
  71. output.push(codepoint)
  72. }
  73. }
  74. Mapping::Disallowed => {
  75. errors.push(Error::DissallowedCharacter);
  76. output.push(codepoint);
  77. }
  78. Mapping::DisallowedStd3Valid => {
  79. if flags.use_std3_ascii_rules {
  80. errors.push(Error::DissallowedByStd3AsciiRules);
  81. }
  82. output.push(codepoint)
  83. }
  84. Mapping::DisallowedStd3Mapped(ref slice) => {
  85. if flags.use_std3_ascii_rules {
  86. errors.push(Error::DissallowedMappedInStd3);
  87. }
  88. output.push_str(decode_slice(slice))
  89. }
  90. }
  91. }
  92. // http://tools.ietf.org/html/rfc5893#section-2
  93. fn passes_bidi(label: &str, is_bidi_domain: bool) -> bool {
  94. // Rule 0: Bidi Rules apply to Bidi Domain Names: a name with at least one RTL label. A label
  95. // is RTL if it contains at least one character of bidi class R, AL or AN.
  96. if !is_bidi_domain {
  97. return true;
  98. }
  99. let mut chars = label.chars();
  100. let first_char_class = match chars.next() {
  101. Some(c) => bidi_class(c),
  102. None => return true, // empty string
  103. };
  104. match first_char_class {
  105. // LTR label
  106. BidiClass::L => {
  107. // Rule 5
  108. loop {
  109. match chars.next() {
  110. Some(c) => {
  111. if !matches!(bidi_class(c),
  112. BidiClass::L | BidiClass::EN |
  113. BidiClass::ES | BidiClass::CS |
  114. BidiClass::ET | BidiClass::ON |
  115. BidiClass::BN | BidiClass::NSM
  116. ) {
  117. return false;
  118. }
  119. },
  120. None => { break; },
  121. }
  122. }
  123. // Rule 6
  124. // must end in L or EN followed by 0 or more NSM
  125. let mut rev_chars = label.chars().rev();
  126. let mut last_non_nsm = rev_chars.next();
  127. loop {
  128. match last_non_nsm {
  129. Some(c) if bidi_class(c) == BidiClass::NSM => {
  130. last_non_nsm = rev_chars.next();
  131. continue;
  132. }
  133. _ => { break; },
  134. }
  135. }
  136. match last_non_nsm {
  137. Some(c) if bidi_class(c) == BidiClass::L
  138. || bidi_class(c) == BidiClass::EN => {},
  139. Some(_) => { return false; },
  140. _ => {}
  141. }
  142. }
  143. // RTL label
  144. BidiClass::R | BidiClass::AL => {
  145. let mut found_en = false;
  146. let mut found_an = false;
  147. // Rule 2
  148. loop {
  149. match chars.next() {
  150. Some(c) => {
  151. let char_class = bidi_class(c);
  152. if char_class == BidiClass::EN {
  153. found_en = true;
  154. }
  155. if char_class == BidiClass::AN {
  156. found_an = true;
  157. }
  158. if !matches!(char_class, BidiClass::R | BidiClass::AL |
  159. BidiClass::AN | BidiClass::EN |
  160. BidiClass::ES | BidiClass::CS |
  161. BidiClass::ET | BidiClass::ON |
  162. BidiClass::BN | BidiClass::NSM) {
  163. return false;
  164. }
  165. },
  166. None => { break; },
  167. }
  168. }
  169. // Rule 3
  170. let mut rev_chars = label.chars().rev();
  171. let mut last = rev_chars.next();
  172. loop { // must end in L or EN followed by 0 or more NSM
  173. match last {
  174. Some(c) if bidi_class(c) == BidiClass::NSM => {
  175. last = rev_chars.next();
  176. continue;
  177. }
  178. _ => { break; },
  179. }
  180. }
  181. match last {
  182. Some(c) if matches!(bidi_class(c), BidiClass::R | BidiClass::AL |
  183. BidiClass::EN | BidiClass::AN) => {},
  184. _ => { return false; }
  185. }
  186. // Rule 4
  187. if found_an && found_en {
  188. return false;
  189. }
  190. }
  191. // Rule 1: Should start with L or R/AL
  192. _ => {
  193. return false;
  194. }
  195. }
  196. return true;
  197. }
  198. /// http://www.unicode.org/reports/tr46/#Validity_Criteria
  199. fn validate(label: &str, is_bidi_domain: bool, flags: Flags, errors: &mut Vec<Error>) {
  200. let first_char = label.chars().next();
  201. if first_char == None {
  202. // Empty string, pass
  203. }
  204. // V1: Must be in NFC form.
  205. else if label.nfc().ne(label.chars()) {
  206. errors.push(Error::ValidityCriteria);
  207. }
  208. // V2: No U+002D HYPHEN-MINUS in both third and fourth positions.
  209. //
  210. // NOTE: Spec says that the label must not contain a HYPHEN-MINUS character in both the
  211. // third and fourth positions. But nobody follows this criteria. See the spec issue below:
  212. // https://github.com/whatwg/url/issues/53
  213. //
  214. // TODO: Add *CheckHyphens* flag.
  215. // V3: neither begin nor end with a U+002D HYPHEN-MINUS
  216. else if label.starts_with("-") || label.ends_with("-") {
  217. errors.push(Error::ValidityCriteria);
  218. }
  219. // V4: not contain a U+002E FULL STOP
  220. //
  221. // Here, label can't contain '.' since the input is from .split('.')
  222. // V5: not begin with a GC=Mark
  223. else if is_combining_mark(first_char.unwrap()) {
  224. errors.push(Error::ValidityCriteria);
  225. }
  226. // V6: Check against Mapping Table
  227. else if label.chars().any(|c| match *find_char(c) {
  228. Mapping::Valid => false,
  229. Mapping::Deviation(_) => flags.transitional_processing,
  230. Mapping::DisallowedStd3Valid => flags.use_std3_ascii_rules,
  231. _ => true,
  232. }) {
  233. errors.push(Error::ValidityCriteria);
  234. }
  235. // V7: ContextJ rules
  236. //
  237. // TODO: Implement rules and add *CheckJoiners* flag.
  238. // V8: Bidi rules
  239. //
  240. // TODO: Add *CheckBidi* flag
  241. else if !passes_bidi(label, is_bidi_domain)
  242. {
  243. errors.push(Error::ValidityCriteria);
  244. }
  245. }
  246. /// http://www.unicode.org/reports/tr46/#Processing
  247. fn processing(domain: &str, flags: Flags, errors: &mut Vec<Error>) -> String {
  248. let mut mapped = String::new();
  249. for c in domain.chars() {
  250. map_char(c, flags, &mut mapped, errors)
  251. }
  252. let normalized: String = mapped.nfc().collect();
  253. // Find out if it's a Bidi Domain Name
  254. //
  255. // First, check for literal bidi chars
  256. let mut is_bidi_domain = domain.chars().any(|c|
  257. matches!(bidi_class(c), BidiClass::R | BidiClass::AL | BidiClass::AN)
  258. );
  259. if !is_bidi_domain {
  260. // Then check for punycode-encoded bidi chars
  261. for label in normalized.split('.') {
  262. if label.starts_with(PUNYCODE_PREFIX) {
  263. match punycode::decode_to_string(&label[PUNYCODE_PREFIX.len()..]) {
  264. Some(decoded_label) => {
  265. if decoded_label.chars().any(|c|
  266. matches!(bidi_class(c), BidiClass::R | BidiClass::AL | BidiClass::AN)
  267. ) {
  268. is_bidi_domain = true;
  269. }
  270. }
  271. None => {
  272. is_bidi_domain = true;
  273. }
  274. }
  275. }
  276. }
  277. }
  278. let mut validated = String::new();
  279. let mut first = true;
  280. for label in normalized.split('.') {
  281. if !first {
  282. validated.push('.');
  283. }
  284. first = false;
  285. if label.starts_with(PUNYCODE_PREFIX) {
  286. match punycode::decode_to_string(&label[PUNYCODE_PREFIX.len()..]) {
  287. Some(decoded_label) => {
  288. let flags = Flags { transitional_processing: false, ..flags };
  289. validate(&decoded_label, is_bidi_domain, flags, errors);
  290. validated.push_str(&decoded_label)
  291. }
  292. None => errors.push(Error::PunycodeError)
  293. }
  294. } else {
  295. validate(label, is_bidi_domain, flags, errors);
  296. validated.push_str(label)
  297. }
  298. }
  299. validated
  300. }
  301. #[derive(Copy, Clone)]
  302. pub struct Flags {
  303. pub use_std3_ascii_rules: bool,
  304. pub transitional_processing: bool,
  305. pub verify_dns_length: bool,
  306. }
  307. #[derive(PartialEq, Eq, Clone, Copy, Debug)]
  308. enum Error {
  309. PunycodeError,
  310. ValidityCriteria,
  311. DissallowedByStd3AsciiRules,
  312. DissallowedMappedInStd3,
  313. DissallowedCharacter,
  314. TooLongForDns,
  315. TooShortForDns,
  316. }
  317. /// Errors recorded during UTS #46 processing.
  318. ///
  319. /// This is opaque for now, only indicating the presence of at least one error.
  320. /// More details may be exposed in the future.
  321. #[derive(Debug)]
  322. pub struct Errors(Vec<Error>);
  323. /// http://www.unicode.org/reports/tr46/#ToASCII
  324. pub fn to_ascii(domain: &str, flags: Flags) -> Result<String, Errors> {
  325. let mut errors = Vec::new();
  326. let mut result = String::new();
  327. let mut first = true;
  328. for label in processing(domain, flags, &mut errors).split('.') {
  329. if !first {
  330. result.push('.');
  331. }
  332. first = false;
  333. if label.is_ascii() {
  334. result.push_str(label);
  335. } else {
  336. match punycode::encode_str(label) {
  337. Some(x) => {
  338. result.push_str(PUNYCODE_PREFIX);
  339. result.push_str(&x);
  340. },
  341. None => errors.push(Error::PunycodeError)
  342. }
  343. }
  344. }
  345. if flags.verify_dns_length {
  346. let domain = if result.ends_with(".") { &result[..result.len()-1] } else { &*result };
  347. if domain.len() < 1 || domain.split('.').any(|label| label.len() < 1) {
  348. errors.push(Error::TooShortForDns)
  349. }
  350. if domain.len() > 253 || domain.split('.').any(|label| label.len() > 63) {
  351. errors.push(Error::TooLongForDns)
  352. }
  353. }
  354. if errors.is_empty() {
  355. Ok(result)
  356. } else {
  357. Err(Errors(errors))
  358. }
  359. }
  360. /// http://www.unicode.org/reports/tr46/#ToUnicode
  361. ///
  362. /// Only `use_std3_ascii_rules` is used in `flags`.
  363. pub fn to_unicode(domain: &str, mut flags: Flags) -> (String, Result<(), Errors>) {
  364. flags.transitional_processing = false;
  365. let mut errors = Vec::new();
  366. let domain = processing(domain, flags, &mut errors);
  367. let errors = if errors.is_empty() {
  368. Ok(())
  369. } else {
  370. Err(Errors(errors))
  371. };
  372. (domain, errors)
  373. }