|
| 1 | +import dataclasses |
| 2 | +import enum |
| 3 | +import ipaddress |
| 4 | +import re |
| 5 | +import typing |
| 6 | + |
| 7 | + |
| 8 | +class AddressType(enum.Enum): |
| 9 | + """ |
| 10 | + AddressType provides an abstracted identification of the determined kind of |
| 11 | + an address. The abstraction eliminates cohesion between the provided |
| 12 | + address identification functionality and its clients. |
| 13 | +
|
| 14 | + The type allows a client which may be configured with any of the supported |
| 15 | + types to identify which type was specified and perform necessary runtime |
| 16 | + handling. |
| 17 | +
|
| 18 | + An example would be a client which uses the values from its configuration |
| 19 | + to construct URLs and which is configured using raw IPv6 addreesses. The |
| 20 | + client needs to be able to determine the address type to know what |
| 21 | + processing (such as enclosing IPv6 addresses in []s) is needed to |
| 22 | + successfully utilize it. |
| 23 | + """ |
| 24 | + |
| 25 | + HOSTNAME = "hostname" |
| 26 | + IPv4 = "ipv4" |
| 27 | + IPv6 = "ipv6" |
| 28 | + UNKNOWN = "unknown" |
| 29 | + |
| 30 | + |
| 31 | +@dataclasses.dataclass(frozen=True) |
| 32 | +class AddressTypeResponse(object): |
| 33 | + """ |
| 34 | + AddressTypeResponse is returned from the classify address method describing |
| 35 | + the detected address including splitting it into address and port parts as |
| 36 | + appicable. |
| 37 | +
|
| 38 | + Strings are used for the address and port so as to minimize changes to |
| 39 | + existing code to facilitate use of the classification functionality |
| 40 | + provided. |
| 41 | + """ |
| 42 | + |
| 43 | + type: AddressType |
| 44 | + address: str |
| 45 | + port: typing.Optional[str] = None |
| 46 | + |
| 47 | + @property |
| 48 | + def ipv6_bracketed(self): |
| 49 | + """ |
| 50 | + IPv6 addresses are stored without brackets in the address field. |
| 51 | + If the type of this instance is AddressType.IPv6 the method will return |
| 52 | + the address enclosed in brackets. |
| 53 | + If the type is not AddressType.IPv6 it will return None. |
| 54 | + """ |
| 55 | + if self.type != AddressType.IPv6: |
| 56 | + return None |
| 57 | + return f"[{self.address}]" |
| 58 | + |
| 59 | + |
| 60 | +def _classify_base_address(address: str) -> AddressTypeResponse: |
| 61 | + """ |
| 62 | + Categorizes a given string as IPv4, IPv6, hostname, or unknown. |
| 63 | +
|
| 64 | + Args: |
| 65 | + address: The string to categorize. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + A value of AddressTypeResponse indicating the classified address. |
| 69 | + """ |
| 70 | + try: |
| 71 | + ipaddress.IPv4Address(address) |
| 72 | + return AddressTypeResponse(AddressType.IPv4, address) |
| 73 | + except ipaddress.AddressValueError: |
| 74 | + pass |
| 75 | + |
| 76 | + try: |
| 77 | + ipaddress.IPv6Address(address) |
| 78 | + return AddressTypeResponse(AddressType.IPv6, address) |
| 79 | + except ipaddress.AddressValueError: |
| 80 | + pass |
| 81 | + |
| 82 | + # Basic hostname check (can be expanded for more rigorous validation) |
| 83 | + # The original regex was generated via Gemini AI. |
| 84 | + # It was modified to require the first character be alphabetic to eliminate |
| 85 | + # a string composed of nothing but digits be recognized as a hostname. |
| 86 | + # |
| 87 | + # The regex may appear more complicated than it actually is. |
| 88 | + # |
| 89 | + # First you can ignore the "?:" which simply makes the group in which it |
| 90 | + # appears non-capturing. |
| 91 | + # |
| 92 | + # Second you can conceptually collapse the portions delineated by "{" and |
| 93 | + # "}" to "*". The bracketed portions simply put a limit on minimum and |
| 94 | + # maximum lengths of the preceding construct. |
| 95 | + # |
| 96 | + # With the two above changes you'll see that there's effectively only one |
| 97 | + # construct in the regex: |
| 98 | + # |
| 99 | + # [a-zA-Z]([a-zA-Z0-9-]*[a-zA-Z0-9])? |
| 100 | + # |
| 101 | + # It's second usage simply includes the requirement for a leading "." and |
| 102 | + # allows it to be specified zero or more times. |
| 103 | + if re.match(r"^[a-zA-Z](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", address): |
| 104 | + return AddressTypeResponse(AddressType.HOSTNAME, address) |
| 105 | + |
| 106 | + return AddressTypeResponse(AddressType.UNKNOWN, address) |
| 107 | + |
| 108 | + |
| 109 | +def _classify_address(address: str) -> AddressTypeResponse: |
| 110 | + """ |
| 111 | + Categorizes a given string as IPv4, IPv6, hostname, or unknown. |
| 112 | +
|
| 113 | + Args: |
| 114 | + address: The string to categorize. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + A value of AddressTypeResponse indicating the classified address. |
| 118 | + """ |
| 119 | + # We could be dealing with an IPv6 address wrapped in []. |
| 120 | + # If that is the case we want to classify the address itself. |
| 121 | + |
| 122 | + # Check that the address is at least two characters long. |
| 123 | + if (len(address) >= 2) and (address[0] == "[") and (address[-1] == "]"): |
| 124 | + response = _classify_base_address(address[1:-1]) |
| 125 | + |
| 126 | + # We only recognize an IPv6 address wrapped in []s as valid. |
| 127 | + # Regardless of the contents being identified if it is not an IPv6 |
| 128 | + # address we treat it as unknown. |
| 129 | + if response.type == AddressType.IPv6: |
| 130 | + return response |
| 131 | + return AddressTypeResponse(AddressType.UNKNOWN, address) |
| 132 | + |
| 133 | + return _classify_base_address(address) |
| 134 | + |
| 135 | + |
| 136 | +def classify_address(address: str) -> AddressTypeResponse: |
| 137 | + """ |
| 138 | + Categorizes a given string with optional ":<port>" suffix as IPv4, IPv6, |
| 139 | + hostname, or unknown. |
| 140 | +
|
| 141 | + Args: |
| 142 | + address: The string to categorize. |
| 143 | +
|
| 144 | + Returns: |
| 145 | + A value of AddressTypeResponse indicating the classified address. |
| 146 | + """ |
| 147 | + response = _classify_address(address) |
| 148 | + if response.type != AddressType.UNKNOWN: |
| 149 | + # A known type with no port. |
| 150 | + return response |
| 151 | + |
| 152 | + # Split into potential address and port and classify the address. |
| 153 | + (split_address, _, port) = address.rpartition(":") |
| 154 | + response = _classify_address(split_address) |
| 155 | + if response.type != AddressType.UNKNOWN: |
| 156 | + # A known type with a port. |
| 157 | + return AddressTypeResponse(response.type, response.address, port) |
| 158 | + |
| 159 | + # An unknown address type. |
| 160 | + return AddressTypeResponse(AddressType.UNKNOWN, address) |
0 commit comments