|
| 1 | +"""Utility functions for multiaddr resolution.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from ..exceptions import RecursionLimitError |
| 8 | +from ..multiaddr import Multiaddr |
| 9 | +from ..protocols import P_DNS, P_DNS4, P_DNS6, P_DNSADDR |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from .base import Resolver |
| 13 | + |
| 14 | +__all__ = ["addr_len", "fqdn", "is_fqdn", "matches", "offset_addr", "resolve_all"] |
| 15 | + |
| 16 | +_DNS_PROTOCOLS = frozenset({P_DNS, P_DNS4, P_DNS6, P_DNSADDR}) |
| 17 | + |
| 18 | + |
| 19 | +def is_fqdn(s: str) -> bool: |
| 20 | + """Check if string is a fully qualified domain name (ends with unescaped dot). |
| 21 | +
|
| 22 | + Args: |
| 23 | + s: The domain name string to check. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + ``True`` if *s* ends with an unescaped ``'.'``, ``False`` otherwise. |
| 27 | + """ |
| 28 | + if not s: |
| 29 | + return False |
| 30 | + # Count trailing backslashes before the final character |
| 31 | + if s[-1] != ".": |
| 32 | + return False |
| 33 | + # Check if the trailing dot is escaped |
| 34 | + num_backslashes = 0 |
| 35 | + for i in range(len(s) - 2, -1, -1): |
| 36 | + if s[i] == "\\": |
| 37 | + num_backslashes += 1 |
| 38 | + else: |
| 39 | + break |
| 40 | + # Odd number of backslashes means the dot is escaped |
| 41 | + return num_backslashes % 2 == 0 |
| 42 | + |
| 43 | + |
| 44 | +def fqdn(s: str) -> str: |
| 45 | + """Append a trailing dot to *s* if it is not already a FQDN. |
| 46 | +
|
| 47 | + Args: |
| 48 | + s: The domain name string. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + The domain name with a trailing ``'.'`` appended if needed. |
| 52 | +
|
| 53 | + Example:: |
| 54 | +
|
| 55 | + >>> fqdn("example.com") |
| 56 | + 'example.com.' |
| 57 | + >>> fqdn("example.com.") |
| 58 | + 'example.com.' |
| 59 | + """ |
| 60 | + if is_fqdn(s): |
| 61 | + return s |
| 62 | + return s + "." |
| 63 | + |
| 64 | + |
| 65 | +def addr_len(maddr: Multiaddr) -> int: |
| 66 | + """Count the number of protocol components in a multiaddr. |
| 67 | +
|
| 68 | + Args: |
| 69 | + maddr: The multiaddr to measure. |
| 70 | +
|
| 71 | + Returns: |
| 72 | + The number of protocol components. |
| 73 | + """ |
| 74 | + return len(list(maddr.protocols())) |
| 75 | + |
| 76 | + |
| 77 | +def offset_addr(maddr: Multiaddr, n: int) -> Multiaddr: |
| 78 | + """Return a new multiaddr with the first *n* protocol components removed. |
| 79 | +
|
| 80 | + Args: |
| 81 | + maddr: The source multiaddr. |
| 82 | + n: Number of leading components to skip. Must be >= 0. |
| 83 | +
|
| 84 | + Returns: |
| 85 | + A new :class:`~multiaddr.Multiaddr` without the first *n* components, |
| 86 | + or ``Multiaddr("/")`` if *n* >= the total number of components. |
| 87 | +
|
| 88 | + Raises: |
| 89 | + ValueError: If *n* is negative. |
| 90 | + """ |
| 91 | + if n < 0: |
| 92 | + raise ValueError(f"offset must be non-negative, got {n}") |
| 93 | + parts = maddr.split(n) |
| 94 | + if len(parts) <= n: |
| 95 | + return Multiaddr("/") |
| 96 | + return parts[n] |
| 97 | + |
| 98 | + |
| 99 | +def matches(maddr: Multiaddr) -> bool: |
| 100 | + """Check if a multiaddr contains any DNS protocol component. |
| 101 | +
|
| 102 | + Args: |
| 103 | + maddr: The multiaddr to inspect. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + ``True`` if *maddr* contains a ``dns``, ``dns4``, ``dns6``, or |
| 107 | + ``dnsaddr`` component. |
| 108 | +
|
| 109 | + Example:: |
| 110 | +
|
| 111 | + >>> matches(Multiaddr("/dns4/example.com/tcp/80")) |
| 112 | + True |
| 113 | + >>> matches(Multiaddr("/ip4/127.0.0.1/tcp/80")) |
| 114 | + False |
| 115 | + """ |
| 116 | + return any(p.code in _DNS_PROTOCOLS for p in maddr.protocols()) |
| 117 | + |
| 118 | + |
| 119 | +async def resolve_all( |
| 120 | + resolver: Resolver, |
| 121 | + maddr: Multiaddr, |
| 122 | + *, |
| 123 | + max_iterations: int = 32, |
| 124 | +) -> list[Multiaddr]: |
| 125 | + """Resolve all DNS components in a multiaddr iteratively. |
| 126 | +
|
| 127 | + Calls ``resolver.resolve()`` in a loop until every returned address is |
| 128 | + free of DNS components. |
| 129 | +
|
| 130 | + Args: |
| 131 | + resolver: A resolver instance implementing an async ``resolve()`` method. |
| 132 | + maddr: The multiaddr to resolve. |
| 133 | + max_iterations: Safety limit on resolution rounds to prevent infinite |
| 134 | + loops (default ``32``). |
| 135 | +
|
| 136 | + Returns: |
| 137 | + A list of fully-resolved :class:`~multiaddr.Multiaddr` instances. |
| 138 | +
|
| 139 | + Raises: |
| 140 | + RecursionLimitError: If DNS components remain after *max_iterations* |
| 141 | + rounds. |
| 142 | +
|
| 143 | + Example:: |
| 144 | +
|
| 145 | + >>> import trio |
| 146 | + >>> result = trio.run(resolve_all, my_resolver, Multiaddr("/dns4/example.com/tcp/80")) |
| 147 | + """ |
| 148 | + queue = [maddr] |
| 149 | + resolved: list[Multiaddr] = [] |
| 150 | + |
| 151 | + for _ in range(max_iterations): |
| 152 | + if not queue: |
| 153 | + break |
| 154 | + next_queue: list[Multiaddr] = [] |
| 155 | + for addr in queue: |
| 156 | + if not matches(addr): |
| 157 | + resolved.append(addr) |
| 158 | + continue |
| 159 | + results = await resolver.resolve(addr) |
| 160 | + for r in results: |
| 161 | + if matches(r): |
| 162 | + next_queue.append(r) |
| 163 | + else: |
| 164 | + resolved.append(r) |
| 165 | + queue = next_queue |
| 166 | + |
| 167 | + if queue: |
| 168 | + raise RecursionLimitError( |
| 169 | + f"resolve_all exceeded {max_iterations} iterations; " |
| 170 | + f"{len(queue)} addresses still contain DNS components" |
| 171 | + ) |
| 172 | + |
| 173 | + return resolved |
0 commit comments