1"""Utility functions for aiohappyeyeballs."""
2
3import ipaddress
4import socket
5
6from .types import AddrInfoType
7
8
9def addr_to_addr_infos(
10 addr: tuple[str, int, int, int] | tuple[str, int, int] | tuple[str, int] | None,
11) -> list[AddrInfoType] | None:
12 """Convert an address tuple to a list of addr_info tuples."""
13 if addr is None:
14 return None
15 host = addr[0]
16 port = addr[1]
17 is_ipv6 = ":" in host
18 if is_ipv6:
19 flowinfo = 0
20 scopeid = 0
21 addr_len = len(addr)
22 if addr_len >= 4:
23 scopeid = addr[3] # type: ignore[misc]
24 if addr_len >= 3:
25 flowinfo = addr[2] # type: ignore[misc]
26 addr = (host, port, flowinfo, scopeid)
27 family = socket.AF_INET6
28 else:
29 addr = (host, port)
30 family = socket.AF_INET
31 return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)]
32
33
34def pop_addr_infos_interleave(
35 addr_infos: list[AddrInfoType], interleave: int | None = None
36) -> None:
37 """
38 Pop addr_info from the list of addr_infos by family up to interleave times.
39
40 The interleave parameter is used to know how many addr_infos for
41 each family should be popped of the top of the list.
42 """
43 if interleave is None:
44 interleave = 1
45 seen: dict[int, int] = {}
46 kept: list[AddrInfoType] = []
47 for addr_info in addr_infos:
48 family = addr_info[0]
49 count = seen.get(family, 0)
50 if count >= interleave:
51 kept.append(addr_info)
52 seen[family] = count + 1
53 addr_infos[:] = kept
54
55
56def _addr_tuple_to_ip_address(
57 addr: tuple[str, int] | tuple[str, int, int, int],
58) -> tuple[ipaddress.IPv4Address, int] | tuple[ipaddress.IPv6Address, int, int, int]:
59 """Convert an address tuple to an IPv4Address."""
60 return (ipaddress.ip_address(addr[0]), *addr[1:])
61
62
63def remove_addr_infos(
64 addr_infos: list[AddrInfoType],
65 addr: tuple[str, int] | tuple[str, int, int, int],
66) -> None:
67 """
68 Remove an address from the list of addr_infos.
69
70 The addr value is typically the return value of
71 sock.getpeername().
72 """
73 kept = [ai for ai in addr_infos if ai[-1] != addr]
74 if len(kept) == len(addr_infos):
75 # Slow path in case addr is formatted differently
76 match_addr = _addr_tuple_to_ip_address(addr)
77 kept = [
78 ai for ai in addr_infos if _addr_tuple_to_ip_address(ai[-1]) != match_addr
79 ]
80 if len(kept) == len(addr_infos):
81 raise ValueError(f"Address {addr} not found in addr_infos")
82 addr_infos[:] = kept