syntax.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. from .exceptions_types import EmailSyntaxError, ValidatedEmail
  2. from .rfc_constants import EMAIL_MAX_LENGTH, LOCAL_PART_MAX_LENGTH, DOMAIN_MAX_LENGTH, \
  3. DOT_ATOM_TEXT, DOT_ATOM_TEXT_INTL, ATEXT_RE, ATEXT_INTL_DOT_RE, ATEXT_HOSTNAME_INTL, QTEXT_INTL, \
  4. DNS_LABEL_LENGTH_LIMIT, DOT_ATOM_TEXT_HOSTNAME, DOMAIN_NAME_REGEX, DOMAIN_LITERAL_CHARS
  5. import re
  6. import unicodedata
  7. import idna # implements IDNA 2008; Python's codec is only IDNA 2003
  8. import ipaddress
  9. from typing import Optional, Tuple, TypedDict, Union
  10. def split_email(email: str) -> Tuple[Optional[str], str, str, bool]:
  11. # Return the display name, unescaped local part, and domain part
  12. # of the address, and whether the local part was quoted. If no
  13. # display name was present and angle brackets do not surround
  14. # the address, display name will be None; otherwise, it will be
  15. # set to the display name or the empty string if there were
  16. # angle brackets but no display name.
  17. # Typical email addresses have a single @-sign and no quote
  18. # characters, but the awkward "quoted string" local part form
  19. # (RFC 5321 4.1.2) allows @-signs and escaped quotes to appear
  20. # in the local part if the local part is quoted.
  21. # A `display name <addr>` format is also present in MIME messages
  22. # (RFC 5322 3.4) and this format is also often recognized in
  23. # mail UIs. It's not allowed in SMTP commands or in typical web
  24. # login forms, but parsing it has been requested, so it's done
  25. # here as a convenience. It's implemented in the spirit but not
  26. # the letter of RFC 5322 3.4 because MIME messages allow newlines
  27. # and comments as a part of the CFWS rule, but this is typically
  28. # not allowed in mail UIs (although comment syntax was requested
  29. # once too).
  30. #
  31. # Display names are either basic characters (the same basic characters
  32. # permitted in email addresses, but periods are not allowed and spaces
  33. # are allowed; see RFC 5322 Appendix A.1.2), or or a quoted string with
  34. # the same rules as a quoted local part. (Multiple quoted strings might
  35. # be allowed? Unclear.) Optional space (RFC 5322 3.4 CFWS) and then the
  36. # email address follows in angle brackets.
  37. #
  38. # An initial quote is ambiguous between starting a display name or
  39. # a quoted local part --- fun.
  40. #
  41. # We assume the input string is already stripped of leading and
  42. # trailing CFWS.
  43. def split_string_at_unquoted_special(text: str, specials: Tuple[str, ...]) -> Tuple[str, str]:
  44. # Split the string at the first character in specials (an @-sign
  45. # or left angle bracket) that does not occur within quotes and
  46. # is not followed by a Unicode combining character.
  47. # If no special character is found, raise an error.
  48. inside_quote = False
  49. escaped = False
  50. left_part = ""
  51. for i, c in enumerate(text):
  52. # < plus U+0338 (Combining Long Solidus Overlay) normalizes to
  53. # ≮ U+226E (Not Less-Than), and it would be confusing to treat
  54. # the < as the start of "<email>" syntax in that case. Liekwise,
  55. # if anything combines with an @ or ", we should probably not
  56. # treat it as a special character.
  57. if unicodedata.normalize("NFC", text[i:])[0] != c:
  58. left_part += c
  59. elif inside_quote:
  60. left_part += c
  61. if c == '\\' and not escaped:
  62. escaped = True
  63. elif c == '"' and not escaped:
  64. # The only way to exit the quote is an unescaped quote.
  65. inside_quote = False
  66. escaped = False
  67. else:
  68. escaped = False
  69. elif c == '"':
  70. left_part += c
  71. inside_quote = True
  72. elif c in specials:
  73. # When unquoted, stop before a special character.
  74. break
  75. else:
  76. left_part += c
  77. if len(left_part) == len(text):
  78. raise EmailSyntaxError("An email address must have an @-sign.")
  79. # The right part is whatever is left.
  80. right_part = text[len(left_part):]
  81. return left_part, right_part
  82. def unquote_quoted_string(text: str) -> Tuple[str, bool]:
  83. # Remove surrounding quotes and unescape escaped backslashes
  84. # and quotes. Escapes are parsed liberally. I think only
  85. # backslashes and quotes can be escaped but we'll allow anything
  86. # to be.
  87. quoted = False
  88. escaped = False
  89. value = ""
  90. for i, c in enumerate(text):
  91. if quoted:
  92. if escaped:
  93. value += c
  94. escaped = False
  95. elif c == '\\':
  96. escaped = True
  97. elif c == '"':
  98. if i != len(text) - 1:
  99. raise EmailSyntaxError("Extra character(s) found after close quote: "
  100. + ", ".join(safe_character_display(c) for c in text[i + 1:]))
  101. break
  102. else:
  103. value += c
  104. elif i == 0 and c == '"':
  105. quoted = True
  106. else:
  107. value += c
  108. return value, quoted
  109. # Split the string at the first unquoted @-sign or left angle bracket.
  110. left_part, right_part = split_string_at_unquoted_special(email, ("@", "<"))
  111. # If the right part starts with an angle bracket,
  112. # then the left part is a display name and the rest
  113. # of the right part up to the final right angle bracket
  114. # is the email address, .
  115. if right_part.startswith("<"):
  116. # Remove space between the display name and angle bracket.
  117. left_part = left_part.rstrip()
  118. # Unquote and unescape the display name.
  119. display_name, display_name_quoted = unquote_quoted_string(left_part)
  120. # Check that only basic characters are present in a
  121. # non-quoted display name.
  122. if not display_name_quoted:
  123. bad_chars = {
  124. safe_character_display(c)
  125. for c in display_name
  126. if (not ATEXT_RE.match(c) and c != ' ') or c == '.'
  127. }
  128. if bad_chars:
  129. raise EmailSyntaxError("The display name contains invalid characters when not quoted: " + ", ".join(sorted(bad_chars)) + ".")
  130. # Check for other unsafe characters.
  131. check_unsafe_chars(display_name, allow_space=True)
  132. # Check that the right part ends with an angle bracket
  133. # but allow spaces after it, I guess.
  134. if ">" not in right_part:
  135. raise EmailSyntaxError("An open angle bracket at the start of the email address has to be followed by a close angle bracket at the end.")
  136. right_part = right_part.rstrip(" ")
  137. if right_part[-1] != ">":
  138. raise EmailSyntaxError("There can't be anything after the email address.")
  139. # Remove the initial and trailing angle brackets.
  140. addr_spec = right_part[1:].rstrip(">")
  141. # Split the email address at the first unquoted @-sign.
  142. local_part, domain_part = split_string_at_unquoted_special(addr_spec, ("@",))
  143. # Otherwise there is no display name. The left part is the local
  144. # part and the right part is the domain.
  145. else:
  146. display_name = None
  147. local_part, domain_part = left_part, right_part
  148. if domain_part.startswith("@"):
  149. domain_part = domain_part[1:]
  150. # Unquote the local part if it is quoted.
  151. local_part, is_quoted_local_part = unquote_quoted_string(local_part)
  152. return display_name, local_part, domain_part, is_quoted_local_part
  153. def get_length_reason(addr: str, limit: int) -> str:
  154. """Helper function to return an error message related to invalid length."""
  155. diff = len(addr) - limit
  156. suffix = "s" if diff > 1 else ""
  157. return f"({diff} character{suffix} too many)"
  158. def safe_character_display(c: str) -> str:
  159. # Return safely displayable characters in quotes.
  160. if c == '\\':
  161. return f"\"{c}\"" # can't use repr because it escapes it
  162. if unicodedata.category(c)[0] in ("L", "N", "P", "S"):
  163. return repr(c)
  164. # Construct a hex string in case the unicode name doesn't exist.
  165. if ord(c) < 0xFFFF:
  166. h = f"U+{ord(c):04x}".upper()
  167. else:
  168. h = f"U+{ord(c):08x}".upper()
  169. # Return the character name or, if it has no name, the hex string.
  170. return unicodedata.name(c, h)
  171. class LocalPartValidationResult(TypedDict):
  172. local_part: str
  173. ascii_local_part: Optional[str]
  174. smtputf8: bool
  175. def validate_email_local_part(local: str, allow_smtputf8: bool = True, allow_empty_local: bool = False,
  176. quoted_local_part: bool = False) -> LocalPartValidationResult:
  177. """Validates the syntax of the local part of an email address."""
  178. if len(local) == 0:
  179. if not allow_empty_local:
  180. raise EmailSyntaxError("There must be something before the @-sign.")
  181. # The caller allows an empty local part. Useful for validating certain
  182. # Postfix aliases.
  183. return {
  184. "local_part": local,
  185. "ascii_local_part": local,
  186. "smtputf8": False,
  187. }
  188. # Check the length of the local part by counting characters.
  189. # (RFC 5321 4.5.3.1.1)
  190. # We're checking the number of characters here. If the local part
  191. # is ASCII-only, then that's the same as bytes (octets). If it's
  192. # internationalized, then the UTF-8 encoding may be longer, but
  193. # that may not be relevant. We will check the total address length
  194. # instead.
  195. if len(local) > LOCAL_PART_MAX_LENGTH:
  196. reason = get_length_reason(local, limit=LOCAL_PART_MAX_LENGTH)
  197. raise EmailSyntaxError(f"The email address is too long before the @-sign {reason}.")
  198. # Check the local part against the non-internationalized regular expression.
  199. # Most email addresses match this regex so it's probably fastest to check this first.
  200. # (RFC 5322 3.2.3)
  201. # All local parts matching the dot-atom rule are also valid as a quoted string
  202. # so if it was originally quoted (quoted_local_part is True) and this regex matches,
  203. # it's ok.
  204. # (RFC 5321 4.1.2 / RFC 5322 3.2.4).
  205. if DOT_ATOM_TEXT.match(local):
  206. # It's valid. And since it's just the permitted ASCII characters,
  207. # it's normalized and safe. If the local part was originally quoted,
  208. # the quoting was unnecessary and it'll be returned as normalized to
  209. # non-quoted form.
  210. # Return the local part and flag that SMTPUTF8 is not needed.
  211. return {
  212. "local_part": local,
  213. "ascii_local_part": local,
  214. "smtputf8": False,
  215. }
  216. # The local part failed the basic dot-atom check. Try the extended character set
  217. # for internationalized addresses. It's the same pattern but with additional
  218. # characters permitted.
  219. # RFC 6531 section 3.3.
  220. valid: Optional[str] = None
  221. requires_smtputf8 = False
  222. if DOT_ATOM_TEXT_INTL.match(local):
  223. # But international characters in the local part may not be permitted.
  224. if not allow_smtputf8:
  225. # Check for invalid characters against the non-internationalized
  226. # permitted character set.
  227. # (RFC 5322 3.2.3)
  228. bad_chars = {
  229. safe_character_display(c)
  230. for c in local
  231. if not ATEXT_RE.match(c)
  232. }
  233. if bad_chars:
  234. raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".")
  235. # Although the check above should always find something, fall back to this just in case.
  236. raise EmailSyntaxError("Internationalized characters before the @-sign are not supported.")
  237. # It's valid.
  238. valid = "dot-atom"
  239. requires_smtputf8 = True
  240. # There are no syntactic restrictions on quoted local parts, so if
  241. # it was originally quoted, it is probably valid. More characters
  242. # are allowed, like @-signs, spaces, and quotes, and there are no
  243. # restrictions on the placement of dots, as in dot-atom local parts.
  244. elif quoted_local_part:
  245. # Check for invalid characters in a quoted string local part.
  246. # (RFC 5321 4.1.2. RFC 5322 lists additional permitted *obsolete*
  247. # characters which are *not* allowed here. RFC 6531 section 3.3
  248. # extends the range to UTF8 strings.)
  249. bad_chars = {
  250. safe_character_display(c)
  251. for c in local
  252. if not QTEXT_INTL.match(c)
  253. }
  254. if bad_chars:
  255. raise EmailSyntaxError("The email address contains invalid characters in quotes before the @-sign: " + ", ".join(sorted(bad_chars)) + ".")
  256. # See if any characters are outside of the ASCII range.
  257. bad_chars = {
  258. safe_character_display(c)
  259. for c in local
  260. if not (32 <= ord(c) <= 126)
  261. }
  262. if bad_chars:
  263. requires_smtputf8 = True
  264. # International characters in the local part may not be permitted.
  265. if not allow_smtputf8:
  266. raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".")
  267. # It's valid.
  268. valid = "quoted"
  269. # If the local part matches the internationalized dot-atom form or was quoted,
  270. # perform additional checks for Unicode strings.
  271. if valid:
  272. # Check that the local part is a valid, safe, and sensible Unicode string.
  273. # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked
  274. # by DOT_ATOM_TEXT_INTL and QTEXT_INTL. Other characters may be permitted by the
  275. # email specs, but they may not be valid, safe, or sensible Unicode strings.
  276. # See the function for rationale.
  277. check_unsafe_chars(local, allow_space=(valid == "quoted"))
  278. # Try encoding to UTF-8. Failure is possible with some characters like
  279. # surrogate code points, but those are checked above. Still, we don't
  280. # want to have an unhandled exception later.
  281. try:
  282. local.encode("utf8")
  283. except ValueError as e:
  284. raise EmailSyntaxError("The email address contains an invalid character.") from e
  285. # If this address passes only by the quoted string form, re-quote it
  286. # and backslash-escape quotes and backslashes (removing any unnecessary
  287. # escapes). Per RFC 5321 4.1.2, "all quoted forms MUST be treated as equivalent,
  288. # and the sending system SHOULD transmit the form that uses the minimum quoting possible."
  289. if valid == "quoted":
  290. local = '"' + re.sub(r'(["\\])', r'\\\1', local) + '"'
  291. return {
  292. "local_part": local,
  293. "ascii_local_part": local if not requires_smtputf8 else None,
  294. "smtputf8": requires_smtputf8,
  295. }
  296. # It's not a valid local part. Let's find out why.
  297. # (Since quoted local parts are all valid or handled above, these checks
  298. # don't apply in those cases.)
  299. # Check for invalid characters.
  300. # (RFC 5322 3.2.3, plus RFC 6531 3.3)
  301. bad_chars = {
  302. safe_character_display(c)
  303. for c in local
  304. if not ATEXT_INTL_DOT_RE.match(c)
  305. }
  306. if bad_chars:
  307. raise EmailSyntaxError("The email address contains invalid characters before the @-sign: " + ", ".join(sorted(bad_chars)) + ".")
  308. # Check for dot errors imposted by the dot-atom rule.
  309. # (RFC 5322 3.2.3)
  310. check_dot_atom(local, 'An email address cannot start with a {}.', 'An email address cannot have a {} immediately before the @-sign.', is_hostname=False)
  311. # All of the reasons should already have been checked, but just in case
  312. # we have a fallback message.
  313. raise EmailSyntaxError("The email address contains invalid characters before the @-sign.")
  314. def check_unsafe_chars(s: str, allow_space: bool = False) -> None:
  315. # Check for unsafe characters or characters that would make the string
  316. # invalid or non-sensible Unicode.
  317. bad_chars = set()
  318. for i, c in enumerate(s):
  319. category = unicodedata.category(c)
  320. if category[0] in ("L", "N", "P", "S"):
  321. # Letters, numbers, punctuation, and symbols are permitted.
  322. pass
  323. elif category[0] == "M":
  324. # Combining character in first position would combine with something
  325. # outside of the email address if concatenated, so they are not safe.
  326. # We also check if this occurs after the @-sign, which would not be
  327. # sensible because it would modify the @-sign.
  328. if i == 0:
  329. bad_chars.add(c)
  330. elif category == "Zs":
  331. # Spaces outside of the ASCII range are not specifically disallowed in
  332. # internationalized addresses as far as I can tell, but they violate
  333. # the spirit of the non-internationalized specification that email
  334. # addresses do not contain ASCII spaces when not quoted. Excluding
  335. # ASCII spaces when not quoted is handled directly by the atom regex.
  336. #
  337. # In quoted-string local parts, spaces are explicitly permitted, and
  338. # the ASCII space has category Zs, so we must allow it here, and we'll
  339. # allow all Unicode spaces to be consistent.
  340. if not allow_space:
  341. bad_chars.add(c)
  342. elif category[0] == "Z":
  343. # The two line and paragraph separator characters (in categories Zl and Zp)
  344. # are not specifically disallowed in internationalized addresses
  345. # as far as I can tell, but they violate the spirit of the non-internationalized
  346. # specification that email addresses do not contain line breaks when not quoted.
  347. bad_chars.add(c)
  348. elif category[0] == "C":
  349. # Control, format, surrogate, private use, and unassigned code points (C)
  350. # are all unsafe in various ways. Control and format characters can affect
  351. # text rendering if the email address is concatenated with other text.
  352. # Bidirectional format characters are unsafe, even if used properly, because
  353. # they cause an email address to render as a different email address.
  354. # Private use characters do not make sense for publicly deliverable
  355. # email addresses.
  356. bad_chars.add(c)
  357. else:
  358. # All categories should be handled above, but in case there is something new
  359. # to the Unicode specification in the future, reject all other categories.
  360. bad_chars.add(c)
  361. if bad_chars:
  362. raise EmailSyntaxError("The email address contains unsafe characters: "
  363. + ", ".join(safe_character_display(c) for c in sorted(bad_chars)) + ".")
  364. def check_dot_atom(label: str, start_descr: str, end_descr: str, is_hostname: bool) -> None:
  365. # RFC 5322 3.2.3
  366. if label.endswith("."):
  367. raise EmailSyntaxError(end_descr.format("period"))
  368. if label.startswith("."):
  369. raise EmailSyntaxError(start_descr.format("period"))
  370. if ".." in label:
  371. raise EmailSyntaxError("An email address cannot have two periods in a row.")
  372. if is_hostname:
  373. # RFC 952
  374. if label.endswith("-"):
  375. raise EmailSyntaxError(end_descr.format("hyphen"))
  376. if label.startswith("-"):
  377. raise EmailSyntaxError(start_descr.format("hyphen"))
  378. if ".-" in label or "-." in label:
  379. raise EmailSyntaxError("An email address cannot have a period and a hyphen next to each other.")
  380. class DomainNameValidationResult(TypedDict):
  381. ascii_domain: str
  382. domain: str
  383. def validate_email_domain_name(domain: str, test_environment: bool = False, globally_deliverable: bool = True) -> DomainNameValidationResult:
  384. """Validates the syntax of the domain part of an email address."""
  385. # Check for invalid characters.
  386. # (RFC 952 plus RFC 6531 section 3.3 for internationalized addresses)
  387. bad_chars = {
  388. safe_character_display(c)
  389. for c in domain
  390. if not ATEXT_HOSTNAME_INTL.match(c)
  391. }
  392. if bad_chars:
  393. raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
  394. # Check for unsafe characters.
  395. # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked
  396. # by DOT_ATOM_TEXT_INTL. Other characters may be permitted by the email specs, but
  397. # they may not be valid, safe, or sensible Unicode strings.
  398. check_unsafe_chars(domain)
  399. # Perform UTS-46 normalization, which includes casefolding, NFC normalization,
  400. # and converting all label separators (the period/full stop, fullwidth full stop,
  401. # ideographic full stop, and halfwidth ideographic full stop) to regular dots.
  402. # It will also raise an exception if there is an invalid character in the input,
  403. # such as "⒈" which is invalid because it would expand to include a dot and
  404. # U+1FEF which normalizes to a backtick, which is not an allowed hostname character.
  405. # Since several characters *are* normalized to a dot, this has to come before
  406. # checks related to dots, like check_dot_atom which comes next.
  407. original_domain = domain
  408. try:
  409. domain = idna.uts46_remap(domain, std3_rules=False, transitional=False)
  410. except idna.IDNAError as e:
  411. raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).") from e
  412. # Check for invalid characters after Unicode normalization which are not caught
  413. # by uts46_remap (see tests for examples).
  414. bad_chars = {
  415. safe_character_display(c)
  416. for c in domain
  417. if not ATEXT_HOSTNAME_INTL.match(c)
  418. }
  419. if bad_chars:
  420. raise EmailSyntaxError("The part after the @-sign contains invalid characters after Unicode normalization: " + ", ".join(sorted(bad_chars)) + ".")
  421. # The domain part is made up dot-separated "labels." Each label must
  422. # have at least one character and cannot start or end with dashes, which
  423. # means there are some surprising restrictions on periods and dashes.
  424. # Check that before we do IDNA encoding because the IDNA library gives
  425. # unfriendly errors for these cases, but after UTS-46 normalization because
  426. # it can insert periods and hyphens (from fullwidth characters).
  427. # (RFC 952, RFC 1123 2.1, RFC 5322 3.2.3)
  428. check_dot_atom(domain, 'An email address cannot have a {} immediately after the @-sign.', 'An email address cannot end with a {}.', is_hostname=True)
  429. # Check for RFC 5890's invalid R-LDH labels, which are labels that start
  430. # with two characters other than "xn" and two dashes.
  431. for label in domain.split("."):
  432. if re.match(r"(?!xn)..--", label, re.I):
  433. raise EmailSyntaxError("An email address cannot have two letters followed by two dashes immediately after the @-sign or after a period, except Punycode.")
  434. if DOT_ATOM_TEXT_HOSTNAME.match(domain):
  435. # This is a valid non-internationalized domain.
  436. ascii_domain = domain
  437. else:
  438. # If international characters are present in the domain name, convert
  439. # the domain to IDNA ASCII. If internationalized characters are present,
  440. # the MTA must either support SMTPUTF8 or the mail client must convert the
  441. # domain name to IDNA before submission.
  442. #
  443. # For ASCII-only domains, the transformation does nothing and is safe to
  444. # apply. However, to ensure we don't rely on the idna library for basic
  445. # syntax checks, we don't use it if it's not needed.
  446. #
  447. # idna.encode also checks the domain name length after encoding but it
  448. # doesn't give a nice error, so we call the underlying idna.alabel method
  449. # directly. idna.alabel checks label length and doesn't give great messages,
  450. # but we can't easily go to lower level methods.
  451. try:
  452. ascii_domain = ".".join(
  453. idna.alabel(label).decode("ascii")
  454. for label in domain.split(".")
  455. )
  456. except idna.IDNAError as e:
  457. # Some errors would have already been raised by idna.uts46_remap.
  458. raise EmailSyntaxError(f"The part after the @-sign is invalid ({e}).") from e
  459. # Check the syntax of the string returned by idna.encode.
  460. # It should never fail.
  461. if not DOT_ATOM_TEXT_HOSTNAME.match(ascii_domain):
  462. raise EmailSyntaxError("The email address contains invalid characters after the @-sign after IDNA encoding.")
  463. # Check the length of the domain name in bytes.
  464. # (RFC 1035 2.3.4 and RFC 5321 4.5.3.1.2)
  465. # We're checking the number of bytes ("octets") here, which can be much
  466. # higher than the number of characters in internationalized domains,
  467. # on the assumption that the domain may be transmitted without SMTPUTF8
  468. # as IDNA ASCII. (This is also checked by idna.encode, so this exception
  469. # is never reached for internationalized domains.)
  470. if len(ascii_domain) > DOMAIN_MAX_LENGTH:
  471. if ascii_domain == original_domain:
  472. reason = get_length_reason(ascii_domain, limit=DOMAIN_MAX_LENGTH)
  473. raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.")
  474. else:
  475. diff = len(ascii_domain) - DOMAIN_MAX_LENGTH
  476. s = "" if diff == 1 else "s"
  477. raise EmailSyntaxError(f"The email address is too long after the @-sign ({diff} byte{s} too many after IDNA encoding).")
  478. # Also check the label length limit.
  479. # (RFC 1035 2.3.1)
  480. for label in ascii_domain.split("."):
  481. if len(label) > DNS_LABEL_LENGTH_LIMIT:
  482. reason = get_length_reason(label, limit=DNS_LABEL_LENGTH_LIMIT)
  483. raise EmailSyntaxError(f"After the @-sign, periods cannot be separated by so many characters {reason}.")
  484. if globally_deliverable:
  485. # All publicly deliverable addresses have domain names with at least
  486. # one period, at least for gTLDs created since 2013 (per the ICANN Board
  487. # New gTLD Program Committee, https://www.icann.org/en/announcements/details/new-gtld-dotless-domain-names-prohibited-30-8-2013-en).
  488. # We'll consider the lack of a period a syntax error
  489. # since that will match people's sense of what an email address looks
  490. # like. We'll skip this in test environments to allow '@test' email
  491. # addresses.
  492. if "." not in ascii_domain and not (ascii_domain == "test" and test_environment):
  493. raise EmailSyntaxError("The part after the @-sign is not valid. It should have a period.")
  494. # We also know that all TLDs currently end with a letter.
  495. if not DOMAIN_NAME_REGEX.search(ascii_domain):
  496. raise EmailSyntaxError("The part after the @-sign is not valid. It is not within a valid top-level domain.")
  497. # Check special-use and reserved domain names.
  498. # Some might fail DNS-based deliverability checks, but that
  499. # can be turned off, so we should fail them all sooner.
  500. # See the references in __init__.py.
  501. from . import SPECIAL_USE_DOMAIN_NAMES
  502. for d in SPECIAL_USE_DOMAIN_NAMES:
  503. # See the note near the definition of SPECIAL_USE_DOMAIN_NAMES.
  504. if d == "test" and test_environment:
  505. continue
  506. if ascii_domain == d or ascii_domain.endswith("." + d):
  507. raise EmailSyntaxError("The part after the @-sign is a special-use or reserved name that cannot be used with email.")
  508. # We may have been given an IDNA ASCII domain to begin with. Check
  509. # that the domain actually conforms to IDNA. It could look like IDNA
  510. # but not be actual IDNA. For ASCII-only domains, the conversion out
  511. # of IDNA just gives the same thing back.
  512. #
  513. # This gives us the canonical internationalized form of the domain,
  514. # which we return to the caller as a part of the normalized email
  515. # address.
  516. try:
  517. domain_i18n = idna.decode(ascii_domain.encode('ascii'))
  518. except idna.IDNAError as e:
  519. raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).") from e
  520. # Check that this normalized domain name has not somehow become
  521. # an invalid domain name. All of the checks before this point
  522. # using the idna package probably guarantee that we now have
  523. # a valid international domain name in most respects. But it
  524. # doesn't hurt to re-apply some tests to be sure. See the similar
  525. # tests above.
  526. # Check for invalid and unsafe characters. We have no test
  527. # case for this.
  528. bad_chars = {
  529. safe_character_display(c)
  530. for c in domain
  531. if not ATEXT_HOSTNAME_INTL.match(c)
  532. }
  533. if bad_chars:
  534. raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
  535. check_unsafe_chars(domain)
  536. # Check that it can be encoded back to IDNA ASCII. We have no test
  537. # case for this.
  538. try:
  539. idna.encode(domain_i18n)
  540. except idna.IDNAError as e:
  541. raise EmailSyntaxError(f"The part after the @-sign became invalid after normalizing to international characters ({e}).") from e
  542. # Return the IDNA ASCII-encoded form of the domain, which is how it
  543. # would be transmitted on the wire (except when used with SMTPUTF8
  544. # possibly), as well as the canonical Unicode form of the domain,
  545. # which is better for display purposes. This should also take care
  546. # of RFC 6532 section 3.1's suggestion to apply Unicode NFC
  547. # normalization to addresses.
  548. return {
  549. "ascii_domain": ascii_domain,
  550. "domain": domain_i18n,
  551. }
  552. def validate_email_length(addrinfo: ValidatedEmail) -> None:
  553. # There are three forms of the email address whose length must be checked:
  554. #
  555. # 1) The original email address string. Since callers may continue to use
  556. # this string, even though we recommend using the normalized form, we
  557. # should not pass validation when the original input is not valid. This
  558. # form is checked first because it is the original input.
  559. # 2) The normalized email address. We perform Unicode NFC normalization of
  560. # the local part, we normalize the domain to internationalized characters
  561. # (if originaly IDNA ASCII) which also includes Unicode normalization,
  562. # and we may remove quotes in quoted local parts. We recommend that
  563. # callers use this string, so it must be valid.
  564. # 3) The email address with the IDNA ASCII representation of the domain
  565. # name, since this string may be used with email stacks that don't
  566. # support UTF-8. Since this is the least likely to be used by callers,
  567. # it is checked last. Note that ascii_email will only be set if the
  568. # local part is ASCII, but conceivably the caller may combine a
  569. # internationalized local part with an ASCII domain, so we check this
  570. # on that combination also. Since we only return the normalized local
  571. # part, we use that (and not the unnormalized local part).
  572. #
  573. # In all cases, the length is checked in UTF-8 because the SMTPUTF8
  574. # extension to SMTP validates the length in bytes.
  575. addresses_to_check = [
  576. (addrinfo.original, None),
  577. (addrinfo.normalized, "after normalization"),
  578. ((addrinfo.ascii_local_part or addrinfo.local_part or "") + "@" + addrinfo.ascii_domain, "when the part after the @-sign is converted to IDNA ASCII"),
  579. ]
  580. for addr, reason in addresses_to_check:
  581. addr_len = len(addr)
  582. addr_utf8_len = len(addr.encode("utf8"))
  583. diff = addr_utf8_len - EMAIL_MAX_LENGTH
  584. if diff > 0:
  585. if reason is None and addr_len == addr_utf8_len:
  586. # If there is no normalization or transcoding,
  587. # we can give a simple count of the number of
  588. # characters over the limit.
  589. reason = get_length_reason(addr, limit=EMAIL_MAX_LENGTH)
  590. elif reason is None:
  591. # If there is no normalization but there is
  592. # some transcoding to UTF-8, we can compute
  593. # the minimum number of characters over the
  594. # limit by dividing the number of bytes over
  595. # the limit by the maximum number of bytes
  596. # per character.
  597. mbpc = max(len(c.encode("utf8")) for c in addr)
  598. mchars = max(1, diff // mbpc)
  599. suffix = "s" if diff > 1 else ""
  600. if mchars == diff:
  601. reason = f"({diff} character{suffix} too many)"
  602. else:
  603. reason = f"({mchars}-{diff} character{suffix} too many)"
  604. else:
  605. # Since there is normalization, the number of
  606. # characters in the input that need to change is
  607. # impossible to know.
  608. suffix = "s" if diff > 1 else ""
  609. reason += f" ({diff} byte{suffix} too many)"
  610. raise EmailSyntaxError(f"The email address is too long {reason}.")
  611. class DomainLiteralValidationResult(TypedDict):
  612. domain_address: Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
  613. domain: str
  614. def validate_email_domain_literal(domain_literal: str) -> DomainLiteralValidationResult:
  615. # This is obscure domain-literal syntax. Parse it and return
  616. # a compressed/normalized address.
  617. # RFC 5321 4.1.3 and RFC 5322 3.4.1.
  618. addr: Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
  619. # Try to parse the domain literal as an IPv4 address.
  620. # There is no tag for IPv4 addresses, so we can never
  621. # be sure if the user intends an IPv4 address.
  622. if re.match(r"^[0-9\.]+$", domain_literal):
  623. try:
  624. addr = ipaddress.IPv4Address(domain_literal)
  625. except ValueError as e:
  626. raise EmailSyntaxError(f"The address in brackets after the @-sign is not valid: It is not an IPv4 address ({e}) or is missing an address literal tag.") from e
  627. # Return the IPv4Address object and the domain back unchanged.
  628. return {
  629. "domain_address": addr,
  630. "domain": f"[{addr}]",
  631. }
  632. # If it begins with "IPv6:" it's an IPv6 address.
  633. if domain_literal.startswith("IPv6:"):
  634. try:
  635. addr = ipaddress.IPv6Address(domain_literal[5:])
  636. except ValueError as e:
  637. raise EmailSyntaxError(f"The IPv6 address in brackets after the @-sign is not valid ({e}).") from e
  638. # Return the IPv6Address object and construct a normalized
  639. # domain literal.
  640. return {
  641. "domain_address": addr,
  642. "domain": f"[IPv6:{addr.compressed}]",
  643. }
  644. # Nothing else is valid.
  645. if ":" not in domain_literal:
  646. raise EmailSyntaxError("The part after the @-sign in brackets is not an IPv4 address and has no address literal tag.")
  647. # The tag (the part before the colon) has character restrictions,
  648. # but since it must come from a registry of tags (in which only "IPv6" is defined),
  649. # there's no need to check the syntax of the tag. See RFC 5321 4.1.2.
  650. # Check for permitted ASCII characters. This actually doesn't matter
  651. # since there will be an exception after anyway.
  652. bad_chars = {
  653. safe_character_display(c)
  654. for c in domain_literal
  655. if not DOMAIN_LITERAL_CHARS.match(c)
  656. }
  657. if bad_chars:
  658. raise EmailSyntaxError("The part after the @-sign contains invalid characters in brackets: " + ", ".join(sorted(bad_chars)) + ".")
  659. # There are no other domain literal tags.
  660. # https://www.iana.org/assignments/address-literal-tags/address-literal-tags.xhtml
  661. raise EmailSyntaxError("The part after the @-sign contains an invalid address literal tag in brackets.")