ipv6.py 5.9 KB

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