Skip to content

Commit

Permalink
Fix: fix the code about handling getaddrinfo when disable ipv6 in
Browse files Browse the repository at this point in the history
CPython and enable ipv6 in system.
Related to #5901; `getaddrinfo` will return an `(int, bytes)` tuple, if
CPython could not handle the address family. It will cause a index out
of range error in aiohttp.
  • Loading branch information
Hanaasagi committed Aug 1, 2021
1 parent 60f5727 commit 23da79f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGES/5901.bugfix
@@ -0,0 +1,4 @@
Fix the error in handling the return value of `getaddrinfo`.
`getaddrinfo` will return an `(int, bytes)` tuple, if CPython could not handle the address family.
It will cause a index out of range error in aiohttp. For example, if user compile CPython with
`--disable-ipv6` option but his system enable the ipv6.
4 changes: 3 additions & 1 deletion aiohttp/resolver.py
Expand Up @@ -37,7 +37,9 @@ async def resolve(

hosts = []
for family, _, proto, _, address in infos:
if family == socket.AF_INET6 and address[3]: # type: ignore[misc]
if family == socket.AF_INET6:
if not (socket.has_ipv6 and address[3]): # type: ignore[misc]
continue
# This is essential for link-local IPv6 addresses.
# LL IPv6 is a VERY rare case. Strictly speaking, we should use
# getnameinfo() unconditionally, but performance makes sense.
Expand Down
24 changes: 24 additions & 0 deletions tests/test_resolver.py
Expand Up @@ -119,6 +119,30 @@ async def test_threaded_negative_lookup() -> None:
await resolver.resolve("doesnotexist.bla")


async def test_threaded_negative_lookup_with_unknown_result() -> None:
loop = Mock()

# If compile CPython with `--disable-ipv6` option,
# we will get an (int, bytes) tuple, instead of a Exception.
async def unknown_addrinfo(*args: Any, **kwargs: Any) -> List[Any]:
return [
(
socket.AF_INET6,
socket.SOCK_STREAM,
6,
"",
(10, b"\x01\xbb\x00\x00\x00\x00*\x04NB\x00\x1a\x00\x00"),
)
]

loop.getaddrinfo = unknown_addrinfo
resolver = ThreadedResolver()
resolver._loop = loop
with patch("socket.has_ipv6", False):
res = await resolver.resolve("www.python.org")
assert len(res) == 0


async def test_close_for_threaded_resolver(loop: Any) -> None:
resolver = ThreadedResolver()
await resolver.close()
Expand Down

0 comments on commit 23da79f

Please sign in to comment.