core.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. import bisect
  2. import re
  3. import unicodedata
  4. import warnings
  5. from typing import Optional, Union
  6. from . import idnadata
  7. from .intranges import intranges_contain
  8. _virama_combining_class = 9
  9. _alabel_prefix = b"xn--"
  10. _max_input_length = 1024
  11. _unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]")
  12. # Bidi category sets from RFC 5893, hoisted out of the per-codepoint loop
  13. _bidi_rtl_first = frozenset({"R", "AL"})
  14. _bidi_rtl_categories = frozenset({"R", "AL", "AN"})
  15. _bidi_rtl_allowed = frozenset({"R", "AL", "AN", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"})
  16. _bidi_rtl_valid_ending = frozenset({"R", "AL", "EN", "AN"})
  17. _bidi_rtl_numeric = frozenset({"AN", "EN"})
  18. _bidi_ltr_allowed = frozenset({"L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"})
  19. _bidi_ltr_valid_ending = frozenset({"L", "EN"})
  20. _bidi_joiner_l_or_d = frozenset({"L", "D"})
  21. _bidi_joiner_r_or_d = frozenset({"R", "D"})
  22. def _joining_type(cp: int) -> Optional[str]:
  23. for jt, ranges in idnadata.joining_types.items():
  24. if intranges_contain(cp, ranges):
  25. return jt
  26. return None
  27. class IDNAError(UnicodeError):
  28. """Base exception for all IDNA-encoding related problems"""
  29. class IDNABidiError(IDNAError):
  30. """Exception when bidirectional requirements are not satisfied"""
  31. class InvalidCodepoint(IDNAError):
  32. """Exception when a disallowed or unallocated codepoint is used"""
  33. class InvalidCodepointContext(IDNAError):
  34. """Exception when the codepoint is not valid in the context it is used"""
  35. def _combining_class(cp: int) -> int:
  36. v = unicodedata.combining(chr(cp))
  37. if v == 0 and not unicodedata.name(chr(cp)):
  38. raise ValueError("Unknown character in unicodedata")
  39. return v
  40. def _is_script(cp: str, script: str) -> bool:
  41. return intranges_contain(ord(cp), idnadata.scripts[script])
  42. def _punycode(s: str) -> bytes:
  43. return s.encode("punycode")
  44. def _unot(s: int) -> str:
  45. return f"U+{s:04X}"
  46. def valid_label_length(label: Union[bytes, str]) -> bool:
  47. """Check that a label does not exceed the maximum permitted length.
  48. Per :rfc:`1035` (and :rfc:`5891` §4.2.4) a DNS label must not exceed
  49. 63 octets. The argument may be either a :class:`str` (a U-label, where
  50. length is measured in characters) or :class:`bytes` (an A-label, where
  51. length is measured in octets).
  52. :param label: The label to check.
  53. :returns: ``True`` if the label is within the length limit, otherwise
  54. ``False``.
  55. """
  56. return len(label) <= 63
  57. def valid_string_length(domain: Union[bytes, str], trailing_dot: bool) -> bool:
  58. """Check that a full domain name does not exceed the maximum length.
  59. Per :rfc:`1035`, a domain name is limited to 253 octets when no trailing
  60. dot is present, or 254 octets when one is included.
  61. :param domain: The full (possibly multi-label) domain name.
  62. :param trailing_dot: ``True`` if ``domain`` includes a trailing ``.``.
  63. :returns: ``True`` if the domain is within the length limit, otherwise
  64. ``False``.
  65. """
  66. return len(domain) <= (254 if trailing_dot else 253)
  67. def check_bidi(label: str, check_ltr: bool = False) -> bool:
  68. """Validate the Bidi Rule from :rfc:`5893` for a single label.
  69. The Bidi Rule constrains how bidirectional characters (Hebrew, Arabic,
  70. etc.) may appear within a label. By default the check is only applied
  71. when the label contains at least one right-to-left character (Unicode
  72. bidirectional categories ``R``, ``AL``, or ``AN``); set ``check_ltr``
  73. to ``True`` to apply it to LTR-only labels as well.
  74. :param label: The label to validate, as a Unicode string.
  75. :param check_ltr: If ``True``, apply the rules even when the label
  76. contains no RTL characters.
  77. :returns: ``True`` if the label satisfies the Bidi Rule.
  78. :raises IDNABidiError: If any of Bidi Rule conditions 1-6 are violated,
  79. or if the directional category of a codepoint cannot be determined.
  80. """
  81. if len(label) > _max_input_length:
  82. raise IDNAError("Label too long")
  83. # Bidi rules should only be applied if string contains RTL characters
  84. bidi_label = False
  85. for idx, cp in enumerate(label, 1):
  86. direction = unicodedata.bidirectional(cp)
  87. if direction == "":
  88. # String likely comes from a newer version of Unicode
  89. raise IDNABidiError(f"Unknown directionality in label {label!r} at position {idx}")
  90. if direction in _bidi_rtl_categories:
  91. bidi_label = True
  92. if not bidi_label and not check_ltr:
  93. return True
  94. # Bidi rule 1
  95. direction = unicodedata.bidirectional(label[0])
  96. if direction in _bidi_rtl_first:
  97. rtl = True
  98. elif direction == "L":
  99. rtl = False
  100. else:
  101. raise IDNABidiError(f"First codepoint in label {label!r} must be directionality L, R or AL")
  102. valid_ending = False
  103. number_type: Optional[str] = None
  104. for idx, cp in enumerate(label, 1):
  105. direction = unicodedata.bidirectional(cp)
  106. if rtl:
  107. # Bidi rule 2
  108. if direction not in _bidi_rtl_allowed:
  109. raise IDNABidiError(f"Invalid direction for codepoint at position {idx} in a right-to-left label")
  110. # Bidi rule 3
  111. if direction in _bidi_rtl_valid_ending:
  112. valid_ending = True
  113. elif direction != "NSM":
  114. valid_ending = False
  115. # Bidi rule 4
  116. if direction in _bidi_rtl_numeric:
  117. if not number_type:
  118. number_type = direction
  119. elif number_type != direction:
  120. raise IDNABidiError("Can not mix numeral types in a right-to-left label")
  121. else:
  122. # Bidi rule 5
  123. if direction not in _bidi_ltr_allowed:
  124. raise IDNABidiError(f"Invalid direction for codepoint at position {idx} in a left-to-right label")
  125. # Bidi rule 6
  126. if direction in _bidi_ltr_valid_ending:
  127. valid_ending = True
  128. elif direction != "NSM":
  129. valid_ending = False
  130. if not valid_ending:
  131. raise IDNABidiError("Label ends with illegal codepoint directionality")
  132. return True
  133. def check_initial_combiner(label: str) -> bool:
  134. """Reject labels that begin with a combining mark.
  135. Per :rfc:`5891` §4.2.3.2 a label must not start with a character of
  136. Unicode general category ``M`` (Mark).
  137. :param label: The label to check.
  138. :returns: ``True`` if the first character is not a combining mark.
  139. :raises IDNAError: If the label begins with a combining character.
  140. """
  141. if unicodedata.category(label[0])[0] == "M":
  142. raise IDNAError("Label begins with an illegal combining character")
  143. return True
  144. def check_hyphen_ok(label: str) -> bool:
  145. """Validate the hyphen restrictions for a label.
  146. Per :rfc:`5891` §4.2.3.1 a label must not start or end with a hyphen
  147. (``U+002D``), and must not have hyphens in both the third and fourth
  148. positions (the prefix reserved for A-labels).
  149. :param label: The label to check.
  150. :returns: ``True`` if the hyphen restrictions are satisfied.
  151. :raises IDNAError: If any of the hyphen restrictions are violated.
  152. """
  153. if label[2:4] == "--":
  154. raise IDNAError("Label has disallowed hyphens in 3rd and 4th position")
  155. if label[0] == "-" or label[-1] == "-":
  156. raise IDNAError("Label must not start or end with a hyphen")
  157. return True
  158. def check_nfc(label: str) -> None:
  159. """Require that a label is in Unicode Normalization Form C.
  160. :param label: The label to check.
  161. :raises IDNAError: If ``label`` differs from its NFC normalisation.
  162. """
  163. if len(label) > _max_input_length:
  164. raise IDNAError("Label too long")
  165. if unicodedata.normalize("NFC", label) != label:
  166. raise IDNAError("Label must be in Normalization Form C")
  167. def valid_contextj(label: str, pos: int) -> bool:
  168. """Validate the CONTEXTJ rules from :rfc:`5892` Appendix A.
  169. These rules govern the contextual use of the joiner codepoints
  170. ``U+200C`` (ZERO WIDTH NON-JOINER, Appendix A.1) and ``U+200D``
  171. (ZERO WIDTH JOINER, Appendix A.2) within a label.
  172. :param label: The label containing the codepoint.
  173. :param pos: Index of the joiner codepoint within ``label``.
  174. :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTJ
  175. rule, ``False`` otherwise (including when the codepoint at
  176. ``pos`` is not a recognised joiner).
  177. :raises ValueError: If an adjacent codepoint has no Unicode name when
  178. determining its combining class.
  179. :raises IDNAError: If ``label`` exceeds the defensive input length limit.
  180. """
  181. if len(label) > _max_input_length:
  182. raise IDNAError("Label too long")
  183. cp_value = ord(label[pos])
  184. if cp_value == 0x200C:
  185. if pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class:
  186. return True
  187. ok = False
  188. for i in range(pos - 1, -1, -1):
  189. joining_type = _joining_type(ord(label[i]))
  190. if joining_type == "T":
  191. continue
  192. if joining_type in _bidi_joiner_l_or_d:
  193. ok = True
  194. break
  195. break
  196. if not ok:
  197. return False
  198. ok = False
  199. for i in range(pos + 1, len(label)):
  200. joining_type = _joining_type(ord(label[i]))
  201. if joining_type == "T":
  202. continue
  203. if joining_type in _bidi_joiner_r_or_d:
  204. ok = True
  205. break
  206. break
  207. return ok
  208. if cp_value == 0x200D:
  209. return pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class
  210. return False
  211. def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
  212. """Validate the CONTEXTO rules from :rfc:`5892` Appendix A.
  213. Covers the contextual rules for codepoints such as MIDDLE DOT
  214. (``U+00B7``), Greek lower numeral sign, Hebrew punctuation, Katakana
  215. middle dot, and the Arabic-Indic / Extended Arabic-Indic digit ranges.
  216. :param label: The label containing the codepoint.
  217. :param pos: Index of the codepoint within ``label``.
  218. :param exception: Reserved for forward compatibility; currently unused.
  219. :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTO
  220. rule, ``False`` otherwise (including when the codepoint is not a
  221. recognised CONTEXTO codepoint).
  222. :raises IDNAError: If ``label`` exceeds the defensive input length limit.
  223. """
  224. if len(label) > _max_input_length:
  225. raise IDNAError("Label too long")
  226. cp_value = ord(label[pos])
  227. if cp_value == 0x00B7:
  228. return 0 < pos < len(label) - 1 and ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C
  229. if cp_value == 0x0375:
  230. if pos < len(label) - 1 and len(label) > 1:
  231. return _is_script(label[pos + 1], "Greek")
  232. return False
  233. if cp_value in {0x05F3, 0x05F4}:
  234. if pos > 0:
  235. return _is_script(label[pos - 1], "Hebrew")
  236. return False
  237. if cp_value == 0x30FB:
  238. for cp in label:
  239. if cp == "\u30fb":
  240. continue
  241. if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"):
  242. return True
  243. return False
  244. if 0x660 <= cp_value <= 0x669:
  245. return not any(0x6F0 <= ord(cp) <= 0x06F9 for cp in label)
  246. if 0x6F0 <= cp_value <= 0x6F9:
  247. return not any(0x660 <= ord(cp) <= 0x0669 for cp in label)
  248. return False
  249. def check_label(label: Union[str, bytes, bytearray]) -> None:
  250. """Run the full set of IDNA 2008 validity checks on a single label.
  251. Applies, in order: NFC normalisation (:func:`check_nfc`), hyphen
  252. restrictions (:func:`check_hyphen_ok`), the no-leading-combiner rule
  253. (:func:`check_initial_combiner`), per-codepoint validity (PVALID,
  254. CONTEXTJ, CONTEXTO classes from :rfc:`5892`), and the Bidi Rule
  255. (:func:`check_bidi`).
  256. :param label: The label to validate. ``bytes`` or ``bytearray`` input
  257. is decoded as UTF-8 first.
  258. :raises IDNAError: If the label is empty or fails a structural rule.
  259. :raises InvalidCodepoint: If the label contains a DISALLOWED or
  260. UNASSIGNED codepoint.
  261. :raises InvalidCodepointContext: If a CONTEXTJ or CONTEXTO codepoint
  262. is not valid in its context.
  263. :raises IDNABidiError: If the Bidi Rule is violated.
  264. """
  265. if len(label) > _max_input_length:
  266. raise IDNAError("Label too long")
  267. if isinstance(label, (bytes, bytearray)):
  268. label = label.decode("utf-8")
  269. if len(label) == 0:
  270. raise IDNAError("Empty Label")
  271. # Reject on domain length rather than label length so support some UTS 46
  272. # use cases, still reducing processing of label contextual rules
  273. if not valid_string_length(label, trailing_dot=True):
  274. raise IDNAError("Label too long")
  275. check_nfc(label)
  276. check_hyphen_ok(label)
  277. check_initial_combiner(label)
  278. for pos, cp in enumerate(label):
  279. cp_value = ord(cp)
  280. if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]):
  281. continue
  282. if intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]):
  283. try:
  284. if not valid_contextj(label, pos):
  285. raise InvalidCodepointContext(f"Joiner {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}")
  286. except ValueError as err:
  287. raise IDNAError(
  288. f"Unknown codepoint adjacent to joiner {_unot(cp_value)} at position {pos + 1} in {label!r}"
  289. ) from err
  290. elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]):
  291. if not valid_contexto(label, pos):
  292. raise InvalidCodepointContext(f"Codepoint {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}")
  293. else:
  294. raise InvalidCodepoint(f"Codepoint {_unot(cp_value)} at position {pos + 1} of {label!r} not allowed")
  295. check_bidi(label)
  296. def alabel(label: str) -> bytes:
  297. """Convert a single U-label into its A-label form.
  298. The result is the ASCII-Compatible Encoding (ACE) form per :rfc:`5891`
  299. §4: the label is validated, Punycode-encoded, and prefixed with
  300. ``xn--``. Pure ASCII labels that are already valid IDNA labels are
  301. returned unchanged (as :class:`bytes`).
  302. :param label: The label to convert, as a Unicode string.
  303. :returns: The A-label as ASCII-encoded :class:`bytes`.
  304. :raises IDNAError: If the label is invalid or the resulting A-label
  305. exceeds 63 octets.
  306. """
  307. if len(label) > _max_input_length:
  308. raise IDNAError("Label too long")
  309. try:
  310. label_bytes = label.encode("ascii")
  311. except UnicodeEncodeError:
  312. pass
  313. else:
  314. ulabel(label_bytes)
  315. if not valid_label_length(label_bytes):
  316. raise IDNAError("Label too long")
  317. return label_bytes
  318. check_label(label)
  319. label_bytes = _alabel_prefix + _punycode(label)
  320. if not valid_label_length(label_bytes):
  321. raise IDNAError("Label too long")
  322. return label_bytes
  323. def ulabel(label: Union[str, bytes, bytearray]) -> str:
  324. """Convert a single A-label into its U-label form.
  325. Performs the inverse of :func:`alabel`: an ``xn--``-prefixed label is
  326. Punycode-decoded and validated. Labels that are already Unicode (or
  327. plain ASCII without the ACE prefix) are validated and returned as a
  328. Unicode string.
  329. :param label: The label to convert. ``bytes`` or ``bytearray`` input
  330. is treated as ASCII.
  331. :returns: The U-label as a Unicode string.
  332. :raises IDNAError: If the label is malformed or fails validation.
  333. """
  334. if len(label) > _max_input_length:
  335. raise IDNAError("Label too long")
  336. if not isinstance(label, (bytes, bytearray)):
  337. try:
  338. label_bytes = label.encode("ascii")
  339. except UnicodeEncodeError:
  340. check_label(label)
  341. return label
  342. else:
  343. label_bytes = bytes(label)
  344. label_bytes = label_bytes.lower()
  345. if label_bytes.startswith(_alabel_prefix):
  346. label_bytes = label_bytes[len(_alabel_prefix) :]
  347. if not label_bytes:
  348. raise IDNAError("Malformed A-label, no Punycode eligible content found")
  349. if label_bytes.endswith(b"-"):
  350. raise IDNAError("A-label must not end with a hyphen")
  351. else:
  352. check_label(label_bytes)
  353. return label_bytes.decode("ascii")
  354. try:
  355. label = label_bytes.decode("punycode")
  356. except UnicodeError as err:
  357. raise IDNAError("Invalid A-label") from err
  358. check_label(label)
  359. return label
  360. def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
  361. """Apply the UTS #46 character mapping to a domain string.
  362. Implements the mapping table from `UTS #46 §4
  363. <https://www.unicode.org/reports/tr46/>`_: each character is kept,
  364. replaced, or rejected based on its status (``V``, ``M``, ``D``, ``3``,
  365. ``I``). The result is returned in Normalisation Form C.
  366. :param domain: The full domain name to remap.
  367. :param std3_rules: If ``True``, apply the stricter STD3 ASCII rules
  368. (status ``3`` codepoints raise instead of being kept or mapped).
  369. :param transitional: If ``True``, use transitional processing (status
  370. ``D`` codepoints are mapped instead of kept). Transitional
  371. processing has been removed from UTS #46 and this option is
  372. retained only for backwards compatibility.
  373. :returns: The remapped domain, in Normalisation Form C.
  374. :raises InvalidCodepoint: If the domain contains a disallowed
  375. codepoint under the chosen rules.
  376. :raises IDNAError: If ``domain`` exceeds the defensive input length limit.
  377. """
  378. if len(domain) > _max_input_length:
  379. raise IDNAError("Domain too long")
  380. from .uts46data import uts46_replacements, uts46_starts, uts46_statuses
  381. output = ""
  382. for pos, char in enumerate(domain):
  383. code_point = ord(char)
  384. i = code_point if code_point < 256 else bisect.bisect_right(uts46_starts, code_point) - 1
  385. status = chr(uts46_statuses[i])
  386. replacement: Optional[str] = uts46_replacements[i]
  387. # UTS #46 §4: V is always valid, D is deviation (kept unless transitional),
  388. # 3 is disallowed-STD3 (kept unmapped if std3_rules is off and no mapping).
  389. keep_as_is = (
  390. status == "V" or (status == "D" and not transitional) or (status == "3" and not std3_rules and replacement is None)
  391. )
  392. # M is mapped, 3-with-replacement and transitional D fall through to the
  393. # same replacement output path.
  394. use_replacement = replacement is not None and (
  395. status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)
  396. )
  397. if keep_as_is:
  398. output += char
  399. elif use_replacement:
  400. assert replacement is not None # narrowed by use_replacement
  401. output += replacement
  402. elif status == "I":
  403. continue
  404. else:
  405. raise InvalidCodepoint(f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {domain!r}")
  406. return unicodedata.normalize("NFC", output)
  407. def encode(
  408. s: Union[str, bytes, bytearray],
  409. strict: bool = False,
  410. uts46: bool = False,
  411. std3_rules: bool = False,
  412. transitional: bool = False,
  413. ) -> bytes:
  414. """Encode a Unicode domain name into its ASCII (A-label) form.
  415. Splits the input on label separators (only ``U+002E`` if ``strict`` is
  416. set; otherwise also IDEOGRAPHIC FULL STOP ``U+3002``, FULLWIDTH FULL
  417. STOP ``U+FF0E``, and HALFWIDTH IDEOGRAPHIC FULL STOP ``U+FF61``),
  418. encodes each label with :func:`alabel`, and rejoins them with ``.``.
  419. Optionally pre-processes the input through :func:`uts46_remap`.
  420. :param s: The domain name to encode.
  421. :param strict: If ``True``, only ``U+002E`` is recognised as a label
  422. separator.
  423. :param uts46: If ``True``, apply UTS #46 mapping before encoding.
  424. :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is
  425. ``True``.
  426. :param transitional: Forwarded to :func:`uts46_remap` when ``uts46``
  427. is ``True``. Deprecated: emits a :class:`DeprecationWarning` and
  428. will be removed in a future version.
  429. :returns: The encoded domain as ASCII :class:`bytes`.
  430. :raises IDNAError: If the domain is empty, contains an invalid label,
  431. or exceeds the maximum domain length.
  432. """
  433. if transitional:
  434. warnings.warn(
  435. "Transitional processing has been removed from UTS #46. "
  436. "The transitional argument will be removed in a future version.",
  437. DeprecationWarning,
  438. stacklevel=2,
  439. )
  440. if not isinstance(s, str):
  441. try:
  442. s = str(s, "ascii")
  443. except (UnicodeDecodeError, TypeError) as err:
  444. raise IDNAError("should pass a unicode string to the function rather than a byte string.") from err
  445. if len(s) > _max_input_length:
  446. raise IDNAError("Domain too long")
  447. if uts46:
  448. s = uts46_remap(s, std3_rules, transitional)
  449. # Reject inputs that exceed the maximum DNS domain length up-front
  450. # to avoid expensive computation on long inputs.
  451. if not valid_string_length(s, trailing_dot=True):
  452. raise IDNAError("Domain too long")
  453. trailing_dot = False
  454. result = []
  455. labels = s.split(".") if strict else _unicode_dots_re.split(s)
  456. if not labels or labels == [""]:
  457. raise IDNAError("Empty domain")
  458. if labels[-1] == "":
  459. del labels[-1]
  460. trailing_dot = True
  461. for label in labels:
  462. s = alabel(label)
  463. if s:
  464. result.append(s)
  465. else:
  466. raise IDNAError("Empty label")
  467. if trailing_dot:
  468. result.append(b"")
  469. s = b".".join(result)
  470. if not valid_string_length(s, trailing_dot):
  471. raise IDNAError("Domain too long")
  472. return s
  473. def decode(
  474. s: Union[str, bytes, bytearray],
  475. strict: bool = False,
  476. uts46: bool = False,
  477. std3_rules: bool = False,
  478. display: bool = False,
  479. ) -> str:
  480. """Decode an A-label-encoded domain name back to Unicode.
  481. Splits the input on label separators (see :func:`encode` for the
  482. rules), decodes each label with :func:`ulabel`, and rejoins them
  483. with ``.``. Optionally pre-processes the input through
  484. :func:`uts46_remap`.
  485. :param s: The domain name to decode.
  486. :param strict: If ``True``, only ``U+002E`` is recognised as a label
  487. separator.
  488. :param uts46: If ``True``, apply UTS #46 mapping before decoding.
  489. :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is
  490. ``True``.
  491. :param display: If ``True``, any ``xn--`` label that fails IDNA
  492. validation is passed through unchanged (lowercased) rather than
  493. aborting the whole call. Intended for "decode for display"
  494. consumers (e.g. URL libraries, HTTP clients) that want to show
  495. the user the label as it appears on the wire when it cannot be
  496. rendered as Unicode. Matches the per-label recovery prescribed
  497. by UTS #46 §4 and the WHATWG URL "domain to Unicode" algorithm.
  498. :returns: The decoded domain as a Unicode string.
  499. :raises IDNAError: If the input is not valid ASCII, contains an
  500. invalid label, or is empty.
  501. """
  502. if not isinstance(s, str):
  503. try:
  504. s = str(s, "ascii")
  505. except (UnicodeDecodeError, TypeError) as err:
  506. raise IDNAError("Invalid ASCII in A-label") from err
  507. if len(s) > _max_input_length:
  508. raise IDNAError("Domain too long")
  509. if uts46:
  510. s = uts46_remap(s, std3_rules, False)
  511. # Reject inputs that exceed the maximum DNS domain length up-front
  512. # to avoid expensive computation on long inputs.
  513. if not valid_string_length(s, trailing_dot=True):
  514. raise IDNAError("Domain too long")
  515. trailing_dot = False
  516. result = []
  517. labels = s.split(".") if strict else _unicode_dots_re.split(s)
  518. if not labels or labels == [""]:
  519. raise IDNAError("Empty domain")
  520. if not labels[-1]:
  521. del labels[-1]
  522. trailing_dot = True
  523. for label in labels:
  524. try:
  525. u = ulabel(label)
  526. except IDNAError:
  527. if display and label[:4].lower() == "xn--":
  528. u = label.lower()
  529. else:
  530. raise
  531. if u:
  532. result.append(u)
  533. else:
  534. raise IDNAError("Empty label")
  535. if trailing_dot:
  536. result.append("")
  537. return ".".join(result)