Debian Codegraph @

dns/ipv6.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2003-2017 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 """IPv6 helper functions."""
19
20 import binascii
21 import re
22 from typing import List
23
24 import dns.exception
25 import dns.ipv4
26
27 _leading_zero = re.compile(r"0+([0-9a-f]+)")
28
29
30 def inet_ntoa(address: bytes) -> str:
31 """Convert an IPv6 address in binary form to text form.
32
33 *address*, a ``bytes``, the IPv6 address in binary form.
34
35 Raises ``ValueError`` if the address isn't 16 bytes long.
36 Returns a ``str``.
37 """
38
39 if len(address) != 16:
40 raise ValueError("IPv6 addresses are 16 bytes long")
41 hex = binascii.hexlify(address)
42 chunks = []
43 i = 0
44 l = len(hex)
45 while i < l:
46 chunk = hex[i : i + 4].decode()
47 # strip leading zeros. we do this with an re instead of
48 # with lstrip() because lstrip() didn't support chars until
49 # python 2.2.2
50 m = _leading_zero.match(chunk)
51 if m is not None:
52 chunk = m.group(1)
53 chunks.append(chunk)
54 i += 4
55 #
56 # Compress the longest subsequence of 0-value chunks to ::
57 #
58 best_start = 0
59 best_len = 0
60 start = -1
61 last_was_zero = False
62 for i in range(8):
63 if chunks[i] != "0":
64 if last_was_zero:
65 end = i
66 current_len = end - start
67 if current_len > best_len:
68 best_start = start
69 best_len = current_len
70 last_was_zero = False
71 elif not last_was_zero:
72 start = i
73 last_was_zero = True
74 if last_was_zero:
75 end = 8
76 current_len = end - start
77 if current_len > best_len:
78 best_start = start
79 best_len = current_len
80 if best_len > 1:
81 if best_start == 0 and (best_len == 6 or best_len == 5 and chunks[5] == "ffff"):
82 # We have an embedded IPv4 address
83 if best_len == 6:
84 prefix = "::"
85 else:
86 prefix = "::ffff:"
87 thex = prefix + dns.ipv4.inet_ntoa(address[12:])
88 else:
89 thex = (
90 ":".join(chunks[:best_start])
91 + "::"
92 + ":".join(chunks[best_start + best_len :])
93 )
94 else:
95 thex = ":".join(chunks)
96 return thex
97
98
99 _v4_ending = re.compile(rb"(.*):(\d+\.\d+\.\d+\.\d+)$")
100 _colon_colon_start = re.compile(rb"::.*")
101 _colon_colon_end = re.compile(rb".*::$")
102
103
104 def inet_aton(text: str | bytes, ignore_scope: bool = False) -> bytes:
105 """Convert an IPv6 address in text form to binary form.
106
107 *text*, a ``str`` or ``bytes``, the IPv6 address in textual form.
108
109 *ignore_scope*, a ``bool``. If ``True``, a scope will be ignored.
110 If ``False``, the default, it is an error for a scope to be present.
111
112 Returns a ``bytes``.
113 """
114
115 #
116 # Our aim here is not something fast; we just want something that works.
117 #
118 if not isinstance(text, bytes):
119 btext = text.encode()
120 else:
121 btext = text
122
123 if ignore_scope:
124 parts = btext.split(b"%")
125 l = len(parts)
126 if l == 2:
127 btext = parts[0]
128 elif l > 2:
129 raise dns.exception.SyntaxError
130
131 if btext == b"":
132 raise dns.exception.SyntaxError
133 elif btext.endswith(b":") and not btext.endswith(b"::"):
134 raise dns.exception.SyntaxError
135 elif btext.startswith(b":") and not btext.startswith(b"::"):
136 raise dns.exception.SyntaxError
137 elif btext == b"::":
138 btext = b"0::"
139 #
140 # Get rid of the icky dot-quad syntax if we have it.
141 #
142 m = _v4_ending.match(btext)
143 if m is not None:
144 b = dns.ipv4.inet_aton(m.group(2))
145 btext = (
146 f"{m.group(1).decode()}:{b[0]:02x}{b[1]:02x}:{b[2]:02x}{b[3]:02x}"
147 ).encode()
148 #
149 # Try to turn '::<whatever>' into ':<whatever>'; if no match try to
150 # turn '<whatever>::' into '<whatever>:'
151 #
152 m = _colon_colon_start.match(btext)
153 if m is not None:
154 btext = btext[1:]
155 else:
156 m = _colon_colon_end.match(btext)
157 if m is not None:
158 btext = btext[:-1]
159 #
160 # Now canonicalize into 8 chunks of 4 hex digits each
161 #
162 chunks = btext.split(b":")
163 l = len(chunks)
164 if l > 8:
165 raise dns.exception.SyntaxError
166 seen_empty = False
167 canonical: List[bytes] = []
168 for c in chunks:
169 if c == b"":
170 if seen_empty:
171 raise dns.exception.SyntaxError
172 seen_empty = True
173 for _ in range(0, 8 - l + 1):
174 canonical.append(b"0000")
175 else:
176 lc = len(c)
177 if lc > 4:
178 raise dns.exception.SyntaxError
179 if lc != 4:
180 c = (b"0" * (4 - lc)) + c
181 canonical.append(c)
182 if l < 8 and not seen_empty:
183 raise dns.exception.SyntaxError
184 btext = b"".join(canonical)
185
186 #
187 # Finally we can go to binary.
188 #
189 try:
190 return binascii.unhexlify(btext)
191 except (binascii.Error, TypeError):
192 raise dns.exception.SyntaxError
193
194
195 _mapped_prefix = b"\x00" * 10 + b"\xff\xff"
196
197
198 def is_mapped(address: bytes) -> bool:
199 """Is the specified address a mapped IPv4 address?
200
201 *address*, a ``bytes`` is an IPv6 address in binary form.
202
203 Returns a ``bool``.
204 """
205
206 return address.startswith(_mapped_prefix)
207
208
209 def canonicalize(text: str | bytes) -> str:
210 """Verify that *address* is a valid text form IPv6 address and return its
211 canonical text form. Addresses with scopes are rejected.
212
213 *text*, a ``str`` or ``bytes``, the IPv6 address in textual form.
214
215 Raises ``dns.exception.SyntaxError`` if the text is not valid.
216 """
217 return inet_ntoa(inet_aton(text))