@@ -110,6 +110,27 @@ async def __aexit__(
110110 return False
111111
112112
113+ def encode_hostname (hostname : str ) -> bytes :
114+ """Encode a hostname using the same IDNA 2008 encoding Trio uses.
115+
116+ If you want to know which exact hostname Trio will connect to, use this
117+ function.
118+ """
119+ # Given a unicode hostname, we want to do our own encoding using the idna
120+ # module, rather than letting Python do it. (Python will use the old IDNA
121+ # 2003 standard, and possibly get the wrong answer - see bpo-17305).
122+ # However, the idna module is picky, and will refuse to process some valid
123+ # hostname strings, like "::1". So if it's already ascii, we pass it
124+ # through; otherwise, we encode it via IDNA.
125+ try :
126+ return hostname .encode ("ascii" )
127+ except UnicodeEncodeError :
128+ # UTS-46 defines various normalizations; in particular, by default
129+ # idna.encode will error out if the hostname has Capital Letters
130+ # in it; with uts46=True it will lowercase them instead.
131+ return _idna .encode (hostname , uts46 = True )
132+
133+
113134################################################################
114135# Overrides
115136################################################################
@@ -252,21 +273,8 @@ def numeric_only_failure(exc: BaseException) -> bool:
252273 flags | _NUMERIC_ONLY ,
253274 )
254275 # That failed; it's a real hostname. We better use a thread.
255- #
256- # Also, it might be a unicode hostname, in which case we want to do our
257- # own encoding using the idna module, rather than letting Python do
258- # it. (Python will use the old IDNA 2003 standard, and possibly get the
259- # wrong answer - see bpo-17305). However, the idna module is picky, and
260- # will refuse to process some valid hostname strings, like "::1". So if
261- # it's already ascii, we pass it through; otherwise, we encode it to.
262276 if isinstance (host , str ):
263- try :
264- host = host .encode ("ascii" )
265- except UnicodeEncodeError :
266- # UTS-46 defines various normalizations; in particular, by default
267- # idna.encode will error out if the hostname has Capital Letters
268- # in it; with uts46=True it will lowercase them instead.
269- host = _idna .encode (host , uts46 = True )
277+ host = encode_hostname (host )
270278 hr = _resolver .get (None )
271279 if hr is not None :
272280 return await hr .getaddrinfo (host , port , family , type , proto , flags )
0 commit comments