btx-lib-mail 4.2.0__tar.gz → 4.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/CHANGELOG.md +17 -0
  2. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/PKG-INFO +1 -1
  3. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/api.md +18 -16
  4. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/configuration.md +5 -1
  5. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/streaming.md +3 -1
  6. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/systemdesign/module_reference.md +6 -1
  7. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/pyproject.toml +1 -1
  8. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/__init__conf__.py +1 -1
  9. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_config.py +5 -2
  10. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_transport.py +190 -11
  11. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_lib_mail.py +2 -10
  12. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_streaming.py +382 -26
  13. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/.gitignore +0 -0
  14. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/LICENSE +0 -0
  15. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/README.md +0 -0
  16. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/attachment-security.md +0 -0
  17. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/cli.md +0 -0
  18. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/installation.md +0 -0
  19. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/plans/2026-10-13-smtputf8-design.md +0 -0
  20. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/docs/plans/2026-10-13-smtputf8.md +0 -0
  21. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/__init__.py +0 -0
  22. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/__main__.py +0 -0
  23. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_attachments.py +0 -0
  24. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_common.py +0 -0
  25. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_compose.py +0 -0
  26. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_descriptor_path.py +0 -0
  27. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/_validation.py +0 -0
  28. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/behaviors.py +0 -0
  29. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/__init__.py +0 -0
  30. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_commands.py +0 -0
  31. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_dispatch.py +0 -0
  32. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_output.py +0 -0
  33. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_payloads.py +0 -0
  34. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_send_command.py +0 -0
  35. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_settings_sources.py +0 -0
  36. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/cli/_traceback.py +0 -0
  37. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/errors.py +0 -0
  38. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/lib_mail.py +0 -0
  39. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/py.typed +0 -0
  40. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/secret_safety.py +0 -0
  41. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/src/btx_lib_mail/typed_click.py +0 -0
  42. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/conftest.py +0 -0
  43. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/log_capture.py +0 -0
  44. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/smtp_test_server.py +0 -0
  45. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_attachment_integrity.py +0 -0
  46. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_behaviors.py +0 -0
  47. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_cli.py +0 -0
  48. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_cli_send.py +0 -0
  49. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_deadline.py +0 -0
  50. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_errors.py +0 -0
  51. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_international_addresses.py +0 -0
  52. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_limits.py +0 -0
  53. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_log_capture.py +0 -0
  54. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_metadata.py +0 -0
  55. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_module_entry.py +0 -0
  56. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_packaging.py +0 -0
  57. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_secret_safety.py +0 -0
  58. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/test_transfer_memory.py +0 -0
  59. {btx_lib_mail-4.2.0 → btx_lib_mail-4.3.0}/tests/transport_doubles.py +0 -0
@@ -2,6 +2,23 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [4.3.0] 2026-10-13 17:40:35
6
+
7
+ ### Fixed
8
+ - A delivery with `smtp_delivery_deadline` set no longer outlives it by the lookup of this host's own
9
+ name for `EHLO` (the first delivery of a process, `smtp_local_hostname` unset; on a host with slow
10
+ reverse DNS that took seconds). The lookup runs on a background thread. A delivery with a deadline
11
+ waits for it, before connecting, at most half the time the deadline has left, then announces its
12
+ connection's own address as an RFC 5321 address literal (`[192.0.2.7]`, `[IPv6:2001:db8::7]`);
13
+ the deliveries after the lookup finishes use the name. Without a deadline the lookup is waited for
14
+ before connecting, as before.
15
+
16
+ ### Added
17
+ - `SmtplibTransport(local_hostname_lookup=...)`: a callable returning the `EHLO` name a transport
18
+ uses when a delivery names none, run once per transport (again after a run that raised, and in a
19
+ forked child whose parent had not finished it). Unset, every transport shares this host's own
20
+ name, looked up once per process.
21
+
5
22
  ## [4.2.0] 2026-10-13 14:56:19
6
23
 
7
24
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: btx_lib_mail
3
- Version: 4.2.0
3
+ Version: 4.3.0
4
4
  Summary: Send email from Python or the shell: streamed large attachments (bounded memory), RFC 3030 BDAT/CHUNKING, STARTTLS, multi-host failover, and attachment security.
5
5
  Project-URL: Homepage, https://github.com/bitranox/btx_lib_mail
6
6
  Project-URL: Repository, https://github.com/bitranox/btx_lib_mail.git
@@ -21,19 +21,19 @@ original object. To use a different settings object, pass it as `send(config=...
21
21
 
22
22
  **SMTP Settings:**
23
23
 
24
- | Field | Type | Default | Description |
25
- |--------------------------------|---------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
26
- | `smtphosts` | `list[str]` | `[]` | Ordered SMTP hosts (`"host[:port]"`, `"[IPv6]:port"`). Each entry is checked with `validate_smtp_host` at construction and assignment; a blank entry is dropped. An empty list requires callers to supply `smtphosts` when sending. |
27
- | `raise_on_missing_attachments` | `bool` | `True` | When `True`, missing or unreadable attachments raise `AttachmentNotFoundError` (a `FileNotFoundError`); otherwise a warning is logged and delivery proceeds without the attachment. |
28
- | `raise_on_invalid_recipient` | `bool` | `True` | When `True`, invalid recipient addresses raise `InvalidInputError` (a `ValueError`); otherwise a warning is logged and the address is skipped. |
29
- | `recipient_max_count` | `int \| None` | `1000` | Most recipients one `send()` call accepts, counted after duplicates are dropped; more is refused with `InvalidInputError` before any delivery. `None` sets no limit; when set, positive. |
30
- | `smtp_username` | `str \| None` | `None` | Username used for SMTP authentication. Must be paired with `smtp_password`. |
31
- | `smtp_password` | `SecretStr \| None` | `None` | Password paired with `smtp_username`. Ignored when either value is missing. Masked in `repr()` and `model_dump()`; call `.get_secret_value()` for the plaintext. A `str`, UTF-8 `bytes` or an `int` is coerced and any other type refused; a validation error of `ConfMail` never carries it. NUL or invalid Unicode in it is refused by `send()`. |
32
- | `smtp_use_starttls` | `bool` | `True` | Enables `STARTTLS` negotiation before authentication. Set to `False` for servers that do not support STARTTLS. |
33
- | `smtp_starttls_verify` | `bool` | `True` | Verifies the server certificate and hostname during `STARTTLS`. Set to `False` for internal self-signed relays (encrypted, unverified). |
34
- | `smtp_timeout` | `float` | `30.0` | Socket timeout in seconds applied to SMTP connections. Must be positive and finite (NaN and infinity are refused) and at most 2147483 (about 24.8 days, the longest timeout a Windows socket holds). |
35
- | `smtp_local_hostname` | `str \| None` | `None` | Name announced in `EHLO`. When `None`, this host's name is looked up once per process and reused (an address literal such as `[192.0.2.7]` when it has no dot). Set it where reverse DNS is slow. Must be non-empty printable ASCII without spaces, at most 255 characters. |
36
- | `smtp_delivery_deadline` | `float \| None` | `None` | Upper bound in seconds for one SMTP session (one recipient via one host), from the TCP connect to the reply to `QUIT`, the server's greeting and the STARTTLS handshake included; each address the host name resolves to is tried with at most the time left, and none once it has run out (the name lookup itself is not interrupted). `smtp_timeout` bounds each socket operation, so a server answering one byte at a time never trips it; this bounds the whole session, after which the host counts as failed. `None` sets no bound; when set, positive, finite and at most 2147483. |
24
+ | Field | Type | Default | Description |
25
+ |--------------------------------|---------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
26
+ | `smtphosts` | `list[str]` | `[]` | Ordered SMTP hosts (`"host[:port]"`, `"[IPv6]:port"`). Each entry is checked with `validate_smtp_host` at construction and assignment; a blank entry is dropped. An empty list requires callers to supply `smtphosts` when sending. |
27
+ | `raise_on_missing_attachments` | `bool` | `True` | When `True`, missing or unreadable attachments raise `AttachmentNotFoundError` (a `FileNotFoundError`); otherwise a warning is logged and delivery proceeds without the attachment. |
28
+ | `raise_on_invalid_recipient` | `bool` | `True` | When `True`, invalid recipient addresses raise `InvalidInputError` (a `ValueError`); otherwise a warning is logged and the address is skipped. |
29
+ | `recipient_max_count` | `int \| None` | `1000` | Most recipients one `send()` call accepts, counted after duplicates are dropped; more is refused with `InvalidInputError` before any delivery. `None` sets no limit; when set, positive. |
30
+ | `smtp_username` | `str \| None` | `None` | Username used for SMTP authentication. Must be paired with `smtp_password`. |
31
+ | `smtp_password` | `SecretStr \| None` | `None` | Password paired with `smtp_username`. Ignored when either value is missing. Masked in `repr()` and `model_dump()`; call `.get_secret_value()` for the plaintext. A `str`, UTF-8 `bytes` or an `int` is coerced and any other type refused; a validation error of `ConfMail` never carries it. NUL or invalid Unicode in it is refused by `send()`. |
32
+ | `smtp_use_starttls` | `bool` | `True` | Enables `STARTTLS` negotiation before authentication. Set to `False` for servers that do not support STARTTLS. |
33
+ | `smtp_starttls_verify` | `bool` | `True` | Verifies the server certificate and hostname during `STARTTLS`. Set to `False` for internal self-signed relays (encrypted, unverified). |
34
+ | `smtp_timeout` | `float` | `30.0` | Socket timeout in seconds applied to SMTP connections. Must be positive and finite (NaN and infinity are refused) and at most 2147483 (about 24.8 days, the longest timeout a Windows socket holds). |
35
+ | `smtp_local_hostname` | `str \| None` | `None` | Name announced in `EHLO`. When `None`, this host's name is looked up once per process and reused (an address literal such as `[192.0.2.7]` when it has no dot); with `smtp_delivery_deadline` set, a delivery waits for that lookup at most half the time left, then announces its connection's own address literal. Set it where reverse DNS is slow. Must be non-empty printable ASCII without spaces, at most 255 characters. |
36
+ | `smtp_delivery_deadline` | `float \| None` | `None` | Upper bound in seconds for one SMTP session (one recipient via one host), from the TCP connect to the reply to `QUIT`, the server's greeting and the STARTTLS handshake included; each address the host name resolves to is tried with at most the time left, and none once it has run out (the name lookup itself is not interrupted); a lookup of this host's own `EHLO` name still running is waited for at most half the time left. `smtp_timeout` bounds each socket operation, so a server answering one byte at a time never trips it; this bounds the whole session, after which the host counts as failed. `None` sets no bound; when set, positive, finite and at most 2147483. |
37
37
 
38
38
  **Attachment Security Settings:**
39
39
 
@@ -321,9 +321,11 @@ next host is tried. An `OSError` it raises is logged with its text, anything els
321
321
  only; never put a credential into the text of an `OSError`. `DeliveryOptions` is a frozen
322
322
  dataclass with `credentials` (`tuple[str, str] | None`, left out of `repr`), `use_starttls`,
323
323
  `starttls_verify`, `timeout`, `local_hostname` and `deadline`. The default transport,
324
- `SmtplibTransport` (importable from `btx_lib_mail.lib_mail`), speaks SMTP; a test passes its
325
- own transport through `send(transport=...)` and asserts on what it received, with no server
326
- and no patching:
324
+ `SmtplibTransport` (importable from `btx_lib_mail.lib_mail`), speaks SMTP. Its keyword-only
325
+ `local_hostname_lookup` takes a callable returning the `EHLO` name to use when a delivery names
326
+ none; unset, every transport shares this host's own name, looked up once per process. A test
327
+ passes its own transport through `send(transport=...)` and asserts on what it received, with no
328
+ server and no patching:
327
329
 
328
330
  ```python
329
331
  from typing import IO
@@ -121,7 +121,11 @@ Key behaviours:
121
121
  (or `local_hostname=`, `--local-hostname`, `BTX_MAIL_SMTP_LOCAL_HOSTNAME`).
122
122
  Unset, it uses this host's fully qualified name, looked up by reverse DNS
123
123
  once per process and reused for every connection; set a name where that
124
- lookup is slow or returns something a relay rejects.
124
+ lookup is slow or returns something a relay rejects. With a delivery
125
+ deadline set, a delivery waits for that lookup at most half the time the
126
+ deadline has left; if it has not finished, the connection's own address
127
+ stands in as an address literal (`[192.0.2.7]`, `[IPv6:2001:db8::7]`), and
128
+ the name is used by the deliveries after it has been found.
125
129
 
126
130
  ## Credentials
127
131
 
@@ -73,7 +73,9 @@ logged and the next is tried without re-rendering the message.
73
73
  Each recipient gets its own SMTP connection, so any fixed per-connection cost is paid once
74
74
  per recipient. The client's `EHLO` name is one such cost when it is not configured: it is
75
75
  then this host's fully qualified name, found by reverse DNS. The library looks it up once
76
- per process and reuses it; set `smtp_local_hostname` (or `send(local_hostname=...)`,
76
+ per process, on a background thread, and reuses it. A delivery with a deadline waits for it at
77
+ most half the time the deadline has left, then announces its connection's own address as an
78
+ address literal instead. Set `smtp_local_hostname` (or `send(local_hostname=...)`,
77
79
  `--local-hostname`, `BTX_MAIL_SMTP_LOCAL_HOSTNAME`) to skip the lookup entirely or to
78
80
  announce a name the relay accepts.
79
81
 
@@ -252,7 +252,12 @@ redacted at the credential fields (`smtp_password`, `smtphosts`).
252
252
  * `SMTPUTF8NotSupportedError` - a relay without SMTPUTF8 for a message that needs it; a message refusal
253
253
  in the host order (the host is not demoted).
254
254
  * `SmtplibTransport` - sends `SMTPUTF8 BODY=8BITMIME` on `MAIL FROM` for a non-ASCII address; opens an `smtplib.SMTP` session (EHLO name: the configured one,
255
- else `_default_local_hostname()`, smtplib's rule computed once per process), STARTTLS
255
+ else `_default_local_hostname()`, smtplib's rule, run once per process on a daemon thread by
256
+ `_LocalHostnameLookup`; with a deadline, waited for at most `_EHLO_NAME_SHARE_OF_DEADLINE` of
257
+ the time left, before connecting, else `_local_address_literal()` of the connection's own address;
258
+ an attempt is registered only once its thread started, and a forked child keeps only a name
259
+ already found (`os.register_at_fork`);
260
+ `SmtplibTransport(local_hostname_lookup=)` substitutes the lookup), STARTTLS
256
261
  with `_build_starttls_context(verify=...)`, a `WARNING` when credentials go out with
257
262
  STARTTLS off, AUTH through `_authenticate` (stdlib login for ASCII credentials, RFC 4616
258
263
  AUTH PLAIN in UTF-8 otherwise), then streams the message in `STREAM_CHUNK_SIZE`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "btx_lib_mail"
3
- version = "4.2.0"
3
+ version = "4.3.0"
4
4
  description = "Send email from Python or the shell: streamed large attachments (bounded memory), RFC 3030 BDAT/CHUNKING, STARTTLS, multi-host failover, and attachment security."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -21,7 +21,7 @@ name = "btx_lib_mail"
21
21
  # assignment line-by-line against pyproject.toml's `project.description` field.
22
22
  title = "Send email from Python or the shell: streamed large attachments (bounded memory), RFC 3030 BDAT/CHUNKING, STARTTLS, multi-host failover, and attachment security." # noqa: E501
23
23
  #: Current release version pulled from ``pyproject.toml`` by automation.
24
- version = "4.2.0"
24
+ version = "4.3.0"
25
25
  #: Repository homepage presented to users.
26
26
  homepage = "https://github.com/bitranox/btx_lib_mail"
27
27
  #: Author attribution surfaced in CLI output.
@@ -85,8 +85,11 @@ class ConfMail(SecretSafeModel):
85
85
  server's final reply. `smtp_timeout` bounds each socket
86
86
  operation, so a server answering one byte at a time never trips
87
87
  it; this bounds the whole session, after which the host counts
88
- as failed and the next one is tried. `None` sets no bound. Must
89
- be positive and finite when set.
88
+ as failed and the next one is tried. A lookup of this host's own
89
+ name for `EHLO` still running is waited for at most half the
90
+ time left; then the connection's own address stands in as an
91
+ address literal. `None` sets no bound. Must be positive and
92
+ finite when set.
90
93
  attachment_allowed_extensions: When set, only these extensions are
91
94
  allowed (whitelist mode). When `None`, the blocked extensions
92
95
  list applies instead.
@@ -10,13 +10,14 @@ from __future__ import annotations
10
10
 
11
11
  import _socket
12
12
  import base64
13
- import functools
13
+ import os
14
14
  import smtplib
15
15
  import socket
16
16
  import ssl
17
17
  import sys
18
18
  import threading
19
19
  import time
20
+ import weakref
20
21
  from contextlib import contextmanager, suppress
21
22
  from dataclasses import dataclass, field
22
23
  from typing import IO, TYPE_CHECKING, Final, Protocol, cast
@@ -26,7 +27,7 @@ from ._validation import needs_smtputf8, parse_smtp_host
26
27
  from .errors import BtxMailError
27
28
 
28
29
  if TYPE_CHECKING:
29
- from collections.abc import Generator
30
+ from collections.abc import Callable, Generator
30
31
 
31
32
 
32
33
  @dataclass(frozen=True)
@@ -60,15 +61,17 @@ class DeliveryOptions:
60
61
  deadline: float | None = None
61
62
 
62
63
 
63
- @functools.cache
64
+ # Every lookup alive in this process, so a forked child can reset them all; weak,
65
+ # so a transport that is dropped does not live on through the fork hook.
66
+ _LOOKUPS: weakref.WeakSet[_LocalHostnameLookup] = weakref.WeakSet()
67
+
68
+
64
69
  def _default_local_hostname() -> str:
65
- """Return the EHLO name smtplib would compute, looked up once per process.
70
+ """Return the EHLO name smtplib would compute for this host.
66
71
 
67
- smtplib calls socket.getfqdn() (a reverse DNS lookup) for every
68
- connection it opens without local_hostname, and delivery opens one
69
- connection per recipient; on a host with slow reverse DNS each one waits
70
- for it. The rule is smtplib's own: the FQDN when it has a dot, else an
71
- address literal (RFC 5321 section 4.1.3).
72
+ The rule is smtplib's own: the FQDN when it has a dot, else an address
73
+ literal (RFC 5321 section 4.1.3). Finding the FQDN is a reverse DNS
74
+ lookup, so callers keep the answer in a `_LocalHostnameLookup`.
72
75
 
73
76
  Returns:
74
77
  The FQDN when it contains a dot, otherwise a bracketed IP address
@@ -83,6 +86,146 @@ def _default_local_hostname() -> str:
83
86
  return "[127.0.0.1]"
84
87
 
85
88
 
89
+ @dataclass
90
+ class _LookupAttempt:
91
+ """One run of an EHLO-name lookup on its own thread, and how it ended."""
92
+
93
+ done: threading.Event = field(default_factory=threading.Event)
94
+ name: str | None = None
95
+ error: Exception | None = None
96
+
97
+
98
+ class _LocalHostnameLookup:
99
+ """Run an EHLO-name lookup once, on a background thread, and keep its answer.
100
+
101
+ smtplib calls socket.getfqdn() (a reverse DNS lookup) for every
102
+ connection it opens without local_hostname, and delivery opens one
103
+ connection per recipient; on a host with slow reverse DNS each one would
104
+ wait for it. The lookup cannot be interrupted, so it runs on a daemon
105
+ thread a caller can stop waiting for: a delivery with a deadline waits only
106
+ part of it, and the next delivery picks the answer up.
107
+ """
108
+
109
+ def __init__(self, lookup: Callable[[], str]) -> None:
110
+ """Wrap a lookup that has not run yet.
111
+
112
+ Args:
113
+ lookup: Returns this host's EHLO name. It runs again only after a
114
+ run that raised.
115
+ """
116
+ self._lookup = lookup
117
+ self._lock = threading.Lock()
118
+ self._attempt: _LookupAttempt | None = None
119
+ _LOOKUPS.add(self)
120
+
121
+ def name_within(self, seconds: float | None) -> str | None:
122
+ """Return the EHLO name, starting the lookup if none has run yet.
123
+
124
+ Args:
125
+ seconds: How long to wait for a lookup still running; None waits
126
+ for it to finish, 0 only reads an answer already found.
127
+
128
+ Returns:
129
+ The name, or None when the lookup did not finish in time.
130
+
131
+ Raises:
132
+ Exception: Whatever the lookup raised; the next call runs it again.
133
+ """
134
+ attempt = self._current_attempt()
135
+ if not attempt.done.wait(seconds):
136
+ return None
137
+ if attempt.error is not None:
138
+ self._forget(attempt)
139
+ raise attempt.error
140
+ return attempt.name
141
+
142
+ def _current_attempt(self) -> _LookupAttempt:
143
+ with self._lock:
144
+ return self._start() if self._attempt is None else self._attempt
145
+
146
+ def _start(self) -> _LookupAttempt:
147
+ attempt = _LookupAttempt()
148
+ # A daemon thread: a lookup that never returns must not keep the process alive.
149
+ threading.Thread(target=self._run, args=(attempt,), name="btx-lib-mail-ehlo-name", daemon=True).start()
150
+ # Registered only once its thread runs: a start refused at a thread limit leaves
151
+ # nothing behind that a later delivery would wait for forever.
152
+ self._attempt = attempt
153
+ return attempt
154
+
155
+ def _run(self, attempt: _LookupAttempt) -> None:
156
+ try:
157
+ attempt.name = self._lookup()
158
+ except Exception as error: # handed to the waiting delivery, which raises it as its own
159
+ attempt.error = error
160
+ finally:
161
+ attempt.done.set()
162
+
163
+ def after_fork_in_child(self) -> None:
164
+ """Keep only a name already found; drop what the parent's threads held.
165
+
166
+ A forked child has none of the parent's threads: a lookup still
167
+ running would never finish, and a lock or event a parent thread held at
168
+ the fork would stay held. A name already found is kept, so the child
169
+ does not look it up again.
170
+ """
171
+ self._lock = threading.Lock()
172
+ attempt = self._attempt
173
+ self._attempt = None
174
+ if attempt is not None and attempt.done.is_set() and attempt.name is not None:
175
+ found = _LookupAttempt(name=attempt.name)
176
+ found.done.set()
177
+ self._attempt = found
178
+
179
+ def _forget(self, attempt: _LookupAttempt) -> None:
180
+ with self._lock:
181
+ if self._attempt is attempt:
182
+ self._attempt = None
183
+
184
+
185
+ def _address_literal(address: str) -> str:
186
+ """Return the RFC 5321 address literal (section 4.1.3) for an IP address.
187
+
188
+ Args:
189
+ address: An IPv4 or IPv6 address as getsockname() reports it; an IPv6
190
+ zone suffix (``%eth0``) is dropped, since a literal has none.
191
+
192
+ Returns:
193
+ ``[192.0.2.7]`` or ``[IPv6:2001:db8::7]``.
194
+ """
195
+ host = address.split("%", 1)[0]
196
+ return f"[IPv6:{host}]" if ":" in host else f"[{host}]"
197
+
198
+
199
+ def _local_address_literal(connection_socket: socket.socket) -> str:
200
+ """Return the address literal of the local end of a connected socket."""
201
+ return _address_literal(str(connection_socket.getsockname()[0]))
202
+
203
+
204
+ # The name a session is created with until its EHLO name is decided after
205
+ # connecting. Empty, so a session that ever reached EHLO without it being set
206
+ # would send a bare EHLO a server refuses rather than a plausible wrong name.
207
+ _EHLO_NAME_UNDECIDED: Final = ""
208
+
209
+ # How much of the time a deadline has left a delivery waits for a lookup still
210
+ # running, before it connects. The rest is for the session itself: waiting all of
211
+ # it would let the deadline end a session the stand-in address literal could finish.
212
+ _EHLO_NAME_SHARE_OF_DEADLINE: Final = 0.5
213
+
214
+
215
+ def _reset_lookups_in_child() -> None:
216
+ for lookup in list(_LOOKUPS):
217
+ lookup.after_fork_in_child()
218
+
219
+
220
+ # Windows has no fork, and neither do some POSIX builds (Emscripten, WASI).
221
+ if sys.platform != "win32" and hasattr(os, "register_at_fork"):
222
+ os.register_at_fork(after_in_child=_reset_lookups_in_child)
223
+
224
+ # Shared by every SmtplibTransport built without a lookup of its own, so the
225
+ # reverse DNS lookup runs once per process however many transports exist.
226
+ _PROCESS_LOCAL_HOSTNAME: Final = _LocalHostnameLookup(_default_local_hostname)
227
+
228
+
86
229
  def _build_starttls_context(*, verify: bool) -> ssl.SSLContext:
87
230
  """Return the SSL context used for the STARTTLS handshake.
88
231
 
@@ -191,6 +334,19 @@ class SmtplibTransport:
191
334
  peak transfer memory is about one chunk.
192
335
  """
193
336
 
337
+ def __init__(self, *, local_hostname_lookup: Callable[[], str] | None = None) -> None:
338
+ """Create a transport.
339
+
340
+ Args:
341
+ local_hostname_lookup: Returns the name to announce in EHLO when a
342
+ delivery names none; run once per transport, and again after
343
+ a run that raised or in a forked child whose parent had not
344
+ finished it. None uses this host's own name, looked
345
+ up once per process and shared by every transport built
346
+ without one.
347
+ """
348
+ self._local_hostname = _PROCESS_LOCAL_HOSTNAME if local_hostname_lookup is None else _LocalHostnameLookup(local_hostname_lookup)
349
+
194
350
  def deliver(
195
351
  self,
196
352
  *,
@@ -212,20 +368,43 @@ class SmtplibTransport:
212
368
  timeouts, deadline).
213
369
  """
214
370
  hostname, port = parse_smtp_host(host)
215
- local_hostname = delivery.local_hostname or _default_local_hostname()
216
371
  # Not connected yet: the greeting is read while connecting, and that read
217
372
  # belongs inside the deadline. No `with`: its exit turns a QUIT reply other
218
373
  # than 221 into a failure, after the server has already taken the message.
219
- smtp_connection = _SessionSMTP(local_hostname=local_hostname, timeout=delivery.timeout)
374
+ smtp_connection = _SessionSMTP(local_hostname=_EHLO_NAME_UNDECIDED, timeout=delivery.timeout)
220
375
  try:
221
376
  with _session_deadline(smtp_connection, delivery.deadline):
377
+ # Waited for before connecting: a relay may drop a connection left idle after its greeting.
378
+ ehlo_name = self._ehlo_name_in_time(delivery, smtp_connection)
222
379
  smtp_connection.connect(hostname, port or 0)
380
+ # smtplib reads the name only when it sends EHLO, after the greeting.
381
+ smtp_connection.local_hostname = ehlo_name or _own_address_literal(smtp_connection)
223
382
  _prepare_session(smtp_connection, host=host, delivery=delivery)
224
383
  _send_message(smtp_connection, sender=sender, recipient=recipient, message=message)
225
384
  _quit_quietly(smtp_connection)
226
385
  finally:
227
386
  smtp_connection.close()
228
387
 
388
+ def _ehlo_name_in_time(self, delivery: DeliveryOptions, smtp_connection: _SessionSMTP) -> str | None:
389
+ """Return the EHLO name, or None when the lookup does not finish in time.
390
+
391
+ Without a deadline the lookup is waited for, as smtplib would; with one,
392
+ for at most `_EHLO_NAME_SHARE_OF_DEADLINE` of the time left.
393
+ """
394
+ if delivery.local_hostname:
395
+ return delivery.local_hostname
396
+ if smtp_connection.ends_at is None:
397
+ return self._local_hostname.name_within(None)
398
+ left = max(0.0, smtp_connection.ends_at - time.monotonic())
399
+ return self._local_hostname.name_within(left * _EHLO_NAME_SHARE_OF_DEADLINE)
400
+
401
+
402
+ def _own_address_literal(smtp_connection: smtplib.SMTP) -> str:
403
+ """Return the address literal a connected session announces when its name was not found in time."""
404
+ if smtp_connection.sock is None:
405
+ raise smtplib.SMTPServerDisconnected("the connection closed before EHLO")
406
+ return _local_address_literal(smtp_connection.sock)
407
+
229
408
 
230
409
  def _prepare_session(smtp_connection: smtplib.SMTP, *, host: str, delivery: DeliveryOptions) -> None:
231
410
  """Greet, secure and authenticate a connected session."""
@@ -2215,11 +2215,7 @@ def test_without_a_dotted_fqdn_the_default_is_the_host_address_literal(monkeypat
2215
2215
  """Mirrors smtplib: RFC 5321 wants a domain in EHLO, else an address literal."""
2216
2216
  monkeypatch.setattr(socket, "getfqdn", _bare_host_fqdn)
2217
2217
  monkeypatch.setattr(socket, "gethostbyname", _documentation_address)
2218
- _transport._default_local_hostname.cache_clear()
2219
- try:
2220
- assert _transport._default_local_hostname() == "[192.0.2.9]"
2221
- finally:
2222
- _transport._default_local_hostname.cache_clear()
2218
+ assert _transport._default_local_hostname() == "[192.0.2.9]"
2223
2219
 
2224
2220
 
2225
2221
  @pytest.mark.os_agnostic
@@ -2229,11 +2225,7 @@ def test_an_unresolvable_host_name_falls_back_to_loopback(monkeypatch: pytest.Mo
2229
2225
 
2230
2226
  monkeypatch.setattr(socket, "getfqdn", _bare_host_fqdn)
2231
2227
  monkeypatch.setattr(socket, "gethostbyname", unresolvable)
2232
- _transport._default_local_hostname.cache_clear()
2233
- try:
2234
- assert _transport._default_local_hostname() == "[127.0.0.1]"
2235
- finally:
2236
- _transport._default_local_hostname.cache_clear()
2228
+ assert _transport._default_local_hostname() == "[127.0.0.1]"
2237
2229
 
2238
2230
 
2239
2231
  # ---------------------------------------------------------------------------
@@ -8,11 +8,15 @@ from __future__ import annotations
8
8
  import contextlib
9
9
  import hashlib
10
10
  import io
11
+ import os
12
+ import signal
11
13
  import smtplib
12
14
  import socket
13
15
  import ssl
16
+ import sys
14
17
  import threading
15
18
  import time
19
+ import warnings
16
20
  from email import message_from_bytes
17
21
  from typing import IO, TYPE_CHECKING, Any, cast
18
22
 
@@ -1051,14 +1055,6 @@ def ehlo_server() -> Iterator[tuple[Controller, _EhloRecordingHandler]]:
1051
1055
  controller.stop()
1052
1056
 
1053
1057
 
1054
- @pytest.fixture
1055
- def fresh_local_name_cache() -> Iterator[None]:
1056
- """Start and end with no cached default EHLO name, so a planted one never leaks."""
1057
- _transport._default_local_hostname.cache_clear()
1058
- yield
1059
- _transport._default_local_hostname.cache_clear()
1060
-
1061
-
1062
1058
  def _send_two(controller: Controller, **kwargs: Any) -> None:
1063
1059
  lib_mail.send(
1064
1060
  mail_from="sender@example.com",
@@ -1072,46 +1068,406 @@ def _send_two(controller: Controller, **kwargs: Any) -> None:
1072
1068
 
1073
1069
 
1074
1070
  @pytest.mark.os_agnostic
1075
- def test_a_configured_ehlo_name_is_announced_without_a_lookup(
1076
- ehlo_server: tuple[Controller, _EhloRecordingHandler], monkeypatch: pytest.MonkeyPatch, fresh_local_name_cache: None
1077
- ) -> None:
1071
+ def test_a_configured_ehlo_name_is_announced_without_a_lookup(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1078
1072
  controller, handler = ehlo_server
1079
1073
 
1080
- def refuse(name: str = "") -> str:
1081
- raise AssertionError(f"the client called socket.getfqdn({name!r}) although a name was configured")
1074
+ def refuse() -> str:
1075
+ raise AssertionError("the client looked up its own name although one was configured")
1082
1076
 
1083
- monkeypatch.setattr(socket, "getfqdn", refuse)
1077
+ transport = _transport.SmtplibTransport(local_hostname_lookup=refuse)
1084
1078
 
1085
- _send_two(controller, config=lib_mail.ConfMail(smtp_local_hostname="relay.example.test"))
1079
+ _send_two(controller, config=lib_mail.ConfMail(smtp_local_hostname="relay.example.test"), transport=transport)
1086
1080
 
1087
1081
  assert handler.ehlo_names == ["relay.example.test", "relay.example.test"]
1088
1082
 
1089
1083
 
1090
1084
  @pytest.mark.os_agnostic
1091
- def test_the_default_ehlo_name_is_resolved_once_per_process(
1092
- ehlo_server: tuple[Controller, _EhloRecordingHandler], monkeypatch: pytest.MonkeyPatch, fresh_local_name_cache: None
1093
- ) -> None:
1085
+ def test_the_default_ehlo_name_is_looked_up_once_per_transport(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1094
1086
  controller, handler = ehlo_server
1095
- lookups: list[str] = []
1087
+ lookups: list[None] = []
1096
1088
 
1097
- def counting_getfqdn(name: str = "") -> str:
1098
- lookups.append(name)
1089
+ def counting_lookup() -> str:
1090
+ lookups.append(None)
1099
1091
  return "client.example.test"
1100
1092
 
1101
- monkeypatch.setattr(socket, "getfqdn", counting_getfqdn)
1093
+ transport = _transport.SmtplibTransport(local_hostname_lookup=counting_lookup)
1102
1094
 
1103
- _send_two(controller)
1104
- _send_two(controller)
1095
+ _send_two(controller, transport=transport)
1096
+ _send_two(controller, transport=transport)
1105
1097
 
1106
1098
  assert handler.ehlo_names == ["client.example.test"] * 4
1107
- assert len(lookups) == 1, f"one lookup per process, got {len(lookups)} for four connections"
1099
+ assert len(lookups) == 1, f"one lookup per transport, got {len(lookups)} for four connections"
1100
+
1101
+
1102
+ @pytest.mark.os_agnostic
1103
+ def test_every_default_transport_shares_the_process_wide_lookup() -> None:
1104
+ """The default lookup is a reverse DNS query; two transports must not each pay for it."""
1105
+ assert _transport.SmtplibTransport()._local_hostname is _transport.SmtplibTransport()._local_hostname
1106
+
1107
+
1108
+ class _HeldLookup:
1109
+ """An EHLO-name lookup that does not answer until the test releases it (slow reverse DNS)."""
1110
+
1111
+ def __init__(self, name: str) -> None:
1112
+ self._name = name
1113
+ self.release = threading.Event()
1114
+ self.calls = 0
1115
+
1116
+ def __call__(self) -> str:
1117
+ self.calls += 1
1118
+ # Bounded, so a regression cannot leave the thread waiting after the test.
1119
+ self.release.wait(timeout=_HELD_LOOKUP_SECONDS)
1120
+ return self._name
1121
+
1122
+
1123
+ _HELD_LOOKUP_SECONDS = 10.0
1124
+ # Wide enough that the session left after the wait finishes on a slow CI runner.
1125
+ _EHLO_DEADLINE = 2.0
1126
+
1127
+
1128
+ def _deliver_once(port: int, transport: _transport.SmtplibTransport, *, deadline: float | None) -> None:
1129
+ transport.deliver(
1130
+ host=f"127.0.0.1:{port}",
1131
+ sender="sender@example.com",
1132
+ recipient="rcpt@example.com",
1133
+ message=io.BytesIO(b"Subject: s\r\n\r\nbody\r\n"),
1134
+ delivery=DeliveryOptions(credentials=None, use_starttls=False, starttls_verify=False, timeout=5.0, deadline=deadline),
1135
+ )
1136
+
1137
+
1138
+ def _bounded(call: Callable[[], object]) -> tuple[BaseException | None, float]:
1139
+ """Run call bounded by the test rather than by the deadline under test; return what it raised and how long it took."""
1140
+ outcome: list[BaseException] = []
1141
+
1142
+ def run() -> None:
1143
+ try:
1144
+ call()
1145
+ except BaseException as error:
1146
+ outcome.append(error)
1147
+
1148
+ started = time.monotonic()
1149
+ worker = threading.Thread(target=run, daemon=True)
1150
+ worker.start()
1151
+ worker.join(timeout=5.0)
1152
+ assert not worker.is_alive(), "the delivery was still running after 5 s"
1153
+ return (outcome[0] if outcome else None), time.monotonic() - started
1154
+
1155
+
1156
+ @pytest.mark.os_agnostic
1157
+ def test_a_slow_ehlo_name_lookup_does_not_hold_a_delivery_past_its_deadline(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1158
+ controller, handler = ehlo_server
1159
+ lookup = _HeldLookup("late.example.test")
1160
+ try:
1161
+ error, took = _bounded(lambda: _deliver_once(controller.port, _transport.SmtplibTransport(local_hostname_lookup=lookup), deadline=_EHLO_DEADLINE))
1162
+ finally:
1163
+ lookup.release.set()
1164
+
1165
+ assert error is None, f"{type(error).__name__}: {error}"
1166
+ assert took < _EHLO_DEADLINE, f"took {took:.2f} s against a {_EHLO_DEADLINE} s deadline"
1167
+ assert handler.ehlo_names == ["[127.0.0.1]"], "the connection's own address stands in for the name not found yet"
1168
+
1169
+
1170
+ @pytest.mark.os_agnostic
1171
+ def test_an_ehlo_name_found_late_is_announced_by_the_next_delivery(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1172
+ controller, handler = ehlo_server
1173
+ lookup = _HeldLookup("late.example.test")
1174
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lookup)
1175
+ try:
1176
+ first, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=_EHLO_DEADLINE))
1177
+ finally:
1178
+ lookup.release.set()
1179
+ second, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=None))
1180
+
1181
+ assert (first, second) == (None, None)
1182
+ assert handler.ehlo_names == ["[127.0.0.1]", "late.example.test"]
1183
+ assert lookup.calls == 1, "the lookup still running is reused, not started again"
1184
+
1185
+
1186
+ @pytest.mark.os_agnostic
1187
+ def test_an_ehlo_name_found_within_the_deadline_is_announced(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1188
+ controller, handler = ehlo_server
1189
+
1190
+ def quick_enough() -> str:
1191
+ time.sleep(_EHLO_DEADLINE / 10)
1192
+ return "prompt.example.test"
1193
+
1194
+ error, _took = _bounded(lambda: _deliver_once(controller.port, _transport.SmtplibTransport(local_hostname_lookup=quick_enough), deadline=_EHLO_DEADLINE))
1195
+
1196
+ assert error is None
1197
+ assert handler.ehlo_names == ["prompt.example.test"]
1198
+
1199
+
1200
+ @pytest.mark.os_agnostic
1201
+ def test_without_a_deadline_a_slow_ehlo_name_lookup_is_waited_for(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1202
+ controller, handler = ehlo_server
1203
+ lookup = _HeldLookup("slow.example.test")
1204
+ timer = threading.Timer(_EHLO_DEADLINE, lookup.release.set)
1205
+ timer.start()
1206
+ try:
1207
+ error, took = _bounded(lambda: _deliver_once(controller.port, _transport.SmtplibTransport(local_hostname_lookup=lookup), deadline=None))
1208
+ finally:
1209
+ timer.cancel()
1210
+ lookup.release.set()
1211
+
1212
+ assert error is None
1213
+ assert took >= _EHLO_DEADLINE
1214
+ assert handler.ehlo_names == ["slow.example.test"]
1215
+
1216
+
1217
+ @pytest.mark.os_agnostic
1218
+ def test_without_a_deadline_nothing_connects_until_the_ehlo_name_is_known() -> None:
1219
+ """A slow lookup must not leave a connection idle long enough for the relay to drop it."""
1220
+ lookup = _HeldLookup("slow.example.test")
1221
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lookup)
1222
+ with socket.create_server(("127.0.0.1", 0)) as listener:
1223
+ port = listener.getsockname()[1]
1224
+ worker = threading.Thread(target=_deliver_quietly, args=(port, transport), daemon=True)
1225
+ worker.start()
1226
+ try:
1227
+ listener.settimeout(_EHLO_DEADLINE)
1228
+ with pytest.raises(TimeoutError):
1229
+ listener.accept()
1230
+ finally:
1231
+ lookup.release.set()
1232
+ listener.settimeout(5.0)
1233
+ connection, _address = listener.accept()
1234
+ connection.close()
1235
+ worker.join(timeout=5.0)
1236
+
1237
+
1238
+ def _deliver_quietly(port: int, transport: _transport.SmtplibTransport, deadline: float | None = None) -> None:
1239
+ """Deliver to a listener that hangs up straight away; the failure is not what the test is about."""
1240
+ with contextlib.suppress(OSError):
1241
+ _deliver_once(port, transport, deadline=deadline)
1242
+
1243
+
1244
+ @pytest.mark.os_agnostic
1245
+ def test_with_a_deadline_nothing_connects_while_the_ehlo_name_is_awaited() -> None:
1246
+ """The wait for a slow lookup comes before the connection opens, so no relay sees an idle session."""
1247
+ lookup = _HeldLookup("slow.example.test")
1248
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lookup)
1249
+ with socket.create_server(("127.0.0.1", 0)) as listener:
1250
+ port = listener.getsockname()[1]
1251
+ started = time.monotonic()
1252
+ worker = threading.Thread(target=_deliver_quietly, args=(port, transport, _EHLO_DEADLINE), daemon=True)
1253
+ worker.start()
1254
+ try:
1255
+ listener.settimeout(5.0)
1256
+ connection, _address = listener.accept()
1257
+ connected_after = time.monotonic() - started
1258
+ connection.close()
1259
+ finally:
1260
+ lookup.release.set()
1261
+ worker.join(timeout=5.0)
1262
+
1263
+ waited = _EHLO_DEADLINE * _transport._EHLO_NAME_SHARE_OF_DEADLINE
1264
+ assert connected_after >= waited * 0.9, f"connected after {connected_after:.2f} s, before the {waited} s wait for the name ended"
1265
+
1266
+
1267
+ @pytest.mark.os_agnostic
1268
+ def test_a_lookup_thread_that_cannot_start_is_tried_again_by_the_next_delivery(
1269
+ ehlo_server: tuple[Controller, _EhloRecordingHandler], monkeypatch: pytest.MonkeyPatch
1270
+ ) -> None:
1271
+ """A thread limit reached once must not leave a lookup registered that nothing will ever finish."""
1272
+ controller, handler = ehlo_server
1273
+ real_start = threading.Thread.start
1274
+ refused: list[str] = []
1275
+
1276
+ def refuse_the_first_lookup_thread(thread: threading.Thread) -> None:
1277
+ if thread.name == "btx-lib-mail-ehlo-name" and not refused:
1278
+ refused.append(thread.name)
1279
+ raise RuntimeError("can't start new thread")
1280
+ real_start(thread)
1281
+
1282
+ # The thread limit is the operating system's; Thread.start is where it surfaces.
1283
+ monkeypatch.setattr(threading.Thread, "start", refuse_the_first_lookup_thread)
1284
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lambda: "retried.example.test")
1285
+
1286
+ first, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=None))
1287
+ second, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=None))
1288
+
1289
+ assert isinstance(first, RuntimeError)
1290
+ assert second is None
1291
+ assert handler.ehlo_names == ["retried.example.test"]
1292
+
1293
+
1294
+ @pytest.mark.os_posix
1295
+ def test_a_forked_child_starts_its_own_lookup(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1296
+ """The parent's lookup thread does not exist in a child, so an attempt still running at the fork is not the child's."""
1297
+ if sys.platform == "win32":
1298
+ pytest.skip("os.fork does not exist on Windows")
1299
+ controller, handler = ehlo_server
1300
+ parent = os.getpid()
1301
+ release = threading.Event()
1302
+
1303
+ def lookup() -> str:
1304
+ if os.getpid() == parent:
1305
+ release.wait(timeout=_HELD_LOOKUP_SECONDS)
1306
+ return "parent.example.test"
1307
+ return "child.example.test"
1308
+
1309
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lookup)
1310
+ try:
1311
+ first, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=_EHLO_DEADLINE))
1312
+ with warnings.catch_warnings():
1313
+ # Python 3.12+ warns that forking a process with threads may deadlock; this child only sends mail.
1314
+ warnings.simplefilter("ignore", DeprecationWarning)
1315
+ child = os.fork()
1316
+ if child == 0:
1317
+ try:
1318
+ _deliver_once(controller.port, transport, deadline=None)
1319
+ except BaseException:
1320
+ os._exit(1)
1321
+ os._exit(0)
1322
+ exit_code = _wait_for_child(child, seconds=5.0)
1323
+ finally:
1324
+ release.set()
1325
+
1326
+ assert first is None
1327
+ assert exit_code == 0
1328
+ assert handler.ehlo_names == ["[127.0.0.1]", "child.example.test"]
1329
+
1330
+
1331
+ @pytest.mark.os_posix
1332
+ def test_a_forked_child_reuses_a_name_its_parent_already_found(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1333
+ """A finished lookup is as true in the child as in the parent; looking it up again costs every worker a reverse DNS query."""
1334
+ if sys.platform == "win32":
1335
+ pytest.skip("os.fork does not exist on Windows")
1336
+ controller, handler = ehlo_server
1337
+ parent = os.getpid()
1338
+
1339
+ def lookup() -> str:
1340
+ return "parent.example.test" if os.getpid() == parent else "child.example.test"
1341
+
1342
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lookup)
1343
+ first, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=None))
1344
+ with warnings.catch_warnings():
1345
+ warnings.simplefilter("ignore", DeprecationWarning)
1346
+ child = os.fork()
1347
+ if child == 0:
1348
+ try:
1349
+ _deliver_once(controller.port, transport, deadline=None)
1350
+ except BaseException:
1351
+ os._exit(1)
1352
+ os._exit(0)
1353
+ exit_code = _wait_for_child(child, seconds=5.0)
1354
+
1355
+ assert (first, exit_code) == (None, 0)
1356
+ assert handler.ehlo_names == ["parent.example.test", "parent.example.test"]
1357
+
1358
+
1359
+ @pytest.mark.os_posix
1360
+ def test_a_forked_child_runs_a_lookup_that_raised_in_its_parent_again(ehlo_server: tuple[Controller, _EhloRecordingHandler]) -> None:
1361
+ if sys.platform == "win32":
1362
+ pytest.skip("os.fork does not exist on Windows")
1363
+ controller, handler = ehlo_server
1364
+ parent = os.getpid()
1365
+ release = threading.Event()
1366
+ raised = threading.Event()
1367
+
1368
+ def lookup() -> str:
1369
+ if os.getpid() == parent:
1370
+ # Raises only after the delivery stopped waiting, so no waiter collects the error before the fork.
1371
+ release.wait(timeout=_HELD_LOOKUP_SECONDS)
1372
+ raised.set()
1373
+ raise OSError("resolver unreachable")
1374
+ return "child.example.test"
1375
+
1376
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lookup)
1377
+ try:
1378
+ first, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=_EHLO_DEADLINE))
1379
+ finally:
1380
+ release.set()
1381
+ assert raised.wait(timeout=5.0)
1382
+ time.sleep(0.1) # the run marks itself finished right after raising
1383
+ with warnings.catch_warnings():
1384
+ warnings.simplefilter("ignore", DeprecationWarning)
1385
+ child = os.fork()
1386
+ if child == 0:
1387
+ try:
1388
+ _deliver_once(controller.port, transport, deadline=None)
1389
+ except BaseException:
1390
+ os._exit(1)
1391
+ os._exit(0)
1392
+ exit_code = _wait_for_child(child, seconds=5.0)
1393
+
1394
+ assert (first, exit_code) == (None, 0)
1395
+ assert handler.ehlo_names == ["[127.0.0.1]", "child.example.test"]
1396
+
1397
+
1398
+ def _wait_for_child(pid: int, *, seconds: float) -> int | None:
1399
+ """Return the child's exit code, or None after killing a child still running when seconds pass."""
1400
+ if sys.platform == "win32":
1401
+ raise RuntimeError("there are no forked children on Windows")
1402
+ ends_at = time.monotonic() + seconds
1403
+ while time.monotonic() < ends_at:
1404
+ done, status = os.waitpid(pid, os.WNOHANG)
1405
+ if done:
1406
+ return os.waitstatus_to_exitcode(status)
1407
+ time.sleep(0.05)
1408
+ os.kill(pid, signal.SIGKILL)
1409
+ os.waitpid(pid, 0)
1410
+ return None
1411
+
1412
+
1413
+ @pytest.mark.os_agnostic
1414
+ @pytest.mark.parametrize("deadline", [None, _EHLO_DEADLINE], ids=["no-deadline", "deadline"])
1415
+ def test_an_empty_ehlo_name_is_replaced_by_the_address_literal(ehlo_server: tuple[Controller, _EhloRecordingHandler], deadline: float | None) -> None:
1416
+ controller, handler = ehlo_server
1417
+ transport = _transport.SmtplibTransport(local_hostname_lookup=lambda: "")
1418
+
1419
+ error, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=deadline))
1420
+
1421
+ assert error is None, f"{type(error).__name__}: {error}"
1422
+ assert handler.ehlo_names == ["[127.0.0.1]"]
1423
+
1424
+
1425
+ @pytest.mark.os_agnostic
1426
+ def test_the_stand_in_literal_is_read_from_the_connections_own_ipv6_address() -> None:
1427
+ try:
1428
+ listener = socket.create_server(("::1", 0), family=socket.AF_INET6)
1429
+ except OSError:
1430
+ pytest.skip("no IPv6 loopback on this machine")
1431
+ with listener, socket.create_connection(("::1", listener.getsockname()[1]), timeout=5.0) as client:
1432
+ assert _transport._local_address_literal(client) == "[IPv6:::1]"
1433
+
1434
+
1435
+ @pytest.mark.os_agnostic
1436
+ @pytest.mark.parametrize("deadline", [None, 5.0], ids=["no-deadline", "deadline"])
1437
+ def test_a_failed_ehlo_name_lookup_fails_the_delivery_and_is_tried_again(ehlo_server: tuple[Controller, _EhloRecordingHandler], deadline: float | None) -> None:
1438
+ controller, handler = ehlo_server
1439
+ answers: list[str | OSError] = [OSError("resolver unreachable"), "retried.example.test"]
1440
+
1441
+ def flaky() -> str:
1442
+ answer = answers.pop(0)
1443
+ if isinstance(answer, OSError):
1444
+ raise answer
1445
+ return answer
1446
+
1447
+ transport = _transport.SmtplibTransport(local_hostname_lookup=flaky)
1448
+ first, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=deadline))
1449
+ second, _took = _bounded(lambda: _deliver_once(controller.port, transport, deadline=deadline))
1450
+
1451
+ assert isinstance(first, OSError)
1452
+ assert "resolver unreachable" in str(first)
1453
+ assert second is None
1454
+ assert handler.ehlo_names == ["retried.example.test"]
1455
+
1456
+
1457
+ @pytest.mark.os_agnostic
1458
+ @pytest.mark.parametrize(
1459
+ ("address", "literal"),
1460
+ [("192.0.2.7", "[192.0.2.7]"), ("2001:db8::7", "[IPv6:2001:db8::7]"), ("fe80::1%eth0", "[IPv6:fe80::1]")],
1461
+ ids=["ipv4", "ipv6", "ipv6-zone"],
1462
+ )
1463
+ def test_the_stand_in_ehlo_name_is_an_rfc_5321_address_literal(address: str, literal: str) -> None:
1464
+ assert _transport._address_literal(address) == literal
1108
1465
 
1109
1466
 
1110
1467
  @pytest.mark.os_agnostic
1111
1468
  @pytest.mark.parametrize("from_env", [False, True], ids=["option", "env"])
1112
1469
  def test_the_cli_announces_the_local_hostname(
1113
1470
  ehlo_server: tuple[Controller, _EhloRecordingHandler],
1114
- fresh_local_name_cache: None,
1115
1471
  monkeypatch: pytest.MonkeyPatch,
1116
1472
  tmp_path: Path,
1117
1473
  from_env: bool,
File without changes
File without changes
File without changes
File without changes