Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/dns/ipv6.py: 13%

115 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-02 06:07 +0000

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 

20import binascii 

21import re 

22from typing import List, Union 

23 

24import dns.exception 

25import dns.ipv4 

26 

27_leading_zero = re.compile(r"0+([0-9a-f]+)") 

28 

29 

30def 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 

104def inet_aton(text: Union[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 "{}:{:02x}{:02x}:{:02x}{:02x}".format( 

147 m.group(1).decode(), b[0], b[1], b[2], b[3] 

148 ) 

149 ).encode() 

150 # 

151 # Try to turn '::<whatever>' into ':<whatever>'; if no match try to 

152 # turn '<whatever>::' into '<whatever>:' 

153 # 

154 m = _colon_colon_start.match(btext) 

155 if m is not None: 

156 btext = btext[1:] 

157 else: 

158 m = _colon_colon_end.match(btext) 

159 if m is not None: 

160 btext = btext[:-1] 

161 # 

162 # Now canonicalize into 8 chunks of 4 hex digits each 

163 # 

164 chunks = btext.split(b":") 

165 l = len(chunks) 

166 if l > 8: 

167 raise dns.exception.SyntaxError 

168 seen_empty = False 

169 canonical: List[bytes] = [] 

170 for c in chunks: 

171 if c == b"": 

172 if seen_empty: 

173 raise dns.exception.SyntaxError 

174 seen_empty = True 

175 for _ in range(0, 8 - l + 1): 

176 canonical.append(b"0000") 

177 else: 

178 lc = len(c) 

179 if lc > 4: 

180 raise dns.exception.SyntaxError 

181 if lc != 4: 

182 c = (b"0" * (4 - lc)) + c 

183 canonical.append(c) 

184 if l < 8 and not seen_empty: 

185 raise dns.exception.SyntaxError 

186 btext = b"".join(canonical) 

187 

188 # 

189 # Finally we can go to binary. 

190 # 

191 try: 

192 return binascii.unhexlify(btext) 

193 except (binascii.Error, TypeError): 

194 raise dns.exception.SyntaxError 

195 

196 

197_mapped_prefix = b"\x00" * 10 + b"\xff\xff" 

198 

199 

200def is_mapped(address: bytes) -> bool: 

201 """Is the specified address a mapped IPv4 address? 

202 

203 *address*, a ``bytes`` is an IPv6 address in binary form. 

204 

205 Returns a ``bool``. 

206 """ 

207 

208 return address.startswith(_mapped_prefix) 

209 

210 

211def canonicalize(text: Union[str, bytes]) -> str: 

212 """Verify that *address* is a valid text form IPv6 address and return its 

213 canonical text form. Addresses with scopes are rejected. 

214 

215 *text*, a ``str`` or ``bytes``, the IPv6 address in textual form. 

216 

217 Raises ``dns.exception.SyntaxError`` if the text is not valid. 

218 """ 

219 return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text))