idna.rs 10.0 KB

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