uts46.rs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  1. // Copyright 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. //! This module provides the lower-level API for UTS 46.
  9. //!
  10. //! [`Uts46::process`] is the core that the other convenience
  11. //! methods build on.
  12. //!
  13. //! UTS 46 flags map to this API as follows:
  14. //!
  15. //! * _CheckHyphens_ - _true_: [`Hyphens::Check`], _false_: [`Hyphens::Allow`]; the WHATWG URL Standard sets this to _false_ for normal (non-conformance-checker) user agents.
  16. //! * _CheckBidi_ - Always _true_; cannot be configured, since this flag is _true_ even when WHATWG URL Standard _beStrict_ is _false_.
  17. //! * _CheckJoiners_ - Always _true_; cannot be configured, since this flag is _true_ even when WHATWG URL Standard _beStrict_ is _false_.
  18. //! * _UseSTD3ASCIIRules_ - _true_: [`AsciiDenyList::STD3`], _false_: [`AsciiDenyList::EMPTY`]; however, the check the WHATWG URL Standard performs right after the UTS 46 invocation corresponds to [`AsciiDenyList::URL`].
  19. //! * _Transitional_Processing_ - Always _false_ but could be implemented as a preprocessing step. This flag is deprecated and for Web purposes the transition is over in the sense that all of Firefox, Safari, or Chrome set this flag to _false_.
  20. //! * _VerifyDnsLength_ - _true_: [`DnsLength::Verify`], _false_: [`DnsLength::Ignore`]; the WHATWG URL Standard sets this to _false_ for normal (non-conformance-checker) user agents.
  21. //! * _IgnoreInvalidPunycode_ - Always _false_; cannot be configured. (Not yet covered by the WHATWG URL Standard, but 2 out of 3 major browser clearly behave as if this was _false_).
  22. use crate::punycode::Decoder;
  23. use crate::punycode::InternalCaller;
  24. use alloc::borrow::Cow;
  25. use alloc::string::String;
  26. use core::fmt::Write;
  27. use idna_adapter::*;
  28. use smallvec::SmallVec;
  29. use utf8_iter::Utf8CharsEx;
  30. /// ICU4C-compatible constraint.
  31. /// https://unicode-org.atlassian.net/browse/ICU-13727
  32. const PUNYCODE_DECODE_MAX_INPUT_LENGTH: usize = 2000;
  33. /// ICU4C-compatible constraint. (Note: ICU4C measures
  34. /// UTF-16 and we measure UTF-32. This means that we
  35. /// allow longer non-BMP inputs. For this implementation,
  36. /// the denial-of-service scaling does not depend on BMP vs.
  37. /// non-BMP: only the scalar values matter.)
  38. ///
  39. /// https://unicode-org.atlassian.net/browse/ICU-13727
  40. const PUNYCODE_ENCODE_MAX_INPUT_LENGTH: usize = 1000;
  41. /// For keeping track of what kind of numerals have been
  42. /// seen in an RTL label.
  43. #[derive(Debug, PartialEq, Eq)]
  44. enum RtlNumeralState {
  45. Undecided,
  46. European,
  47. Arabic,
  48. }
  49. /// Computes the mask for upper-case ASCII.
  50. const fn upper_case_mask() -> u128 {
  51. let mut accu = 0u128;
  52. let mut b = 0u8;
  53. while b < 128 {
  54. if (b >= b'A') && (b <= b'Z') {
  55. accu |= 1u128 << b;
  56. }
  57. b += 1;
  58. }
  59. accu
  60. }
  61. /// Bit set for upper-case ASCII.
  62. const UPPER_CASE_MASK: u128 = upper_case_mask();
  63. /// Computes the mask for glyphless ASCII.
  64. const fn glyphless_mask() -> u128 {
  65. let mut accu = 0u128;
  66. let mut b = 0u8;
  67. while b < 128 {
  68. if (b <= b' ') || (b == 0x7F) {
  69. accu |= 1u128 << b;
  70. }
  71. b += 1;
  72. }
  73. accu
  74. }
  75. /// Bit set for glyphless ASCII.
  76. const GLYPHLESS_MASK: u128 = glyphless_mask();
  77. /// The mask for the ASCII dot.
  78. const DOT_MASK: u128 = 1 << b'.';
  79. /// Computes the ASCII deny list for STD3 ASCII rules.
  80. const fn ldh_mask() -> u128 {
  81. let mut accu = 0u128;
  82. let mut b = 0u8;
  83. while b < 128 {
  84. if !((b >= b'a' && b <= b'z') || (b >= b'0' && b <= b'9') || b == b'-' || b == b'.') {
  85. accu |= 1u128 << b;
  86. }
  87. b += 1;
  88. }
  89. accu
  90. }
  91. const PUNYCODE_PREFIX: u32 =
  92. ((b'-' as u32) << 24) | ((b'-' as u32) << 16) | ((b'N' as u32) << 8) | b'X' as u32;
  93. const PUNYCODE_PREFIX_MASK: u32 = (0xFF << 24) | (0xFF << 16) | (0xDF << 8) | 0xDF;
  94. fn write_punycode_label<W: Write + ?Sized>(
  95. label: &[char],
  96. sink: &mut W,
  97. ) -> Result<(), ProcessingError> {
  98. sink.write_str("xn--")?;
  99. crate::punycode::encode_into::<_, _, InternalCaller>(label.iter().copied(), sink)?;
  100. Ok(())
  101. }
  102. #[inline(always)]
  103. fn has_punycode_prefix(slice: &[u8]) -> bool {
  104. if slice.len() < 4 {
  105. return false;
  106. }
  107. // Sadly, the optimizer doesn't figure out that more idiomatic code
  108. // should compile to masking on 32-bit value.
  109. let a = slice[0];
  110. let b = slice[1];
  111. let c = slice[2];
  112. let d = slice[3];
  113. let u = (u32::from(d) << 24) | (u32::from(c) << 16) | (u32::from(b) << 8) | u32::from(a);
  114. (u & PUNYCODE_PREFIX_MASK) == PUNYCODE_PREFIX
  115. }
  116. #[inline(always)]
  117. fn in_inclusive_range8(u: u8, start: u8, end: u8) -> bool {
  118. u.wrapping_sub(start) <= (end - start)
  119. }
  120. #[inline(always)]
  121. fn in_inclusive_range_char(c: char, start: char, end: char) -> bool {
  122. u32::from(c).wrapping_sub(u32::from(start)) <= (u32::from(end) - u32::from(start))
  123. }
  124. #[inline(always)]
  125. fn is_passthrough_ascii_label(label: &[u8]) -> bool {
  126. // XXX if we aren't performing _CheckHyphens_, this could
  127. // check for "xn--" and pass through YouTube CDN node names.
  128. if label.len() >= 4 && label[2] == b'-' && label[3] == b'-' {
  129. return false;
  130. }
  131. if let Some((&first, tail)) = label.split_first() {
  132. // We need to check the first and last character
  133. // more strictly in case this turns out to be a
  134. // label in a bidi domain name. This has the side
  135. // effect that this function only accepts labels
  136. // that also conform to the STD3 rules.
  137. //
  138. // XXX: If we are in the fail-fast mode (i.e. we don't need
  139. // to be able to overwrite anything with U+FFFD), we could
  140. // merely record that we've seen a digit here and error out
  141. // if we later discover that the domain name is a bidi
  142. // domain name.
  143. if !in_inclusive_range8(first, b'a', b'z') {
  144. return false;
  145. }
  146. for &b in tail {
  147. // If we used LDH_MASK, we'd have to check
  148. // the bytes for the ASCII range anyhow.
  149. if in_inclusive_range8(b, b'a', b'z') {
  150. continue;
  151. }
  152. if in_inclusive_range8(b, b'0', b'9') {
  153. continue;
  154. }
  155. if b == b'-' {
  156. continue;
  157. }
  158. return false;
  159. }
  160. label.last() != Some(&b'-')
  161. } else {
  162. // empty
  163. true
  164. }
  165. }
  166. #[inline(always)]
  167. fn split_ascii_fast_path_prefix(label: &[u8]) -> (&[u8], &[u8]) {
  168. if let Some(pos) = label.iter().position(|b| !b.is_ascii()) {
  169. if pos == 0 {
  170. // First is non-ASCII
  171. (&[], label)
  172. } else {
  173. // Leave one ASCII character in the suffix
  174. // in case it's a letter that a combining
  175. // character combines with.
  176. let (head, tail) = label.split_at(pos - 1);
  177. (head, tail)
  178. }
  179. } else {
  180. // All ASCII
  181. (label, &[])
  182. }
  183. }
  184. // Input known to be lower-case, but may contain non-ASCII.
  185. #[inline(always)]
  186. fn apply_ascii_deny_list_to_lower_cased_unicode(c: char, deny_list: u128) -> char {
  187. if let Some(shifted) = 1u128.checked_shl(u32::from(c)) {
  188. if (deny_list & shifted) == 0 {
  189. c
  190. } else {
  191. '\u{FFFD}'
  192. }
  193. } else {
  194. c
  195. }
  196. }
  197. // Input known to be ASCII, but may contain upper case ASCII.
  198. #[inline(always)]
  199. fn apply_ascii_deny_list_to_potentially_upper_case_ascii(b: u8, deny_list: u128) -> char {
  200. if (deny_list & (1u128 << b)) == 0 {
  201. return char::from(b);
  202. }
  203. if in_inclusive_range8(b, b'A', b'Z') {
  204. return char::from(b + 0x20);
  205. }
  206. '\u{FFFD}'
  207. }
  208. #[inline(always)]
  209. fn is_ascii(label: &[char]) -> bool {
  210. for c in label.iter() {
  211. if !c.is_ascii() {
  212. return false;
  213. }
  214. }
  215. true
  216. }
  217. #[derive(PartialEq, Eq, Copy, Clone)]
  218. enum PunycodeClassification {
  219. Ascii,
  220. Unicode,
  221. Error,
  222. }
  223. #[inline(always)]
  224. fn classify_for_punycode(label: &[char]) -> PunycodeClassification {
  225. let mut iter = label.iter().copied();
  226. loop {
  227. if let Some(c) = iter.next() {
  228. if c.is_ascii() {
  229. continue;
  230. }
  231. if c == '\u{FFFD}' {
  232. return PunycodeClassification::Error;
  233. }
  234. for c in iter {
  235. if c == '\u{FFFD}' {
  236. return PunycodeClassification::Error;
  237. }
  238. }
  239. return PunycodeClassification::Unicode;
  240. }
  241. return PunycodeClassification::Ascii;
  242. }
  243. }
  244. /// The ASCII deny list to be applied.
  245. #[derive(PartialEq, Eq, Copy, Clone)]
  246. #[repr(transparent)]
  247. pub struct AsciiDenyList {
  248. bits: u128,
  249. }
  250. impl AsciiDenyList {
  251. /// Computes (preferably at compile time) an ASCII deny list.
  252. ///
  253. /// Setting `deny_glyphless` to `true` denies U+0020 SPACE and below
  254. /// as well as U+007F DELETE for convenience without having to list
  255. /// these characters in the `deny_list` string.
  256. ///
  257. /// `deny_list` is the list of ASCII characters to deny. This
  258. /// list must not contain any of:
  259. /// * Letters
  260. /// * Digits
  261. /// * Hyphen
  262. /// * Dot (period / full-stop)
  263. /// * Non-ASCII
  264. ///
  265. /// # Panics
  266. ///
  267. /// If the deny list contains characters listed as prohibited above.
  268. pub const fn new(deny_glyphless: bool, deny_list: &str) -> Self {
  269. let mut bits = UPPER_CASE_MASK;
  270. if deny_glyphless {
  271. bits |= GLYPHLESS_MASK;
  272. }
  273. let mut i = 0;
  274. let bytes = deny_list.as_bytes();
  275. while i < bytes.len() {
  276. let b = bytes[i];
  277. assert!(b < 0x80, "ASCII deny list must be ASCII.");
  278. // assert_ne not yet available in const context.
  279. assert!(b != b'.', "ASCII deny list must not contain the dot.");
  280. assert!(b != b'-', "ASCII deny list must not contain the hyphen.");
  281. assert!(
  282. !((b >= b'0') && (b <= b'9')),
  283. "ASCII deny list must not contain digits."
  284. );
  285. assert!(
  286. !((b >= b'a') && (b <= b'z')),
  287. "ASCII deny list must not contain letters."
  288. );
  289. assert!(
  290. !((b >= b'A') && (b <= b'Z')),
  291. "ASCII deny list must not contain letters."
  292. );
  293. bits |= 1u128 << b;
  294. i += 1;
  295. }
  296. AsciiDenyList { bits }
  297. }
  298. /// No ASCII deny list. This corresponds to _UseSTD3ASCIIRules=false_.
  299. ///
  300. /// Equivalent to `AsciiDenyList::new(false, "")`.
  301. ///
  302. /// Note: Not denying the space and control characters can result in
  303. /// strange behavior. Without a deny list provided to the UTS 46
  304. /// operation, the caller is expected perform filtering afterwards,
  305. /// but it's more efficient to use `AsciiDenyList` than post-processing,
  306. /// because the internals of this crate can optimize away checks in
  307. /// certain cases.
  308. pub const EMPTY: AsciiDenyList = AsciiDenyList::new(false, "");
  309. /// The STD3 deny list. This corresponds to _UseSTD3ASCIIRules=true_.
  310. ///
  311. /// Note that this deny list rejects the underscore, which occurs in
  312. /// pseudo-hosts used by various TXT record-based protocols, and also
  313. /// characters that may occurs in non-DNS naming, such as NetBIOS.
  314. pub const STD3: AsciiDenyList = AsciiDenyList { bits: ldh_mask() };
  315. /// [Forbidden domain code point](https://url.spec.whatwg.org/#forbidden-domain-code-point) from the WHATWG URL Standard.
  316. ///
  317. /// Equivalent to `AsciiDenyList::new(true, "%#/:<>?@[\\]^|")`.
  318. ///
  319. /// Note that this deny list rejects IPv6 addresses, so (as in URL
  320. /// parsing) you need to check for IPv6 addresses first and not
  321. /// put them through UTS 46 processing.
  322. pub const URL: AsciiDenyList = AsciiDenyList::new(true, "%#/:<>?@[\\]^|");
  323. }
  324. /// The _CheckHyphens_ mode.
  325. #[derive(PartialEq, Eq, Copy, Clone)]
  326. #[non_exhaustive] // non_exhaustive in case a middle mode that prohibits only first and last position needs to be added
  327. pub enum Hyphens {
  328. /// _CheckHyphens=false_: Do not place positional restrictions on hyphens.
  329. ///
  330. /// This mode is used by the WHATWG URL Standard for normal User Agent processing
  331. /// (i.e. not conformance checking).
  332. Allow,
  333. /// Prohibit hyphens in the first and last position in the label but allow in
  334. /// the third and fourth position.
  335. ///
  336. /// Note that this mode rejects real-world names, including some GitHub user pages.
  337. CheckFirstLast,
  338. /// _CheckHyphens=true_: Prohibit hyphens in the first, third, fourth,
  339. /// and last position in the label.
  340. ///
  341. /// Note that this mode rejects real-world names, including YouTube CDN nodes
  342. /// and some GitHub user pages.
  343. Check,
  344. }
  345. /// The UTS 46 _VerifyDNSLength_ flag.
  346. #[derive(PartialEq, Eq, Copy, Clone)]
  347. #[non_exhaustive]
  348. pub enum DnsLength {
  349. /// _VerifyDNSLength=false_. (Possibly relevant for allowing non-DNS naming systems.)
  350. Ignore,
  351. /// _VerifyDNSLength=true_ with the exception that the trailing root label dot is
  352. /// allowed.
  353. VerifyAllowRootDot,
  354. /// _VerifyDNSLength=true_. (The trailing root label dot is not allowed.)
  355. Verify,
  356. }
  357. /// Policy for customizing behavior in case of an error.
  358. #[derive(PartialEq, Eq, Copy, Clone)]
  359. #[non_exhaustive]
  360. pub enum ErrorPolicy {
  361. /// Return as early as possible without producing output in case of error.
  362. FailFast,
  363. /// In case of error, mark errors with the REPLACEMENT CHARACTER. (The output
  364. /// containing REPLACEMENT CHARACTERs may be show to the user to illustrate
  365. /// what was wrong but must not be used for naming in a network protocol.)
  366. MarkErrors,
  367. }
  368. /// The success outcome of [`Uts46::process`]
  369. #[derive(PartialEq, Eq, Copy, Clone, Debug)]
  370. pub enum ProcessingSuccess {
  371. /// There were no errors. The caller must consider the input to be the output.
  372. ///
  373. /// This asserts that the input can be safely passed to [`core::str::from_utf8_unchecked`].
  374. ///
  375. /// (Distinct from `WroteToSink` in order to allow `Cow` behavior to be implemented on top of
  376. /// [`Uts46::process`].)
  377. Passthrough,
  378. /// There were no errors. The caller must consider what was written to the sink to be the output.
  379. ///
  380. /// (Distinct from `Passthrough` in order to allow `Cow` behavior to be implemented on top of
  381. /// [`Uts46::process`].)
  382. WroteToSink,
  383. }
  384. /// The failure outcome of [`Uts46::process`]
  385. #[derive(PartialEq, Eq, Copy, Clone, Debug)]
  386. pub enum ProcessingError {
  387. /// There was a validity error according to the chosen options.
  388. ///
  389. /// In case of `Operation::ToAscii`, there is no output. Otherwise, output was written to the
  390. /// sink and the output contains at least one U+FFFD REPLACEMENT CHARACTER to denote an error.
  391. ValidityError,
  392. /// The sink emitted [`core::fmt::Error`]. The partial output written to the sink must not
  393. /// be used.
  394. SinkError,
  395. }
  396. impl From<core::fmt::Error> for ProcessingError {
  397. fn from(_: core::fmt::Error) -> Self {
  398. ProcessingError::SinkError
  399. }
  400. }
  401. impl From<crate::punycode::PunycodeEncodeError> for ProcessingError {
  402. fn from(_: crate::punycode::PunycodeEncodeError) -> Self {
  403. unreachable!(
  404. "Punycode overflows should not be possible due to PUNYCODE_ENCODE_MAX_INPUT_LENGTH"
  405. );
  406. }
  407. }
  408. #[derive(Debug, Clone, Copy)]
  409. enum AlreadyAsciiLabel<'a> {
  410. MixedCaseAscii(&'a [u8]),
  411. MixedCasePunycode(&'a [u8]),
  412. Other,
  413. }
  414. /// Performs the _VerifyDNSLength_ check on the output of the _ToASCII_ operation.
  415. ///
  416. /// If the second argument is `false`, the trailing root label dot is allowed.
  417. ///
  418. /// # Panics
  419. ///
  420. /// Panics in debug mode if the argument isn't ASCII.
  421. pub fn verify_dns_length(domain_name: &str, allow_trailing_dot: bool) -> bool {
  422. let bytes = domain_name.as_bytes();
  423. debug_assert!(bytes.is_ascii());
  424. let domain_name_without_trailing_dot = if let Some(without) = bytes.strip_suffix(b".") {
  425. if !allow_trailing_dot {
  426. return false;
  427. }
  428. without
  429. } else {
  430. bytes
  431. };
  432. if domain_name_without_trailing_dot.len() > 253 {
  433. return false;
  434. }
  435. for label in domain_name_without_trailing_dot.split(|b| *b == b'.') {
  436. if label.is_empty() {
  437. return false;
  438. }
  439. if label.len() > 63 {
  440. return false;
  441. }
  442. }
  443. true
  444. }
  445. /// An implementation of UTS #46.
  446. pub struct Uts46 {
  447. data: idna_adapter::Adapter,
  448. }
  449. #[cfg(feature = "compiled_data")]
  450. impl Default for Uts46 {
  451. fn default() -> Self {
  452. Self::new()
  453. }
  454. }
  455. impl Uts46 {
  456. /// Constructor using data compiled into the binary.
  457. #[cfg(feature = "compiled_data")]
  458. pub const fn new() -> Self {
  459. Self {
  460. data: idna_adapter::Adapter::new(),
  461. }
  462. }
  463. // XXX Should there be an `icu_provider` feature for enabling
  464. // a constructor for run-time data loading?
  465. /// Performs the [ToASCII](https://www.unicode.org/reports/tr46/#ToASCII) operation
  466. /// from UTS #46 with the options indicated.
  467. ///
  468. /// # Arguments
  469. ///
  470. /// * `domain_name` - The input domain name as UTF-8 bytes. (The UTF-8ness is checked by
  471. /// this method and input that is not well-formed UTF-8 is treated as an error. If you
  472. /// already have a `&str`, call `.as_bytes()` on it.)
  473. /// * `ascii_deny_list` - What ASCII deny list, if any, to apply. The UTS 46
  474. /// _UseSTD3ASCIIRules_ flag or the WHATWG URL Standard forbidden domain code point
  475. /// processing is handled via this argument. Most callers are probably the best off
  476. /// by using [`AsciiDenyList::URL`] here.
  477. /// * `hyphens` - The UTS 46 _CheckHyphens_ flag. Most callers are probably the best
  478. /// off by using [`Hyphens::Allow`] here.
  479. /// * `dns_length` - The UTS 46 _VerifyDNSLength_ flag.
  480. pub fn to_ascii<'a>(
  481. &self,
  482. domain_name: &'a [u8],
  483. ascii_deny_list: AsciiDenyList,
  484. hyphens: Hyphens,
  485. dns_length: DnsLength,
  486. ) -> Result<Cow<'a, str>, crate::Errors> {
  487. let mut s = String::new();
  488. match self.process(
  489. domain_name,
  490. ascii_deny_list,
  491. hyphens,
  492. ErrorPolicy::FailFast,
  493. |_, _, _| false,
  494. &mut s,
  495. None,
  496. ) {
  497. // SAFETY: `ProcessingSuccess::Passthrough` asserts that `domain_name` is ASCII.
  498. Ok(ProcessingSuccess::Passthrough) => {
  499. let cow = Cow::Borrowed(unsafe { core::str::from_utf8_unchecked(domain_name) });
  500. if dns_length != DnsLength::Ignore
  501. && !verify_dns_length(&cow, dns_length == DnsLength::VerifyAllowRootDot)
  502. {
  503. Err(crate::Errors::default())
  504. } else {
  505. Ok(cow)
  506. }
  507. }
  508. Ok(ProcessingSuccess::WroteToSink) => {
  509. let cow: Cow<'_, str> = Cow::Owned(s);
  510. if dns_length != DnsLength::Ignore
  511. && !verify_dns_length(&cow, dns_length == DnsLength::VerifyAllowRootDot)
  512. {
  513. Err(crate::Errors::default())
  514. } else {
  515. Ok(cow)
  516. }
  517. }
  518. Err(ProcessingError::ValidityError) => Err(crate::Errors::default()),
  519. Err(ProcessingError::SinkError) => unreachable!(),
  520. }
  521. }
  522. /// Performs the [ToUnicode](https://www.unicode.org/reports/tr46/#ToUnicode) operation
  523. /// from UTS #46 according to the options given. When there
  524. /// are errors, there is still output, which may be rendered user, even through
  525. /// the output must not be used in networking protocols. Errors are denoted
  526. /// by U+FFFD REPLACEMENT CHARACTERs in the output. (That is, if the second item of the
  527. /// return tuple is `Err`, the first item of the return tuple is guaranteed to contain
  528. /// at least one U+FFFD.)
  529. ///
  530. /// Most applications probably shouldn't use this method and should be using
  531. /// [`Uts46::to_user_interface`] instead.
  532. ///
  533. /// # Arguments
  534. ///
  535. /// * `domain_name` - The input domain name as UTF-8 bytes. (The UTF-8ness is checked by
  536. /// this method and input that is not well-formed UTF-8 is treated as an error. If you
  537. /// already have a `&str`, call `.as_bytes()` on it.)
  538. /// * `ascii_deny_list` - What ASCII deny list, if any, to apply. The UTS 46
  539. /// _UseSTD3ASCIIRules_ flag or the WHATWG URL Standard forbidden domain code point
  540. /// processing is handled via this argument. Most callers are probably the best off
  541. /// by using [`AsciiDenyList::URL`] here.
  542. /// * `hyphens` - The UTS 46 _CheckHyphens_ flag. Most callers are probably the best
  543. /// off by using [`Hyphens::Allow`] here.
  544. pub fn to_unicode<'a>(
  545. &self,
  546. domain_name: &'a [u8],
  547. ascii_deny_list: AsciiDenyList,
  548. hyphens: Hyphens,
  549. ) -> (Cow<'a, str>, Result<(), crate::Errors>) {
  550. self.to_user_interface(domain_name, ascii_deny_list, hyphens, |_, _, _| true)
  551. }
  552. /// Performs the [ToUnicode](https://www.unicode.org/reports/tr46/#ToUnicode) operation
  553. /// from UTS #46 according to options given with some
  554. /// error-free Unicode labels output according to
  555. /// [ToASCII](https://www.unicode.org/reports/tr46/#ToASCII) instead as decided by
  556. /// application policy implemented via the `output_as_unicode` closure. The purpose
  557. /// is to convert user-visible domains to the Unicode form in general but to render
  558. /// potentially misleading labels as Punycode.
  559. ///
  560. /// This is an imperfect security mechanism, because [the Punycode form itself may be
  561. /// resemble a user-recognizable name](https://www.unicode.org/reports/tr36/#TablePunycodeSpoofing).
  562. /// However, since this mechanism is common practice, this API provides support for The
  563. /// the mechanism.
  564. ///
  565. /// ASCII labels always pass through as ASCII and labels with errors always pass through
  566. /// as Unicode. For non-erroneous labels that contain at least one non-ASCII character
  567. /// (implies non-empty), `output_as_unicode` is called with the Unicode form of the label,
  568. /// the TLD (potentially empty), and a flag indicating whether the domain name as a whole
  569. /// is a bidi domain name. If the return value is `true`, the label passes through as
  570. /// Unicode. If the return value is `false`, the label is converted to Punycode.
  571. ///
  572. /// When there are errors, there is still output, which may be rendered user, even through
  573. /// the output must not be used in networking protocols. Errors are denoted by
  574. /// U+FFFD REPLACEMENT CHARACTERs in the output. (That is, if the second item
  575. /// of the return tuple is `Err`, the first item of the return tuple is guaranteed to contain
  576. /// at least one U+FFFD.) Labels that contain errors are not converted to Punycode.
  577. ///
  578. /// # Arguments
  579. ///
  580. /// * `domain_name` - The input domain name as UTF-8 bytes. (The UTF-8ness is checked by
  581. /// this method and input that is not well-formed UTF-8 is treated as an error. If you
  582. /// already have a `&str`, call `.as_bytes()` on it.)
  583. /// * `ascii_deny_list` - What ASCII deny list, if any, to apply. The UTS 46
  584. /// _UseSTD3ASCIIRules_ flag or the WHATWG URL Standard forbidden domain code point
  585. /// processing is handled via this argument. Most callers are probably the best off
  586. /// by using [`AsciiDenyList::URL`] here.
  587. /// * `hyphens` - The UTS 46 _CheckHyphens_ flag. Most callers are probably the best
  588. /// off by using [`Hyphens::Allow`] here.
  589. /// * `output_as_unicode` - A closure for deciding if a label should be output as Unicode
  590. /// (as opposed to Punycode). The first argument is the label for which a decision is
  591. /// needed (always non-empty slice). The second argument is the TLD (potentially empty).
  592. /// The third argument is `true` iff the domain name as a whole is a bidi domain name.
  593. /// Only non-erroneous labels that contain at least one non-ASCII character are passed
  594. /// to the closure as the first argument. The second and third argument values are
  595. /// guaranteed to remain the same during a single call to `process`, and the closure
  596. /// may cache computations derived from the second and third argument (hence the
  597. /// `FnMut` type).
  598. pub fn to_user_interface<'a, OutputUnicode: FnMut(&[char], &[char], bool) -> bool>(
  599. &self,
  600. domain_name: &'a [u8],
  601. ascii_deny_list: AsciiDenyList,
  602. hyphens: Hyphens,
  603. output_as_unicode: OutputUnicode,
  604. ) -> (Cow<'a, str>, Result<(), crate::Errors>) {
  605. let mut s = String::new();
  606. match self.process(
  607. domain_name,
  608. ascii_deny_list,
  609. hyphens,
  610. ErrorPolicy::MarkErrors,
  611. output_as_unicode,
  612. &mut s,
  613. None,
  614. ) {
  615. // SAFETY: `ProcessingSuccess::Passthrough` asserts that `domain_name` is ASCII.
  616. Ok(ProcessingSuccess::Passthrough) => (
  617. Cow::Borrowed(unsafe { core::str::from_utf8_unchecked(domain_name) }),
  618. Ok(()),
  619. ),
  620. Ok(ProcessingSuccess::WroteToSink) => (Cow::Owned(s), Ok(())),
  621. Err(ProcessingError::ValidityError) => (Cow::Owned(s), Err(crate::Errors::default())),
  622. Err(ProcessingError::SinkError) => unreachable!(),
  623. }
  624. }
  625. /// The lower-level function that [`Uts46::to_ascii`], [`Uts46::to_unicode`], and
  626. /// [`Uts46::to_user_interface`] are built on to allow support for output types other
  627. /// than `Cow<'a, str>` (e.g. string types in a non-Rust programming language).
  628. ///
  629. /// # Arguments
  630. ///
  631. /// * `domain_name` - The input domain name as UTF-8 bytes. (The UTF-8ness is checked by
  632. /// this method and input that is not well-formed UTF-8 is treated as an error. If you
  633. /// already have a `&str`, call `.as_bytes()` on it.)
  634. /// * `ascii_deny_list` - What ASCII deny list, if any, to apply. The UTS 46
  635. /// _UseSTD3ASCIIRules_ flag or the WHATWG URL Standard forbidden domain code point
  636. /// processing is handled via this argument. Most callers are probably the best off
  637. /// by using [`AsciiDenyList::URL`] here.
  638. /// * `hyphens` - The UTS 46 _CheckHyphens_ flag. Most callers are probably the best
  639. /// off by using [`Hyphens::Allow`] here.
  640. /// * `error_policy` - Whether to fail fast or to produce output that may be rendered
  641. /// for the user to examine in case of errors.
  642. /// * `output_as_unicode` - A closure for deciding if a label should be output as Unicode
  643. /// (as opposed to Punycode). The first argument is the label for which a decision is
  644. /// needed (always non-empty slice). The second argument is the TLD (potentially empty).
  645. /// The third argument is `true` iff the domain name as a whole is a bidi domain name.
  646. /// Only non-erroneous labels that contain at least one non-ASCII character are passed
  647. /// to the closure as the first argument. The second and third argument values are
  648. /// guaranteed to remain the same during a single call to `process`, and the closure
  649. /// may cache computations derived from the second and third argument (hence the
  650. /// `FnMut` type). To perform the _ToASCII_ operation, `|_, _, _| false` must be
  651. /// passed as the closure. To perform the _ToUnicode_ operation, `|_, _, _| true` must
  652. /// be passed as the closure. A more complex closure may be used to prepare a domain
  653. /// name for display in a user interface so that labels are converted to the Unicode
  654. /// form in general but potentially misleading labels are converted to the Punycode
  655. /// form.
  656. /// * `sink` - The object that receives the output (in the non-passthrough case).
  657. /// * `ascii_sink` - A second sink that receives the _ToASCII_ form only if there
  658. /// were no errors and `sink` received at least one character of non-ASCII output.
  659. /// The purpose of this argument is to enable a user interface display form of the
  660. /// domain and the _ToASCII_ form of the domain to be computed efficiently together.
  661. /// This argument is useless when `output_as_unicode` always returns `false`, in
  662. /// which case the _ToASCII_ form ends up in `sink` already. If `ascii_sink` receives
  663. /// no output and the return value is `Ok(ProcessingSuccess::WroteToSink)`, use the
  664. /// output received by `sink` also as the _ToASCII_ result.
  665. ///
  666. /// # Return value
  667. ///
  668. /// * `Ok(ProcessingSuccess::Passthrough)` - The caller must treat
  669. /// `unsafe { core::str::from_utf8_unchecked(domain_name) }` as the output. (This
  670. /// return value asserts that calling `core::str::from_utf8_unchecked(domain_name)`
  671. /// is safe.)
  672. /// * `Ok(ProcessingSuccess::WroteToSink)` - The caller must treat was was written
  673. /// to `sink` as the output. If another sink was passed as `ascii_sink` but it did
  674. /// not receive output, the caller must treat what was written to `sink` also as
  675. /// the _ToASCII_ output. Otherwise, if `ascii_sink` received output, the caller
  676. /// must treat what was written to `ascii_sink` as the _ToASCII_ output.
  677. /// * `Err(ProcessingError::ValidityError)` - The input was in error and must
  678. /// not be used for DNS lookup or otherwise in a network protocol. If `error_policy`
  679. /// was `ErrorPolicy::MarkErrors`, the output written to `sink` may be displayed
  680. /// to the user as an illustration of where the error was or the errors were.
  681. /// * `Err(ProcessingError::SinkError)` - Either `sink` or `ascii_sink` returned
  682. /// [`core::fmt::Error`]. The partial output written to `sink` `ascii_sink` must not
  683. /// be used. If `W` never returns [`core::fmt::Error`], this method never returns
  684. /// `Err(ProcessingError::SinkError)`.
  685. ///
  686. /// # Safety-usable invariant
  687. ///
  688. /// If the return value is `Ok(ProcessingSuccess::Passthrough)`, `domain_name` is
  689. /// ASCII and `core::str::from_utf8_unchecked(domain_name)` is safe. (Note:
  690. /// Other return values do _not_ imply that `domain_name` wasn't ASCII!)
  691. ///
  692. /// # Security considerations
  693. ///
  694. /// Showing labels whose Unicode form might mislead the user as Punycode instead is
  695. /// an imperfect security mechanism, because [the Punycode form itself may be resemble
  696. /// a user-recognizable name](https://www.unicode.org/reports/tr36/#TablePunycodeSpoofing).
  697. /// However, since this mechanism is common practice, this API provides support for the
  698. /// the mechanism.
  699. ///
  700. /// Punycode processing is quadratic, so to avoid denial of service, this method imposes
  701. /// length limits on Punycode treating especially long inputs as being in error. These
  702. /// limits are well higher than the DNS length limits and are not more restrictive than
  703. /// the limits imposed by ICU4C.
  704. #[allow(clippy::too_many_arguments)]
  705. pub fn process<W: Write + ?Sized, OutputUnicode: FnMut(&[char], &[char], bool) -> bool>(
  706. &self,
  707. domain_name: &[u8],
  708. ascii_deny_list: AsciiDenyList,
  709. hyphens: Hyphens,
  710. error_policy: ErrorPolicy,
  711. mut output_as_unicode: OutputUnicode,
  712. sink: &mut W,
  713. ascii_sink: Option<&mut W>,
  714. ) -> Result<ProcessingSuccess, ProcessingError> {
  715. let fail_fast = error_policy == ErrorPolicy::FailFast;
  716. let mut domain_buffer = SmallVec::<[char; 253]>::new();
  717. let mut already_punycode = SmallVec::<[AlreadyAsciiLabel; 8]>::new();
  718. // `process_inner` could be pasted inline here, but it's out of line in order
  719. // to avoid duplicating that code when monomorphizing over `W` and `OutputUnicode`.
  720. let (passthrough_up_to, is_bidi, had_errors) = self.process_inner(
  721. domain_name,
  722. ascii_deny_list,
  723. hyphens,
  724. fail_fast,
  725. &mut domain_buffer,
  726. &mut already_punycode,
  727. );
  728. if passthrough_up_to == domain_name.len() {
  729. debug_assert!(!had_errors);
  730. return Ok(ProcessingSuccess::Passthrough);
  731. }
  732. // Checked only after passthrough as a micro optimization.
  733. if fail_fast && had_errors {
  734. return Err(ProcessingError::ValidityError);
  735. }
  736. debug_assert_eq!(had_errors, domain_buffer.contains(&'\u{FFFD}'));
  737. let without_dot = if let Some(without_dot) = domain_buffer.strip_suffix(&['.']) {
  738. without_dot
  739. } else {
  740. &domain_buffer[..]
  741. };
  742. // unwrap is OK, because we always have at least one label
  743. let tld = without_dot.rsplit(|c| *c == '.').next().unwrap();
  744. let mut had_unicode_output = false;
  745. let mut seen_label = false;
  746. let mut already_punycode_iter = already_punycode.iter();
  747. let mut passthrough_up_to_extended = passthrough_up_to;
  748. let mut flushed_prefix = false;
  749. for label in domain_buffer.split(|c| *c == '.') {
  750. // Unwrap is OK, because there are supposed to be as many items in
  751. // `already_punycode` as there are labels.
  752. let input_punycode = *already_punycode_iter.next().unwrap();
  753. if seen_label {
  754. if flushed_prefix {
  755. sink.write_char('.')?;
  756. } else {
  757. debug_assert_eq!(domain_name[passthrough_up_to_extended], b'.');
  758. passthrough_up_to_extended += 1;
  759. if passthrough_up_to_extended == domain_name.len() {
  760. debug_assert!(!had_errors);
  761. return Ok(ProcessingSuccess::Passthrough);
  762. }
  763. }
  764. }
  765. seen_label = true;
  766. if let AlreadyAsciiLabel::MixedCaseAscii(mixed_case) = input_punycode {
  767. if let Some(first_upper_case) =
  768. mixed_case.iter().position(|c| c.is_ascii_uppercase())
  769. {
  770. let (head, tail) = mixed_case.split_at(first_upper_case);
  771. let slice_to_write = if flushed_prefix {
  772. head
  773. } else {
  774. flushed_prefix = true;
  775. passthrough_up_to_extended += head.len();
  776. debug_assert_ne!(passthrough_up_to_extended, domain_name.len());
  777. &domain_name[..passthrough_up_to_extended]
  778. };
  779. // SAFETY: `mixed_case` and `domain_name` up to `passthrough_up_to_extended` are known to be ASCII.
  780. sink.write_str(unsafe { core::str::from_utf8_unchecked(slice_to_write) })?;
  781. for c in tail.iter() {
  782. sink.write_char(char::from(c.to_ascii_lowercase()))?;
  783. }
  784. } else if flushed_prefix {
  785. // SAFETY: `mixed_case` is known to be ASCII.
  786. sink.write_str(unsafe { core::str::from_utf8_unchecked(mixed_case) })?;
  787. } else {
  788. passthrough_up_to_extended += mixed_case.len();
  789. if passthrough_up_to_extended == domain_name.len() {
  790. debug_assert!(!had_errors);
  791. return Ok(ProcessingSuccess::Passthrough);
  792. }
  793. }
  794. continue;
  795. }
  796. let potentially_punycode = if fail_fast {
  797. debug_assert!(classify_for_punycode(label) != PunycodeClassification::Error);
  798. !is_ascii(label)
  799. } else {
  800. classify_for_punycode(label) == PunycodeClassification::Unicode
  801. };
  802. let passthrough = if potentially_punycode {
  803. let unicode = output_as_unicode(label, tld, is_bidi);
  804. had_unicode_output |= unicode;
  805. unicode
  806. } else {
  807. true
  808. };
  809. if passthrough {
  810. if !flushed_prefix {
  811. flushed_prefix = true;
  812. // SAFETY: `domain_name` up to `passthrough_up_to_extended` is known to be ASCII.
  813. sink.write_str(unsafe {
  814. core::str::from_utf8_unchecked(&domain_name[..passthrough_up_to_extended])
  815. })?;
  816. }
  817. for c in label.iter().copied() {
  818. sink.write_char(c)?;
  819. }
  820. } else if let AlreadyAsciiLabel::MixedCasePunycode(mixed_case) = input_punycode {
  821. if let Some(first_upper_case) =
  822. mixed_case.iter().position(|c| c.is_ascii_uppercase())
  823. {
  824. let (head, tail) = mixed_case.split_at(first_upper_case);
  825. let slice_to_write = if flushed_prefix {
  826. head
  827. } else {
  828. flushed_prefix = true;
  829. passthrough_up_to_extended += head.len();
  830. debug_assert_ne!(passthrough_up_to_extended, domain_name.len());
  831. &domain_name[..passthrough_up_to_extended]
  832. };
  833. // SAFETY: `mixed_case` and `domain_name` up to `passthrough_up_to_extended` are known to be ASCII.
  834. sink.write_str(unsafe { core::str::from_utf8_unchecked(slice_to_write) })?;
  835. for c in tail.iter() {
  836. sink.write_char(char::from(c.to_ascii_lowercase()))?;
  837. }
  838. } else if flushed_prefix {
  839. // SAFETY: `mixed_case` is known to be ASCII.
  840. sink.write_str(unsafe { core::str::from_utf8_unchecked(mixed_case) })?;
  841. } else {
  842. passthrough_up_to_extended += mixed_case.len();
  843. if passthrough_up_to_extended == domain_name.len() {
  844. debug_assert!(!had_errors);
  845. return Ok(ProcessingSuccess::Passthrough);
  846. }
  847. }
  848. } else {
  849. if !flushed_prefix {
  850. flushed_prefix = true;
  851. // SAFETY: `domain_name` up to `passthrough_up_to_extended` is known to be ASCII.
  852. sink.write_str(unsafe {
  853. core::str::from_utf8_unchecked(&domain_name[..passthrough_up_to_extended])
  854. })?;
  855. }
  856. write_punycode_label(label, sink)?;
  857. }
  858. }
  859. if had_errors {
  860. return Err(ProcessingError::ValidityError);
  861. }
  862. if had_unicode_output {
  863. if let Some(sink) = ascii_sink {
  864. let mut seen_label = false;
  865. let mut already_punycode_iter = already_punycode.iter();
  866. let mut passthrough_up_to_extended = passthrough_up_to;
  867. let mut flushed_prefix = false;
  868. for label in domain_buffer.split(|c| *c == '.') {
  869. // Unwrap is OK, because there are supposed to be as many items in
  870. // `already_punycode` as there are labels.
  871. let input_punycode = *already_punycode_iter.next().unwrap();
  872. if seen_label {
  873. if flushed_prefix {
  874. sink.write_char('.')?;
  875. } else {
  876. debug_assert_eq!(domain_name[passthrough_up_to_extended], b'.');
  877. passthrough_up_to_extended += 1;
  878. }
  879. }
  880. seen_label = true;
  881. if let AlreadyAsciiLabel::MixedCaseAscii(mixed_case) = input_punycode {
  882. if let Some(first_upper_case) =
  883. mixed_case.iter().position(|c| c.is_ascii_uppercase())
  884. {
  885. let (head, tail) = mixed_case.split_at(first_upper_case);
  886. let slice_to_write = if flushed_prefix {
  887. head
  888. } else {
  889. flushed_prefix = true;
  890. passthrough_up_to_extended += head.len();
  891. debug_assert_ne!(passthrough_up_to_extended, domain_name.len());
  892. &domain_name[..passthrough_up_to_extended]
  893. };
  894. // SAFETY: `mixed_case` and `domain_name` up to `passthrough_up_to_extended` are known to be ASCII.
  895. sink.write_str(unsafe {
  896. core::str::from_utf8_unchecked(slice_to_write)
  897. })?;
  898. for c in tail.iter() {
  899. sink.write_char(char::from(c.to_ascii_lowercase()))?;
  900. }
  901. } else if flushed_prefix {
  902. // SAFETY: `mixed_case` is known to be ASCII.
  903. sink.write_str(unsafe { core::str::from_utf8_unchecked(mixed_case) })?;
  904. } else {
  905. passthrough_up_to_extended += mixed_case.len();
  906. }
  907. continue;
  908. }
  909. if is_ascii(label) {
  910. if !flushed_prefix {
  911. flushed_prefix = true;
  912. // SAFETY: `domain_name` up to `passthrough_up_to_extended` is known to be ASCII.
  913. sink.write_str(unsafe {
  914. core::str::from_utf8_unchecked(
  915. &domain_name[..passthrough_up_to_extended],
  916. )
  917. })?;
  918. }
  919. for c in label.iter().copied() {
  920. sink.write_char(c)?;
  921. }
  922. } else if let AlreadyAsciiLabel::MixedCasePunycode(mixed_case) = input_punycode
  923. {
  924. if let Some(first_upper_case) =
  925. mixed_case.iter().position(|c| c.is_ascii_uppercase())
  926. {
  927. let (head, tail) = mixed_case.split_at(first_upper_case);
  928. let slice_to_write = if flushed_prefix {
  929. head
  930. } else {
  931. flushed_prefix = true;
  932. passthrough_up_to_extended += head.len();
  933. debug_assert_ne!(passthrough_up_to_extended, domain_name.len());
  934. &domain_name[..passthrough_up_to_extended]
  935. };
  936. // SAFETY: `mixed_case` and `domain_name` up to `passthrough_up_to_extended` are known to be ASCII.
  937. sink.write_str(unsafe {
  938. core::str::from_utf8_unchecked(slice_to_write)
  939. })?;
  940. for c in tail.iter() {
  941. sink.write_char(char::from(c.to_ascii_lowercase()))?;
  942. }
  943. } else if flushed_prefix {
  944. // SAFETY: `mixed_case` is known to be ASCII.
  945. sink.write_str(unsafe { core::str::from_utf8_unchecked(mixed_case) })?;
  946. } else {
  947. passthrough_up_to_extended += mixed_case.len();
  948. }
  949. } else {
  950. if !flushed_prefix {
  951. flushed_prefix = true;
  952. // SAFETY: `domain_name` up to `passthrough_up_to_extended` is known to be ASCII.
  953. sink.write_str(unsafe {
  954. core::str::from_utf8_unchecked(
  955. &domain_name[..passthrough_up_to_extended],
  956. )
  957. })?;
  958. }
  959. write_punycode_label(label, sink)?;
  960. }
  961. }
  962. if !flushed_prefix {
  963. // SAFETY: `domain_name` up to `passthrough_up_to_extended` is known to be ASCII.
  964. sink.write_str(unsafe {
  965. core::str::from_utf8_unchecked(&domain_name[..passthrough_up_to_extended])
  966. })?;
  967. }
  968. }
  969. }
  970. Ok(ProcessingSuccess::WroteToSink)
  971. }
  972. /// The part of `process` that doesn't need to be generic over the sink.
  973. #[inline(always)]
  974. fn process_inner<'a>(
  975. &self,
  976. domain_name: &'a [u8],
  977. ascii_deny_list: AsciiDenyList,
  978. hyphens: Hyphens,
  979. fail_fast: bool,
  980. domain_buffer: &mut SmallVec<[char; 253]>,
  981. already_punycode: &mut SmallVec<[AlreadyAsciiLabel<'a>; 8]>,
  982. ) -> (usize, bool, bool) {
  983. // Sadly, this even faster-path ASCII tier is needed to avoid regressing
  984. // performance.
  985. let mut iter = domain_name.iter();
  986. let mut most_recent_label_start = iter.clone();
  987. loop {
  988. if let Some(&b) = iter.next() {
  989. if in_inclusive_range8(b, b'a', b'z') {
  990. continue;
  991. }
  992. if b == b'.' {
  993. most_recent_label_start = iter.clone();
  994. continue;
  995. }
  996. return self.process_innermost(
  997. domain_name,
  998. ascii_deny_list,
  999. hyphens,
  1000. fail_fast,
  1001. domain_buffer,
  1002. already_punycode,
  1003. most_recent_label_start.as_slice(),
  1004. );
  1005. } else {
  1006. // Success! The whole input passes through on the fastest path!
  1007. return (domain_name.len(), false, false);
  1008. }
  1009. }
  1010. }
  1011. /// The part of `process` that doesn't need to be generic over the sink and
  1012. /// can avoid monomorphizing in the interest of code size.
  1013. /// Separating this into a different stack frame compared to `process_inner`
  1014. /// improves performance in the ICU4X case.
  1015. #[allow(clippy::too_many_arguments)]
  1016. #[inline(never)]
  1017. fn process_innermost<'a>(
  1018. &self,
  1019. domain_name: &'a [u8],
  1020. ascii_deny_list: AsciiDenyList,
  1021. hyphens: Hyphens,
  1022. fail_fast: bool,
  1023. domain_buffer: &mut SmallVec<[char; 253]>,
  1024. already_punycode: &mut SmallVec<[AlreadyAsciiLabel<'a>; 8]>,
  1025. tail: &'a [u8],
  1026. ) -> (usize, bool, bool) {
  1027. let deny_list = ascii_deny_list.bits;
  1028. let deny_list_deny_dot = deny_list | DOT_MASK;
  1029. let mut had_errors = false;
  1030. let mut passthrough_up_to = domain_name.len() - tail.len(); // Index into `domain_name`
  1031. // 253 ASCII characters is the max length for a valid domain name
  1032. // (excluding the root dot).
  1033. let mut current_label_start; // Index into `domain_buffer`
  1034. let mut seen_label = false;
  1035. let mut in_prefix = true;
  1036. for label in tail.split(|b| *b == b'.') {
  1037. // We check for passthrough only for the prefix. That is, if we
  1038. // haven't moved on and started filling `domain_buffer`. Keeping
  1039. // this stuff in one loop where the first items keep being skipped
  1040. // once they have been skipped at least once instead of working
  1041. // this into a fancier loop structure in order to make sure that
  1042. // no item from the iterator is lost or processed twice.
  1043. // Furthermore, after the passthrough fails, restarting the
  1044. // normalization process after each pre-existing ASCII dot also
  1045. // provides an opportunity for the processing to get back onto
  1046. // an ASCII fast path that bypasses the normalizer for ASCII
  1047. // after a pre-existing ASCII dot (pre-existing in the sense
  1048. // of not coming from e.g. normalizing an ideographic dot).
  1049. if in_prefix && is_passthrough_ascii_label(label) {
  1050. if seen_label {
  1051. debug_assert_eq!(domain_name[passthrough_up_to], b'.');
  1052. passthrough_up_to += 1;
  1053. }
  1054. seen_label = true;
  1055. passthrough_up_to += label.len();
  1056. continue;
  1057. }
  1058. if seen_label {
  1059. if in_prefix {
  1060. debug_assert_eq!(domain_name[passthrough_up_to], b'.');
  1061. passthrough_up_to += 1;
  1062. } else {
  1063. domain_buffer.push('.');
  1064. }
  1065. }
  1066. seen_label = true;
  1067. in_prefix = false;
  1068. current_label_start = domain_buffer.len();
  1069. if !label.is_empty() {
  1070. let (ascii, non_ascii) = split_ascii_fast_path_prefix(label);
  1071. let non_punycode_ascii_label = if non_ascii.is_empty() {
  1072. if has_punycode_prefix(ascii) {
  1073. if (ascii.last() != Some(&b'-'))
  1074. && (ascii.len() - 4 <= PUNYCODE_DECODE_MAX_INPUT_LENGTH)
  1075. {
  1076. if let Ok(decode) =
  1077. Decoder::default().decode::<u8, InternalCaller>(&ascii[4..])
  1078. {
  1079. // 63 ASCII characters is the max length for a valid DNS label and xn-- takes 4
  1080. // characters.
  1081. let mut label_buffer = SmallVec::<[char; 59]>::new();
  1082. label_buffer.extend(decode);
  1083. if self.after_punycode_decode(
  1084. domain_buffer,
  1085. current_label_start,
  1086. &label_buffer,
  1087. deny_list_deny_dot,
  1088. fail_fast,
  1089. &mut had_errors,
  1090. ) {
  1091. return (0, false, true);
  1092. }
  1093. if self.check_label(
  1094. hyphens,
  1095. &mut domain_buffer[current_label_start..],
  1096. fail_fast,
  1097. &mut had_errors,
  1098. true,
  1099. true,
  1100. ) {
  1101. return (0, false, true);
  1102. }
  1103. } else {
  1104. // Punycode failed
  1105. if fail_fast {
  1106. return (0, false, true);
  1107. }
  1108. had_errors = true;
  1109. domain_buffer.push('\u{FFFD}');
  1110. let mut iter = ascii.iter();
  1111. // Discard the first character that we replaced.
  1112. let _ = iter.next();
  1113. domain_buffer.extend(iter.map(|c| {
  1114. // Can't have dot here, so `deny_list` vs `deny_list_deny_dot` does
  1115. // not matter.
  1116. apply_ascii_deny_list_to_potentially_upper_case_ascii(
  1117. *c, deny_list,
  1118. )
  1119. }));
  1120. };
  1121. // If there were errors, we won't be trying to use this
  1122. // anyway later, so it's fine to put it here unconditionally.
  1123. already_punycode.push(AlreadyAsciiLabel::MixedCasePunycode(label));
  1124. continue;
  1125. } else if fail_fast {
  1126. return (0, false, true);
  1127. }
  1128. // Else fall through to the complex path and rediscover error
  1129. // there.
  1130. false
  1131. } else {
  1132. true
  1133. }
  1134. } else {
  1135. false
  1136. };
  1137. for c in ascii.iter().map(|c| {
  1138. // Can't have dot here, so `deny_list` vs `deny_list_deny_dot` does
  1139. // not matter.
  1140. apply_ascii_deny_list_to_potentially_upper_case_ascii(*c, deny_list)
  1141. }) {
  1142. if c == '\u{FFFD}' {
  1143. if fail_fast {
  1144. return (0, false, true);
  1145. }
  1146. had_errors = true;
  1147. }
  1148. domain_buffer.push(c);
  1149. }
  1150. if non_punycode_ascii_label {
  1151. if hyphens != Hyphens::Allow
  1152. && check_hyphens(
  1153. &mut domain_buffer[current_label_start..],
  1154. hyphens == Hyphens::CheckFirstLast,
  1155. fail_fast,
  1156. &mut had_errors,
  1157. )
  1158. {
  1159. return (0, false, true);
  1160. }
  1161. already_punycode.push(if had_errors {
  1162. AlreadyAsciiLabel::Other
  1163. } else {
  1164. AlreadyAsciiLabel::MixedCaseAscii(label)
  1165. });
  1166. continue;
  1167. }
  1168. already_punycode.push(AlreadyAsciiLabel::Other);
  1169. let mut first_needs_combining_mark_check = ascii.is_empty();
  1170. let mut needs_contextj_check = !non_ascii.is_empty();
  1171. let mut mapping = self
  1172. .data
  1173. .map_normalize(non_ascii.chars())
  1174. .map(|c| apply_ascii_deny_list_to_lower_cased_unicode(c, deny_list));
  1175. loop {
  1176. let n = mapping.next();
  1177. match n {
  1178. None | Some('.') => {
  1179. if domain_buffer[current_label_start..]
  1180. .starts_with(&['x', 'n', '-', '-'])
  1181. {
  1182. let mut punycode_precondition_failed = false;
  1183. for c in domain_buffer[current_label_start + 4..].iter_mut() {
  1184. if !c.is_ascii() {
  1185. if fail_fast {
  1186. return (0, false, true);
  1187. }
  1188. had_errors = true;
  1189. *c = '\u{FFFD}';
  1190. punycode_precondition_failed = true;
  1191. }
  1192. }
  1193. if let Some(last) = domain_buffer.last_mut() {
  1194. if *last == '-' {
  1195. // Either there's nothing after the "xn--" prefix
  1196. // and we got the last hyphen of "xn--", or there
  1197. // are no Punycode digits after the last delimiter
  1198. // which would result in Punycode decode outputting
  1199. // ASCII only.
  1200. if fail_fast {
  1201. return (0, false, true);
  1202. }
  1203. had_errors = true;
  1204. *last = '\u{FFFD}';
  1205. punycode_precondition_failed = true;
  1206. }
  1207. } else {
  1208. unreachable!();
  1209. }
  1210. // Reject excessively long input
  1211. // https://github.com/whatwg/url/issues/824
  1212. // https://unicode-org.atlassian.net/browse/ICU-13727
  1213. if domain_buffer.len() - current_label_start - 4
  1214. > PUNYCODE_DECODE_MAX_INPUT_LENGTH
  1215. {
  1216. if fail_fast {
  1217. return (0, false, true);
  1218. }
  1219. had_errors = true;
  1220. domain_buffer[current_label_start
  1221. + 4
  1222. + PUNYCODE_DECODE_MAX_INPUT_LENGTH] = '\u{FFFD}';
  1223. punycode_precondition_failed = true;
  1224. }
  1225. if !punycode_precondition_failed {
  1226. if let Ok(decode) = Decoder::default()
  1227. .decode::<char, InternalCaller>(
  1228. &domain_buffer[current_label_start + 4..],
  1229. )
  1230. {
  1231. first_needs_combining_mark_check = true;
  1232. needs_contextj_check = true;
  1233. // 63 ASCII characters is the max length for a valid DNS label and xn-- takes 4
  1234. // characters.
  1235. let mut label_buffer = SmallVec::<[char; 59]>::new();
  1236. label_buffer.extend(decode);
  1237. domain_buffer.truncate(current_label_start);
  1238. if self.after_punycode_decode(
  1239. domain_buffer,
  1240. current_label_start,
  1241. &label_buffer,
  1242. deny_list_deny_dot,
  1243. fail_fast,
  1244. &mut had_errors,
  1245. ) {
  1246. return (0, false, true);
  1247. }
  1248. } else {
  1249. // Punycode failed
  1250. if fail_fast {
  1251. return (0, false, true);
  1252. }
  1253. had_errors = true;
  1254. domain_buffer[current_label_start] = '\u{FFFD}';
  1255. needs_contextj_check = false; // ASCII label
  1256. first_needs_combining_mark_check = false;
  1257. };
  1258. } else {
  1259. first_needs_combining_mark_check = false;
  1260. needs_contextj_check = false; // Non-ASCII already turned to U+FFFD.
  1261. }
  1262. }
  1263. if self.check_label(
  1264. hyphens,
  1265. &mut domain_buffer[current_label_start..],
  1266. fail_fast,
  1267. &mut had_errors,
  1268. first_needs_combining_mark_check,
  1269. needs_contextj_check,
  1270. ) {
  1271. return (0, false, true);
  1272. }
  1273. if n.is_none() {
  1274. break;
  1275. }
  1276. domain_buffer.push('.');
  1277. current_label_start = domain_buffer.len();
  1278. first_needs_combining_mark_check = true;
  1279. needs_contextj_check = true;
  1280. already_punycode.push(AlreadyAsciiLabel::Other);
  1281. }
  1282. Some(c) => {
  1283. if c == '\u{FFFD}' {
  1284. if fail_fast {
  1285. return (0, false, true);
  1286. }
  1287. had_errors = true;
  1288. }
  1289. domain_buffer.push(c);
  1290. }
  1291. }
  1292. }
  1293. } else {
  1294. // Empty label
  1295. already_punycode.push(AlreadyAsciiLabel::MixedCaseAscii(label));
  1296. }
  1297. }
  1298. let is_bidi = self.is_bidi(domain_buffer);
  1299. if is_bidi {
  1300. for label in domain_buffer.split_mut(|c| *c == '.') {
  1301. if let Some((first, tail)) = label.split_first_mut() {
  1302. let first_bc = self.data.bidi_class(*first);
  1303. if !FIRST_BC_MASK.intersects(first_bc.to_mask()) {
  1304. // Neither RTL label nor LTR label
  1305. if fail_fast {
  1306. return (0, false, true);
  1307. }
  1308. had_errors = true;
  1309. *first = '\u{FFFD}';
  1310. continue;
  1311. }
  1312. let is_ltr = first_bc.is_ltr();
  1313. // Trim NSM
  1314. let mut middle = tail;
  1315. #[allow(clippy::while_let_loop)]
  1316. loop {
  1317. if let Some((last, prior)) = middle.split_last_mut() {
  1318. let last_bc = self.data.bidi_class(*last);
  1319. if last_bc.is_nonspacing_mark() {
  1320. middle = prior;
  1321. continue;
  1322. }
  1323. let last_mask = if is_ltr { LAST_LTR_MASK } else { LAST_RTL_MASK };
  1324. if !last_mask.intersects(last_bc.to_mask()) {
  1325. if fail_fast {
  1326. return (0, false, true);
  1327. }
  1328. had_errors = true;
  1329. *last = '\u{FFFD}';
  1330. }
  1331. if is_ltr {
  1332. for c in prior.iter_mut() {
  1333. let bc = self.data.bidi_class(*c);
  1334. if !MIDDLE_LTR_MASK.intersects(bc.to_mask()) {
  1335. if fail_fast {
  1336. return (0, false, true);
  1337. }
  1338. had_errors = true;
  1339. *c = '\u{FFFD}';
  1340. }
  1341. }
  1342. } else {
  1343. let mut numeral_state = RtlNumeralState::Undecided;
  1344. for c in prior.iter_mut() {
  1345. let bc = self.data.bidi_class(*c);
  1346. if !MIDDLE_RTL_MASK.intersects(bc.to_mask()) {
  1347. if fail_fast {
  1348. return (0, false, true);
  1349. }
  1350. had_errors = true;
  1351. *c = '\u{FFFD}';
  1352. } else {
  1353. match numeral_state {
  1354. RtlNumeralState::Undecided => {
  1355. if bc.is_european_number() {
  1356. numeral_state = RtlNumeralState::European;
  1357. } else if bc.is_arabic_number() {
  1358. numeral_state = RtlNumeralState::Arabic;
  1359. }
  1360. }
  1361. RtlNumeralState::European => {
  1362. if bc.is_arabic_number() {
  1363. if fail_fast {
  1364. return (0, false, true);
  1365. }
  1366. had_errors = true;
  1367. *c = '\u{FFFD}';
  1368. }
  1369. }
  1370. RtlNumeralState::Arabic => {
  1371. if bc.is_european_number() {
  1372. if fail_fast {
  1373. return (0, false, true);
  1374. }
  1375. had_errors = true;
  1376. *c = '\u{FFFD}';
  1377. }
  1378. }
  1379. }
  1380. }
  1381. }
  1382. if (numeral_state == RtlNumeralState::European
  1383. && last_bc.is_arabic_number())
  1384. || (numeral_state == RtlNumeralState::Arabic
  1385. && last_bc.is_european_number())
  1386. {
  1387. if fail_fast {
  1388. return (0, false, true);
  1389. }
  1390. had_errors = true;
  1391. *last = '\u{FFFD}';
  1392. }
  1393. }
  1394. break;
  1395. } else {
  1396. // One-character label or label where
  1397. // everything after the first character
  1398. // is just non-spacing marks.
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. (passthrough_up_to, is_bidi, had_errors)
  1406. }
  1407. #[inline(never)]
  1408. fn after_punycode_decode(
  1409. &self,
  1410. domain_buffer: &mut SmallVec<[char; 253]>,
  1411. current_label_start: usize,
  1412. label_buffer: &[char],
  1413. deny_list_deny_dot: u128,
  1414. fail_fast: bool,
  1415. had_errors: &mut bool,
  1416. ) -> bool {
  1417. for c in self
  1418. .data
  1419. .normalize_validate(label_buffer.iter().copied())
  1420. .map(|c| apply_ascii_deny_list_to_lower_cased_unicode(c, deny_list_deny_dot))
  1421. {
  1422. if c == '\u{FFFD}' {
  1423. if fail_fast {
  1424. return true;
  1425. }
  1426. *had_errors = true;
  1427. }
  1428. domain_buffer.push(c);
  1429. }
  1430. let normalized = &mut domain_buffer[current_label_start..];
  1431. if let Err(()) =
  1432. normalized
  1433. .iter_mut()
  1434. .zip(label_buffer.iter())
  1435. .try_for_each(|(norm_c, decoded_c)| {
  1436. if *norm_c == *decoded_c {
  1437. Ok(())
  1438. } else {
  1439. // Mark the first difference
  1440. *norm_c = '\u{FFFD}';
  1441. Err(())
  1442. }
  1443. })
  1444. {
  1445. if fail_fast {
  1446. return true;
  1447. }
  1448. *had_errors = true;
  1449. }
  1450. false
  1451. }
  1452. #[inline(never)]
  1453. fn check_label(
  1454. &self,
  1455. hyphens: Hyphens,
  1456. mut_label: &mut [char],
  1457. fail_fast: bool,
  1458. had_errors: &mut bool,
  1459. first_needs_combining_mark_check: bool,
  1460. needs_contextj_check: bool,
  1461. ) -> bool {
  1462. if hyphens != Hyphens::Allow
  1463. && check_hyphens(
  1464. mut_label,
  1465. hyphens == Hyphens::CheckFirstLast,
  1466. fail_fast,
  1467. had_errors,
  1468. )
  1469. {
  1470. return true;
  1471. }
  1472. if first_needs_combining_mark_check {
  1473. if let Some(first) = mut_label.first_mut() {
  1474. if self.data.is_mark(*first) {
  1475. if fail_fast {
  1476. return true;
  1477. }
  1478. *had_errors = true;
  1479. *first = '\u{FFFD}';
  1480. }
  1481. }
  1482. }
  1483. if needs_contextj_check {
  1484. // ContextJ
  1485. for i in 0..mut_label.len() {
  1486. let c = mut_label[i];
  1487. if !in_inclusive_range_char(c, '\u{200C}', '\u{200D}') {
  1488. continue;
  1489. }
  1490. let (head, joiner_and_tail) = mut_label.split_at_mut(i);
  1491. if let Some((joiner, tail)) = joiner_and_tail.split_first_mut() {
  1492. if let Some(previous) = head.last() {
  1493. if self.data.is_virama(*previous) {
  1494. continue;
  1495. }
  1496. } else {
  1497. // No preceding character
  1498. if fail_fast {
  1499. return true;
  1500. }
  1501. *had_errors = true;
  1502. *joiner = '\u{FFFD}';
  1503. continue;
  1504. }
  1505. if c == '\u{200D}' {
  1506. // ZWJ only has the virama rule
  1507. if fail_fast {
  1508. return true;
  1509. }
  1510. *had_errors = true;
  1511. *joiner = '\u{FFFD}';
  1512. continue;
  1513. }
  1514. debug_assert_eq!(c, '\u{200C}');
  1515. if !self.has_appropriately_joining_char(
  1516. head.iter().rev().copied(),
  1517. LEFT_OR_DUAL_JOINING_MASK,
  1518. ) || !self.has_appropriately_joining_char(
  1519. tail.iter().copied(),
  1520. RIGHT_OR_DUAL_JOINING_MASK,
  1521. ) {
  1522. if fail_fast {
  1523. return true;
  1524. }
  1525. *had_errors = true;
  1526. *joiner = '\u{FFFD}';
  1527. }
  1528. } else {
  1529. debug_assert!(false);
  1530. }
  1531. }
  1532. }
  1533. if !is_ascii(mut_label) && mut_label.len() > PUNYCODE_ENCODE_MAX_INPUT_LENGTH {
  1534. // Limit quadratic behavior
  1535. // https://github.com/whatwg/url/issues/824
  1536. // https://unicode-org.atlassian.net/browse/ICU-13727
  1537. if fail_fast {
  1538. return true;
  1539. }
  1540. *had_errors = true;
  1541. mut_label[PUNYCODE_ENCODE_MAX_INPUT_LENGTH] = '\u{FFFD}';
  1542. }
  1543. false
  1544. }
  1545. #[inline(always)]
  1546. fn has_appropriately_joining_char<I: Iterator<Item = char>>(
  1547. &self,
  1548. iter: I,
  1549. required_mask: JoiningTypeMask,
  1550. ) -> bool {
  1551. for c in iter {
  1552. let jt = self.data.joining_type(c);
  1553. if jt.to_mask().intersects(required_mask) {
  1554. return true;
  1555. }
  1556. if jt.is_transparent() {
  1557. continue;
  1558. }
  1559. return false;
  1560. }
  1561. false
  1562. }
  1563. #[inline(always)]
  1564. fn is_bidi(&self, buffer: &[char]) -> bool {
  1565. for &c in buffer {
  1566. if c < '\u{0590}' {
  1567. // Below Hebrew
  1568. continue;
  1569. }
  1570. if in_inclusive_range_char(c, '\u{0900}', '\u{FB1C}') {
  1571. debug_assert_ne!(c, '\u{200F}'); // disallowed
  1572. continue;
  1573. }
  1574. if in_inclusive_range_char(c, '\u{1F000}', '\u{3FFFF}') {
  1575. continue;
  1576. }
  1577. if in_inclusive_range_char(c, '\u{FF00}', '\u{107FF}') {
  1578. continue;
  1579. }
  1580. if in_inclusive_range_char(c, '\u{11000}', '\u{1E7FF}') {
  1581. continue;
  1582. }
  1583. if RTL_MASK.intersects(self.data.bidi_class(c).to_mask()) {
  1584. return true;
  1585. }
  1586. }
  1587. false
  1588. }
  1589. }
  1590. fn check_hyphens(
  1591. mut_label: &mut [char],
  1592. allow_third_fourth: bool,
  1593. fail_fast: bool,
  1594. had_errors: &mut bool,
  1595. ) -> bool {
  1596. if let Some(first) = mut_label.first_mut() {
  1597. if *first == '-' {
  1598. if fail_fast {
  1599. return true;
  1600. }
  1601. *had_errors = true;
  1602. *first = '\u{FFFD}';
  1603. }
  1604. }
  1605. if let Some(last) = mut_label.last_mut() {
  1606. if *last == '-' {
  1607. if fail_fast {
  1608. return true;
  1609. }
  1610. *had_errors = true;
  1611. *last = '\u{FFFD}';
  1612. }
  1613. }
  1614. if allow_third_fourth {
  1615. return false;
  1616. }
  1617. if mut_label.len() >= 4 && mut_label[2] == '-' && mut_label[3] == '-' {
  1618. if fail_fast {
  1619. return true;
  1620. }
  1621. *had_errors = true;
  1622. mut_label[2] = '\u{FFFD}';
  1623. mut_label[3] = '\u{FFFD}';
  1624. }
  1625. false
  1626. }