core.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. from __future__ import annotations
  2. import bisect
  3. import re
  4. import unicodedata
  5. import warnings
  6. from typing import Literal
  7. from . import idnadata
  8. from .intranges import intranges_contain
  9. _virama_combining_class = 9
  10. _alabel_prefix = b"xn--"
  11. _max_input_length = 1024
  12. _STATUS_VALID, _STATUS_MAPPED, _STATUS_DEVIATION, _STATUS_IGNORED = b"VMDI"
  13. _unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]")
  14. _std3_disallowed_re = re.compile("[\x00-\x2c\x2f\x3a-\x40A-Z\x5b-\x60\x7b-\x7f]")
  15. _bidi_rtl_first = frozenset({"R", "AL"})
  16. _bidi_rtl_categories = frozenset({"R", "AL", "AN"})
  17. _bidi_rtl_allowed = frozenset({"R", "AL", "AN", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"})
  18. _bidi_rtl_valid_ending = frozenset({"R", "AL", "EN", "AN"})
  19. _bidi_rtl_numeric = frozenset({"AN", "EN"})
  20. _bidi_ltr_allowed = frozenset({"L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"})
  21. _bidi_ltr_valid_ending = frozenset({"L", "EN"})
  22. _bidi_joiner_l_or_d = frozenset({"L", "D"})
  23. _bidi_joiner_r_or_d = frozenset({"R", "D"})
  24. def _joining_type(cp: int) -> str | None:
  25. for jt, ranges in idnadata.joining_types.items():
  26. if intranges_contain(cp, ranges):
  27. return jt
  28. return None
  29. # Machine-readable identifiers for the rule an :class:`IDNAError` reports.
  30. # These strings are stable and documented; exception message wording is not.
  31. _ErrorCode = Literal[
  32. "input_too_long",
  33. "label_too_long",
  34. "domain_too_long",
  35. "empty_label",
  36. "empty_domain",
  37. "not_nfc",
  38. "hyphen_3_4",
  39. "hyphen_start_end",
  40. "leading_combiner",
  41. "disallowed_codepoint",
  42. "contextj",
  43. "contexto",
  44. "unknown_codepoint",
  45. "bidi_rule_1",
  46. "bidi_rule_2",
  47. "bidi_rule_3",
  48. "bidi_rule_4",
  49. "bidi_rule_5",
  50. "bidi_rule_6",
  51. "bidi_unknown_direction",
  52. "invalid_alabel",
  53. "non_canonical_alabel",
  54. "invalid_ascii",
  55. "invalid_utf8",
  56. "uts46_disallowed",
  57. "uts46_std3",
  58. "unsupported_errors",
  59. ]
  60. class IDNAError(UnicodeError):
  61. """Base exception for all IDNA-encoding related problems.
  62. ``str(err)`` is a human-readable description of the failure. The
  63. exception also carries machine-readable attributes so callers do not
  64. need to parse the message:
  65. * ``code`` -- a short, stable identifier for the rule that failed, such
  66. as ``"disallowed_codepoint"`` or ``"bidi_rule_2"``; the full list is
  67. documented in the README. Message wording, by contrast, may change
  68. between releases.
  69. * ``text`` -- the label (or, for UTS #46 processing, the domain) that
  70. was being validated;
  71. * ``codepoint`` -- the offending codepoint, as an ``int``;
  72. * ``position`` -- the 1-based index of the offending character within
  73. ``text``, matching the position quoted in the message.
  74. Each is ``None`` when it does not apply.
  75. """
  76. code: str | None
  77. text: str | None
  78. codepoint: int | None
  79. position: int | None
  80. def __init__(
  81. self,
  82. *args: object,
  83. code: _ErrorCode | None = None,
  84. text: str | None = None,
  85. codepoint: int | None = None,
  86. position: int | None = None,
  87. ) -> None:
  88. super().__init__(*args)
  89. self.code = code
  90. self.text = text
  91. self.codepoint = codepoint
  92. self.position = position
  93. class IDNABidiError(IDNAError):
  94. """Exception when bidirectional requirements are not satisfied"""
  95. class InvalidCodepoint(IDNAError):
  96. """Exception when a disallowed or unallocated codepoint is used"""
  97. class InvalidCodepointContext(IDNAError):
  98. """Exception when the codepoint is not valid in the context it is used"""
  99. def _combining_class(cp: int) -> int:
  100. v = unicodedata.combining(chr(cp))
  101. if v == 0 and not unicodedata.name(chr(cp)):
  102. raise ValueError("Unknown character in unicodedata")
  103. return v
  104. def _is_script(cp: str, script: str) -> bool:
  105. return intranges_contain(ord(cp), idnadata.scripts[script])
  106. def _punycode(s: str) -> bytes:
  107. return s.encode("punycode")
  108. def _unot(s: int) -> str:
  109. return f"U+{s:04X}"
  110. def valid_label_length(label: bytes | str) -> bool:
  111. """Check that a label does not exceed the maximum permitted length.
  112. Per :rfc:`1035` (and :rfc:`5891` §4.2.4) a DNS label must not exceed
  113. 63 octets. The argument may be either a :class:`str` (a U-label, where
  114. length is measured in characters) or :class:`bytes` (an A-label, where
  115. length is measured in octets).
  116. :param label: The label to check.
  117. :returns: ``True`` if the label is within the length limit, otherwise
  118. ``False``.
  119. """
  120. return len(label) <= 63
  121. def valid_string_length(domain: bytes | str, trailing_dot: bool) -> bool:
  122. """Check that a full domain name does not exceed the maximum length.
  123. Per :rfc:`1035`, a domain name is limited to 253 octets when no trailing
  124. dot is present, or 254 octets when one is included.
  125. :param domain: The full (possibly multi-label) domain name.
  126. :param trailing_dot: ``True`` if ``domain`` includes a trailing ``.``.
  127. :returns: ``True`` if the domain is within the length limit, otherwise
  128. ``False``.
  129. """
  130. return len(domain) <= (254 if trailing_dot else 253)
  131. def check_bidi(label: str, check_ltr: bool = False) -> bool:
  132. """Validate the Bidi Rule from :rfc:`5893` for a single label.
  133. The Bidi Rule constrains how bidirectional characters (Hebrew, Arabic,
  134. etc.) may appear within a label. By default the check is only applied
  135. when the label contains at least one right-to-left character (Unicode
  136. bidirectional categories ``R``, ``AL``, or ``AN``); set ``check_ltr``
  137. to ``True`` to apply it to LTR-only labels as well.
  138. :param label: The label to validate, as a Unicode string.
  139. :param check_ltr: If ``True``, apply the rules even when the label
  140. contains no RTL characters.
  141. :returns: ``True`` if the label satisfies the Bidi Rule.
  142. :raises IDNABidiError: If any of Bidi Rule conditions 1-6 are violated,
  143. or if the directional category of a codepoint cannot be determined.
  144. """
  145. if len(label) > _max_input_length:
  146. raise IDNAError("Label too long", code="input_too_long")
  147. # Bidi rules should only be applied if string contains RTL characters
  148. bidi_label = False
  149. for idx, cp in enumerate(label, 1):
  150. direction = unicodedata.bidirectional(cp)
  151. if direction == "":
  152. # String likely comes from a newer version of Unicode
  153. raise IDNABidiError(
  154. f"Unknown directionality in label {label!r} at position {idx}",
  155. code="bidi_unknown_direction",
  156. text=label,
  157. codepoint=ord(cp),
  158. position=idx,
  159. )
  160. if direction in _bidi_rtl_categories:
  161. bidi_label = True
  162. if not bidi_label and not check_ltr:
  163. return True
  164. # Bidi rule 1
  165. direction = unicodedata.bidirectional(label[0])
  166. if direction in _bidi_rtl_first:
  167. rtl = True
  168. elif direction == "L":
  169. rtl = False
  170. else:
  171. raise IDNABidiError(
  172. f"First codepoint in label {label!r} must be directionality L, R or AL",
  173. code="bidi_rule_1",
  174. text=label,
  175. codepoint=ord(label[0]),
  176. position=1,
  177. )
  178. valid_ending = False
  179. ending_idx = 1
  180. number_type: str | None = None
  181. for idx, cp in enumerate(label, 1):
  182. direction = unicodedata.bidirectional(cp)
  183. if rtl:
  184. # Bidi rule 2
  185. if direction not in _bidi_rtl_allowed:
  186. raise IDNABidiError(
  187. f"Invalid direction for codepoint at position {idx} in a right-to-left label",
  188. code="bidi_rule_2",
  189. text=label,
  190. codepoint=ord(cp),
  191. position=idx,
  192. )
  193. # Bidi rule 3
  194. if direction in _bidi_rtl_valid_ending:
  195. valid_ending = True
  196. ending_idx = idx
  197. elif direction != "NSM":
  198. valid_ending = False
  199. ending_idx = idx
  200. # Bidi rule 4
  201. if direction in _bidi_rtl_numeric:
  202. if not number_type:
  203. number_type = direction
  204. elif number_type != direction:
  205. raise IDNABidiError(
  206. "Can not mix numeral types in a right-to-left label",
  207. code="bidi_rule_4",
  208. text=label,
  209. codepoint=ord(cp),
  210. position=idx,
  211. )
  212. else:
  213. # Bidi rule 5
  214. if direction not in _bidi_ltr_allowed:
  215. raise IDNABidiError(
  216. f"Invalid direction for codepoint at position {idx} in a left-to-right label",
  217. code="bidi_rule_5",
  218. text=label,
  219. codepoint=ord(cp),
  220. position=idx,
  221. )
  222. # Bidi rule 6
  223. if direction in _bidi_ltr_valid_ending:
  224. valid_ending = True
  225. ending_idx = idx
  226. elif direction != "NSM":
  227. valid_ending = False
  228. ending_idx = idx
  229. if not valid_ending:
  230. # Rules 3 and 6 concern the last character that is not a
  231. # non-spacing mark, which is what ``ending_idx`` tracks.
  232. raise IDNABidiError(
  233. "Label ends with illegal codepoint directionality",
  234. code="bidi_rule_3" if rtl else "bidi_rule_6",
  235. text=label,
  236. codepoint=ord(label[ending_idx - 1]),
  237. position=ending_idx,
  238. )
  239. return True
  240. def check_initial_combiner(label: str) -> bool:
  241. """Reject labels that begin with a combining mark.
  242. Per :rfc:`5891` §4.2.3.2 a label must not start with a character of
  243. Unicode general category ``M`` (Mark).
  244. :param label: The label to check.
  245. :returns: ``True`` if the first character is not a combining mark.
  246. :raises IDNAError: If the label begins with a combining character.
  247. """
  248. if label and unicodedata.category(label[0])[0] == "M":
  249. raise IDNAError(
  250. "Label begins with an illegal combining character",
  251. code="leading_combiner",
  252. text=label,
  253. codepoint=ord(label[0]),
  254. position=1,
  255. )
  256. return True
  257. def check_hyphen_ok(label: str) -> bool:
  258. """Validate the hyphen restrictions for a label.
  259. Per :rfc:`5891` §4.2.3.1 a label must not start or end with a hyphen
  260. (``U+002D``), and must not have hyphens in both the third and fourth
  261. positions (the prefix reserved for A-labels).
  262. :param label: The label to check.
  263. :returns: ``True`` if the hyphen restrictions are satisfied.
  264. :raises IDNAError: If any of the hyphen restrictions are violated.
  265. """
  266. if label[2:4] == "--":
  267. raise IDNAError("Label has disallowed hyphens in 3rd and 4th position", code="hyphen_3_4")
  268. if label.startswith("-") or label.endswith("-"):
  269. raise IDNAError("Label must not start or end with a hyphen", code="hyphen_start_end")
  270. return True
  271. def check_nfc(label: str) -> None:
  272. """Require that a label is in Unicode Normalization Form C.
  273. :param label: The label to check.
  274. :raises IDNAError: If ``label`` differs from its NFC normalisation.
  275. """
  276. if len(label) > _max_input_length:
  277. raise IDNAError("Label too long", code="input_too_long")
  278. if unicodedata.normalize("NFC", label) != label:
  279. raise IDNAError("Label must be in Normalization Form C", code="not_nfc")
  280. def valid_contextj(label: str, pos: int) -> bool:
  281. """Validate the CONTEXTJ rules from :rfc:`5892` Appendix A.
  282. These rules govern the contextual use of the joiner codepoints
  283. ``U+200C`` (ZERO WIDTH NON-JOINER, Appendix A.1) and ``U+200D``
  284. (ZERO WIDTH JOINER, Appendix A.2) within a label.
  285. :param label: The label containing the codepoint.
  286. :param pos: Index of the joiner codepoint within ``label``.
  287. :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTJ
  288. rule, ``False`` otherwise (including when the codepoint at
  289. ``pos`` is not a recognised joiner).
  290. :raises ValueError: If an adjacent codepoint has no Unicode name when
  291. determining its combining class.
  292. :raises IDNAError: If ``label`` exceeds the defensive input length limit.
  293. """
  294. if len(label) > _max_input_length:
  295. raise IDNAError("Label too long", code="input_too_long")
  296. cp_value = ord(label[pos])
  297. if cp_value == 0x200C:
  298. if pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class:
  299. return True
  300. ok = False
  301. for i in range(pos - 1, -1, -1):
  302. joining_type = _joining_type(ord(label[i]))
  303. if joining_type == "T":
  304. continue
  305. if joining_type in _bidi_joiner_l_or_d:
  306. ok = True
  307. break
  308. break
  309. if not ok:
  310. return False
  311. ok = False
  312. for i in range(pos + 1, len(label)):
  313. joining_type = _joining_type(ord(label[i]))
  314. if joining_type == "T":
  315. continue
  316. if joining_type in _bidi_joiner_r_or_d:
  317. ok = True
  318. break
  319. break
  320. return ok
  321. if cp_value == 0x200D:
  322. return pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class
  323. return False
  324. def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
  325. """Validate the CONTEXTO rules from :rfc:`5892` Appendix A.
  326. Covers the contextual rules for codepoints such as MIDDLE DOT
  327. (``U+00B7``), Greek lower numeral sign, Hebrew punctuation, Katakana
  328. middle dot, and the Arabic-Indic / Extended Arabic-Indic digit ranges.
  329. :param label: The label containing the codepoint.
  330. :param pos: Index of the codepoint within ``label``.
  331. :param exception: Reserved for forward compatibility; currently unused.
  332. :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTO
  333. rule, ``False`` otherwise (including when the codepoint is not a
  334. recognised CONTEXTO codepoint).
  335. :raises IDNAError: If ``label`` exceeds the defensive input length limit.
  336. """
  337. if len(label) > _max_input_length:
  338. raise IDNAError("Label too long", code="input_too_long")
  339. cp_value = ord(label[pos])
  340. if cp_value == 0x00B7:
  341. return 0 < pos < len(label) - 1 and ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C
  342. if cp_value == 0x0375:
  343. if pos < len(label) - 1 and len(label) > 1:
  344. return _is_script(label[pos + 1], "Greek")
  345. return False
  346. if cp_value in {0x05F3, 0x05F4}:
  347. if pos > 0:
  348. return _is_script(label[pos - 1], "Hebrew")
  349. return False
  350. if cp_value == 0x30FB:
  351. for cp in label:
  352. if cp == "\u30fb":
  353. continue
  354. if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"):
  355. return True
  356. return False
  357. if 0x660 <= cp_value <= 0x669:
  358. return not any(0x6F0 <= ord(cp) <= 0x06F9 for cp in label)
  359. if 0x6F0 <= cp_value <= 0x6F9:
  360. return not any(0x660 <= ord(cp) <= 0x0669 for cp in label)
  361. return False
  362. def check_label(label: str | bytes | bytearray) -> None:
  363. """Run the full set of IDNA 2008 validity checks on a single label.
  364. Applies, in order: NFC normalisation (:func:`check_nfc`), hyphen
  365. restrictions (:func:`check_hyphen_ok`), the no-leading-combiner rule
  366. (:func:`check_initial_combiner`), per-codepoint validity (PVALID,
  367. CONTEXTJ, CONTEXTO classes from :rfc:`5892`), and the Bidi Rule
  368. (:func:`check_bidi`).
  369. :param label: The label to validate. ``bytes`` or ``bytearray`` input
  370. is decoded as UTF-8 first.
  371. :raises IDNAError: If the label is empty or fails a structural rule.
  372. :raises InvalidCodepoint: If the label contains a DISALLOWED or
  373. UNASSIGNED codepoint.
  374. :raises InvalidCodepointContext: If a CONTEXTJ or CONTEXTO codepoint
  375. is not valid in its context.
  376. :raises IDNABidiError: If the Bidi Rule is violated.
  377. """
  378. if len(label) > _max_input_length:
  379. raise IDNAError("Label too long", code="input_too_long")
  380. if isinstance(label, (bytes, bytearray)):
  381. try:
  382. label = label.decode("utf-8")
  383. except UnicodeDecodeError as err:
  384. raise IDNAError("Invalid UTF-8 in label", code="invalid_utf8") from err
  385. if len(label) == 0:
  386. raise IDNAError("Empty Label", code="empty_label")
  387. # Check against the domain length rather than the label length to
  388. # support some UTS #46 use cases, while still bounding the work done
  389. # by the label contextual rules below.
  390. if not valid_string_length(label, trailing_dot=True):
  391. raise IDNAError("Label too long", code="label_too_long")
  392. check_nfc(label)
  393. check_hyphen_ok(label)
  394. check_initial_combiner(label)
  395. for pos, cp in enumerate(label):
  396. cp_value = ord(cp)
  397. if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]):
  398. continue
  399. if intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]):
  400. try:
  401. contextj_ok = valid_contextj(label, pos)
  402. except ValueError as err:
  403. raise IDNAError(
  404. f"Unknown codepoint adjacent to joiner {_unot(cp_value)} at position {pos + 1} in {label!r}",
  405. code="unknown_codepoint",
  406. text=label,
  407. codepoint=cp_value,
  408. position=pos + 1,
  409. ) from err
  410. if not contextj_ok:
  411. raise InvalidCodepointContext(
  412. f"Joiner {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}",
  413. code="contextj",
  414. text=label,
  415. codepoint=cp_value,
  416. position=pos + 1,
  417. )
  418. elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]):
  419. if not valid_contexto(label, pos):
  420. raise InvalidCodepointContext(
  421. f"Codepoint {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}",
  422. code="contexto",
  423. text=label,
  424. codepoint=cp_value,
  425. position=pos + 1,
  426. )
  427. else:
  428. raise InvalidCodepoint(
  429. f"Codepoint {_unot(cp_value)} at position {pos + 1} of {label!r} not allowed",
  430. code="disallowed_codepoint",
  431. text=label,
  432. codepoint=cp_value,
  433. position=pos + 1,
  434. )
  435. check_bidi(label)
  436. def alabel(label: str) -> bytes:
  437. """Convert a single U-label into its A-label form.
  438. The result is the ASCII-Compatible Encoding (ACE) form per :rfc:`5891`
  439. §4: the label is validated, Punycode-encoded, and prefixed with
  440. ``xn--``. Pure ASCII labels that are already valid IDNA labels are
  441. returned unchanged (as :class:`bytes`).
  442. :param label: The label to convert, as a Unicode string.
  443. :returns: The A-label as ASCII-encoded :class:`bytes`.
  444. :raises IDNAError: If the label is invalid or the resulting A-label
  445. exceeds 63 octets.
  446. """
  447. if len(label) > _max_input_length:
  448. raise IDNAError("Label too long", code="input_too_long")
  449. try:
  450. label_bytes = label.encode("ascii")
  451. except UnicodeEncodeError:
  452. pass
  453. else:
  454. ulabel(label_bytes)
  455. if not valid_label_length(label_bytes):
  456. raise IDNAError("Label too long", code="label_too_long")
  457. return label_bytes
  458. check_label(label)
  459. label_bytes = _alabel_prefix + _punycode(label)
  460. if not valid_label_length(label_bytes):
  461. raise IDNAError("Label too long", code="label_too_long")
  462. return label_bytes
  463. def ulabel(label: str | bytes | bytearray) -> str:
  464. """Convert a single A-label into its U-label form.
  465. Performs the inverse of :func:`alabel`: an ``xn--``-prefixed label is
  466. Punycode-decoded and validated, and is rejected unless it is the
  467. canonical A-label for the decoded U-label (:rfc:`5891` §5.3). Labels
  468. that are already Unicode (or plain ASCII without the ACE prefix) are
  469. validated and returned as a Unicode string.
  470. :param label: The label to convert. ``bytes`` or ``bytearray`` input
  471. is treated as ASCII.
  472. :returns: The U-label as a Unicode string.
  473. :raises IDNAError: If the label is malformed or fails validation.
  474. """
  475. if len(label) > _max_input_length:
  476. raise IDNAError("Label too long", code="input_too_long")
  477. if not isinstance(label, (bytes, bytearray)):
  478. try:
  479. label_bytes = label.encode("ascii")
  480. except UnicodeEncodeError:
  481. check_label(label)
  482. return label
  483. else:
  484. label_bytes = bytes(label)
  485. if not label_bytes.isascii():
  486. raise IDNAError("Invalid ASCII in A-label", code="invalid_ascii")
  487. label_bytes = label_bytes.lower()
  488. if label_bytes.startswith(_alabel_prefix):
  489. label_bytes = label_bytes[len(_alabel_prefix) :]
  490. if not label_bytes:
  491. raise IDNAError("Malformed A-label, no Punycode eligible content found", code="invalid_alabel")
  492. if label_bytes.endswith(b"-"):
  493. raise IDNAError("A-label must not end with a hyphen", code="invalid_alabel")
  494. else:
  495. check_label(label_bytes)
  496. return label_bytes.decode("ascii")
  497. try:
  498. label = label_bytes.decode("punycode")
  499. except UnicodeError as err:
  500. raise IDNAError("Invalid A-label", code="invalid_alabel") from err
  501. # RFC 5891 §5.3: the label is rejected unless re-encoding the decoded
  502. # form reproduces the (lowercased) input. This catches "fake A-labels"
  503. # (RFC 5890 §2.3.2.1) such as ``xn---bbk``, a non-canonical Punycode
  504. # spelling of ``xn--bbk`` that would otherwise decode to the same
  505. # U-label and so display identically to a different wire-format name.
  506. if _punycode(label) != label_bytes:
  507. raise IDNAError("A-label is not the canonical Punycode encoding of its U-label", code="non_canonical_alabel")
  508. check_label(label)
  509. return label
  510. def _check_std3(text: str, domain: str, offset: int) -> None:
  511. """Raise if ``text``, a slice of ``domain`` starting at ``offset`` that
  512. UTS #46 mapping left unchanged, contains an ASCII character disallowed
  513. under ``UseSTD3ASCIIRules``."""
  514. match = _std3_disallowed_re.search(text)
  515. if match:
  516. codepoint = ord(match.group())
  517. position = offset + match.start() + 1
  518. raise InvalidCodepoint(
  519. f"Codepoint {_unot(codepoint)} not allowed at position {position} in {domain!r}",
  520. code="uts46_std3",
  521. text=domain,
  522. codepoint=codepoint,
  523. position=position,
  524. )
  525. def _warn_transitional() -> None:
  526. warnings.warn(
  527. "Transitional processing is deprecated in UTS #46 and has no effect. "
  528. "The transitional argument will be removed in a future version.",
  529. DeprecationWarning,
  530. stacklevel=3,
  531. )
  532. def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
  533. """Apply the UTS #46 character mapping to a domain string.
  534. Implements the mapping table from `UTS #46 §4
  535. <https://www.unicode.org/reports/tr46/>`_: each character is kept,
  536. replaced, or rejected based on its status (``V``, ``M``, ``D``,
  537. ``I``, ``X``). The result is returned in Normalisation Form C.
  538. :param domain: The full domain name to remap.
  539. :param std3_rules: If ``True``, apply UTS #46's ``UseSTD3ASCIIRules``:
  540. after mapping, any ASCII character other than a lowercase letter,
  541. digit, hyphen or the label separator ``.`` is rejected, whether it
  542. appeared in the input or was produced by a mapping (e.g. U+FF01
  543. FULLWIDTH EXCLAMATION MARK maps to ``!``). If ``False``, such
  544. characters are passed through.
  545. :param transitional: Deprecated and ignored. UTS #46 deprecated
  546. transitional processing in Unicode 15.1 and deviation (status
  547. ``D``) codepoints are now always kept, so this has no effect
  548. beyond emitting a :class:`DeprecationWarning`. It will be removed
  549. in a future version.
  550. :returns: The remapped domain, in Normalisation Form C.
  551. :raises InvalidCodepoint: If the domain contains a disallowed
  552. codepoint under the chosen rules.
  553. :raises IDNAError: If ``domain`` exceeds the defensive input length limit.
  554. """
  555. if transitional:
  556. _warn_transitional()
  557. if len(domain) > _max_input_length:
  558. raise IDNAError("Domain too long", code="input_too_long")
  559. if domain.isascii():
  560. # The only ASCII mapping in UTS #46 is upper- to lowercase, and
  561. # ASCII is invariant under NFC, so lowercasing is the whole job.
  562. result = domain.lower()
  563. if std3_rules:
  564. _check_std3(result, domain, 0)
  565. return result
  566. from .uts46data import uts46_replacements, uts46_starts, uts46_statuses
  567. # ``start`` marks the run of unchanged input not yet copied; a run is
  568. # only sliced out when a character must be replaced or dropped, so the
  569. # common no-change case makes no copy. STD3 is checked per output piece
  570. # to report a violation at its input position.
  571. output: list[str] = []
  572. start = 0
  573. for pos, char in enumerate(domain):
  574. code_point = ord(char)
  575. i = code_point if code_point < 256 else bisect.bisect_right(uts46_starts, code_point) - 1
  576. status = uts46_statuses[i]
  577. # UTS #46 §4: V valid, D deviation (kept), M mapped, I ignored,
  578. # anything else disallowed.
  579. if status == _STATUS_VALID:
  580. continue
  581. if status == _STATUS_MAPPED:
  582. replacement = uts46_replacements[i]
  583. elif status == _STATUS_DEVIATION:
  584. continue
  585. elif status == _STATUS_IGNORED:
  586. replacement = None
  587. else:
  588. raise InvalidCodepoint(
  589. f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {domain!r}",
  590. code="uts46_disallowed",
  591. text=domain,
  592. codepoint=code_point,
  593. position=pos + 1,
  594. )
  595. if start < pos:
  596. run = domain[start:pos]
  597. if std3_rules:
  598. _check_std3(run, domain, start)
  599. output.append(run)
  600. if replacement:
  601. if std3_rules and _std3_disallowed_re.search(replacement):
  602. raise InvalidCodepoint(
  603. f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {domain!r}",
  604. code="uts46_std3",
  605. text=domain,
  606. codepoint=code_point,
  607. position=pos + 1,
  608. )
  609. output.append(replacement)
  610. start = pos + 1
  611. if start == 0:
  612. if std3_rules:
  613. _check_std3(domain, domain, 0)
  614. return unicodedata.normalize("NFC", domain)
  615. tail = domain[start:]
  616. if std3_rules:
  617. _check_std3(tail, domain, start)
  618. output.append(tail)
  619. return unicodedata.normalize("NFC", "".join(output))
  620. def encode(
  621. s: str | bytes | bytearray,
  622. strict: bool = False,
  623. uts46: bool = False,
  624. std3_rules: bool = False,
  625. transitional: bool = False,
  626. ) -> bytes:
  627. """Encode a Unicode domain name into its ASCII (A-label) form.
  628. Splits the input on label separators (only ``U+002E`` if ``strict`` is
  629. set; otherwise also IDEOGRAPHIC FULL STOP ``U+3002``, FULLWIDTH FULL
  630. STOP ``U+FF0E``, and HALFWIDTH IDEOGRAPHIC FULL STOP ``U+FF61``),
  631. encodes each label with :func:`alabel`, and rejoins them with ``.``.
  632. Optionally pre-processes the input through :func:`uts46_remap`.
  633. :param s: The domain name to encode.
  634. :param strict: If ``True``, only ``U+002E`` is recognised as a label
  635. separator.
  636. :param uts46: If ``True``, apply UTS #46 mapping before encoding.
  637. :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is
  638. ``True``.
  639. :param transitional: Deprecated and ignored (see :func:`uts46_remap`):
  640. emits a :class:`DeprecationWarning` and will be removed in a
  641. future version.
  642. :returns: The encoded domain as ASCII :class:`bytes`.
  643. :raises IDNAError: If the domain is empty, contains an invalid label,
  644. or exceeds the maximum domain length.
  645. """
  646. if transitional:
  647. _warn_transitional()
  648. if not isinstance(s, str):
  649. try:
  650. s = str(s, "ascii")
  651. except (UnicodeDecodeError, TypeError) as err:
  652. raise IDNAError(
  653. "should pass a unicode string to the function rather than a byte string.", code="invalid_ascii"
  654. ) from err
  655. if len(s) > _max_input_length:
  656. raise IDNAError("Domain too long", code="input_too_long")
  657. if uts46:
  658. s = uts46_remap(s, std3_rules)
  659. if not valid_string_length(s, trailing_dot=True):
  660. raise IDNAError("Domain too long", code="domain_too_long")
  661. trailing_dot = False
  662. result = []
  663. labels = s.split(".") if strict else _unicode_dots_re.split(s)
  664. if not labels or labels == [""]:
  665. raise IDNAError("Empty domain", code="empty_domain")
  666. if labels[-1] == "":
  667. del labels[-1]
  668. trailing_dot = True
  669. for label in labels:
  670. s = alabel(label)
  671. if s:
  672. result.append(s)
  673. else:
  674. raise IDNAError("Empty label", code="empty_label")
  675. if trailing_dot:
  676. result.append(b"")
  677. s = b".".join(result)
  678. if not valid_string_length(s, trailing_dot):
  679. raise IDNAError("Domain too long", code="domain_too_long")
  680. return s
  681. def decode(
  682. s: str | bytes | bytearray,
  683. strict: bool = False,
  684. uts46: bool = False,
  685. std3_rules: bool = False,
  686. display: bool = False,
  687. ) -> str:
  688. """Decode an A-label-encoded domain name back to Unicode.
  689. Splits the input on label separators (see :func:`encode` for the
  690. rules), decodes each label with :func:`ulabel`, and rejoins them
  691. with ``.``. Optionally pre-processes the input through
  692. :func:`uts46_remap`.
  693. :param s: The domain name to decode.
  694. :param strict: If ``True``, only ``U+002E`` is recognised as a label
  695. separator.
  696. :param uts46: If ``True``, apply UTS #46 mapping before decoding.
  697. :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is
  698. ``True``.
  699. :param display: If ``True``, any ``xn--`` label that fails IDNA
  700. validation is passed through unchanged (lowercased) rather than
  701. aborting the whole call. Intended for "decode for display"
  702. consumers (e.g. URL libraries, HTTP clients) that want to show
  703. the user the label as it appears on the wire when it cannot be
  704. rendered as Unicode. Matches the per-label recovery prescribed
  705. by UTS #46 §4 and the WHATWG URL "domain to Unicode" algorithm.
  706. :returns: The decoded domain as a Unicode string.
  707. :raises IDNAError: If the input is not valid ASCII, contains an
  708. invalid label, or is empty.
  709. """
  710. if not isinstance(s, str):
  711. try:
  712. s = str(s, "ascii")
  713. except (UnicodeDecodeError, TypeError) as err:
  714. raise IDNAError("Invalid ASCII in A-label", code="invalid_ascii") from err
  715. if len(s) > _max_input_length:
  716. raise IDNAError("Domain too long", code="input_too_long")
  717. if uts46:
  718. s = uts46_remap(s, std3_rules, False)
  719. if not valid_string_length(s, trailing_dot=True):
  720. raise IDNAError("Domain too long", code="domain_too_long")
  721. trailing_dot = False
  722. result = []
  723. labels = s.split(".") if strict else _unicode_dots_re.split(s)
  724. if not labels or labels == [""]:
  725. raise IDNAError("Empty domain", code="empty_domain")
  726. if not labels[-1]:
  727. del labels[-1]
  728. trailing_dot = True
  729. for label in labels:
  730. try:
  731. u = ulabel(label)
  732. except IDNAError:
  733. if display and label[:4].lower() == "xn--":
  734. u = label.lower()
  735. else:
  736. raise
  737. if u:
  738. result.append(u)
  739. else:
  740. raise IDNAError("Empty label", code="empty_label")
  741. if trailing_dot:
  742. result.append("")
  743. return ".".join(result)