Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_rfc1982.py 8.9KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # -*- test-case-name: twisted.names.test.test_rfc1982 -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Utilities for handling RFC1982 Serial Number Arithmetic.
  6. @see: U{http://tools.ietf.org/html/rfc1982}
  7. @var RFC4034_TIME_FORMAT: RRSIG Time field presentation format. The Signature
  8. Expiration Time and Inception Time field values MUST be represented either
  9. as an unsigned decimal integer indicating seconds since 1 January 1970
  10. 00:00:00 UTC, or in the form YYYYMMDDHHmmSS in UTC. See U{RRSIG Presentation
  11. Format<https://tools.ietf.org/html/rfc4034#section-3.2>}
  12. """
  13. import calendar
  14. from datetime import datetime, timedelta
  15. from twisted.python.compat import nativeString
  16. from twisted.python.util import FancyStrMixin
  17. RFC4034_TIME_FORMAT = "%Y%m%d%H%M%S"
  18. class SerialNumber(FancyStrMixin):
  19. """
  20. An RFC1982 Serial Number.
  21. This class implements RFC1982 DNS Serial Number Arithmetic.
  22. SNA is used in DNS and specifically in DNSSEC as defined in RFC4034 in the
  23. DNSSEC Signature Expiration and Inception Fields.
  24. @see: U{https://tools.ietf.org/html/rfc1982}
  25. @see: U{https://tools.ietf.org/html/rfc4034}
  26. @ivar _serialBits: See C{serialBits} of L{__init__}.
  27. @ivar _number: See C{number} of L{__init__}.
  28. @ivar _modulo: The value at which wrapping will occur.
  29. @ivar _halfRing: Half C{_modulo}. If another L{SerialNumber} value is larger
  30. than this, it would lead to a wrapped value which is larger than the
  31. first and comparisons are therefore ambiguous.
  32. @ivar _maxAdd: Half C{_modulo} plus 1. If another L{SerialNumber} value is
  33. larger than this, it would lead to a wrapped value which is larger than
  34. the first. Comparisons with the original value would therefore be
  35. ambiguous.
  36. """
  37. showAttributes = (
  38. ("_number", "number", "%d"),
  39. ("_serialBits", "serialBits", "%d"),
  40. )
  41. def __init__(self, number, serialBits=32):
  42. """
  43. Construct an L{SerialNumber} instance.
  44. @param number: An L{int} which will be stored as the modulo
  45. C{number % 2 ^ serialBits}
  46. @type number: L{int}
  47. @param serialBits: The size of the serial number space. The power of two
  48. which results in one larger than the largest integer corresponding
  49. to a serial number value.
  50. @type serialBits: L{int}
  51. """
  52. self._serialBits = serialBits
  53. self._modulo = 2 ** serialBits
  54. self._halfRing = 2 ** (serialBits - 1)
  55. self._maxAdd = 2 ** (serialBits - 1) - 1
  56. self._number = int(number) % self._modulo
  57. def _convertOther(self, other: object) -> "SerialNumber":
  58. """
  59. Check that a foreign object is suitable for use in the comparison or
  60. arithmetic magic methods of this L{SerialNumber} instance. Raise
  61. L{TypeError} if not.
  62. @param other: The foreign L{object} to be checked.
  63. @return: C{other} after compatibility checks and possible coercion.
  64. @raise TypeError: If C{other} is not compatible.
  65. """
  66. if not isinstance(other, SerialNumber):
  67. raise TypeError(f"cannot compare or combine {self!r} and {other!r}")
  68. if self._serialBits != other._serialBits:
  69. raise TypeError(
  70. "cannot compare or combine SerialNumber instances with "
  71. "different serialBits. %r and %r" % (self, other)
  72. )
  73. return other
  74. def __str__(self) -> str:
  75. """
  76. Return a string representation of this L{SerialNumber} instance.
  77. @rtype: L{nativeString}
  78. """
  79. return nativeString("%d" % (self._number,))
  80. def __int__(self):
  81. """
  82. @return: The integer value of this L{SerialNumber} instance.
  83. @rtype: L{int}
  84. """
  85. return self._number
  86. def __eq__(self, other: object) -> bool:
  87. """
  88. Allow rich equality comparison with another L{SerialNumber} instance.
  89. """
  90. try:
  91. other = self._convertOther(other)
  92. except TypeError:
  93. return NotImplemented
  94. return other._number == self._number
  95. def __lt__(self, other: object) -> bool:
  96. """
  97. Allow I{less than} comparison with another L{SerialNumber} instance.
  98. """
  99. try:
  100. other = self._convertOther(other)
  101. except TypeError:
  102. return NotImplemented
  103. return (
  104. self._number < other._number
  105. and (other._number - self._number) < self._halfRing
  106. ) or (
  107. self._number > other._number
  108. and (self._number - other._number) > self._halfRing
  109. )
  110. def __gt__(self, other: object) -> bool:
  111. """
  112. Allow I{greater than} comparison with another L{SerialNumber} instance.
  113. """
  114. try:
  115. other = self._convertOther(other)
  116. except TypeError:
  117. return NotImplemented
  118. return (
  119. self._number < other._number
  120. and (other._number - self._number) > self._halfRing
  121. ) or (
  122. self._number > other._number
  123. and (self._number - other._number) < self._halfRing
  124. )
  125. def __le__(self, other: object) -> bool:
  126. """
  127. Allow I{less than or equal} comparison with another L{SerialNumber}
  128. instance.
  129. """
  130. try:
  131. other = self._convertOther(other)
  132. except TypeError:
  133. return NotImplemented
  134. return self == other or self < other
  135. def __ge__(self, other: object) -> bool:
  136. """
  137. Allow I{greater than or equal} comparison with another L{SerialNumber}
  138. instance.
  139. """
  140. try:
  141. other = self._convertOther(other)
  142. except TypeError:
  143. return NotImplemented
  144. return self == other or self > other
  145. def __add__(self, other: object) -> "SerialNumber":
  146. """
  147. Allow I{addition} with another L{SerialNumber} instance.
  148. Serial numbers may be incremented by the addition of a positive
  149. integer n, where n is taken from the range of integers
  150. [0 .. (2^(SERIAL_BITS - 1) - 1)]. For a sequence number s, the
  151. result of such an addition, s', is defined as
  152. s' = (s + n) modulo (2 ^ SERIAL_BITS)
  153. where the addition and modulus operations here act upon values that are
  154. non-negative values of unbounded size in the usual ways of integer
  155. arithmetic.
  156. Addition of a value outside the range
  157. [0 .. (2^(SERIAL_BITS - 1) - 1)] is undefined.
  158. @see: U{http://tools.ietf.org/html/rfc1982#section-3.1}
  159. @raise ArithmeticError: If C{other} is more than C{_maxAdd}
  160. ie more than half the maximum value of this serial number.
  161. """
  162. try:
  163. other = self._convertOther(other)
  164. except TypeError:
  165. return NotImplemented
  166. if other._number <= self._maxAdd:
  167. return SerialNumber(
  168. (self._number + other._number) % self._modulo,
  169. serialBits=self._serialBits,
  170. )
  171. else:
  172. raise ArithmeticError(
  173. "value %r outside the range 0 .. %r"
  174. % (
  175. other._number,
  176. self._maxAdd,
  177. )
  178. )
  179. def __hash__(self):
  180. """
  181. Allow L{SerialNumber} instances to be hashed for use as L{dict} keys.
  182. @rtype: L{int}
  183. """
  184. return hash(self._number)
  185. @classmethod
  186. def fromRFC4034DateString(cls, utcDateString):
  187. """
  188. Create an L{SerialNumber} instance from a date string in format
  189. 'YYYYMMDDHHMMSS' described in U{RFC4034
  190. 3.2<https://tools.ietf.org/html/rfc4034#section-3.2>}.
  191. The L{SerialNumber} instance stores the date as a 32bit UNIX timestamp.
  192. @see: U{https://tools.ietf.org/html/rfc4034#section-3.1.5}
  193. @param utcDateString: A UTC date/time string of format I{YYMMDDhhmmss}
  194. which will be converted to seconds since the UNIX epoch.
  195. @type utcDateString: L{unicode}
  196. @return: An L{SerialNumber} instance containing the supplied date as a
  197. 32bit UNIX timestamp.
  198. """
  199. parsedDate = datetime.strptime(utcDateString, RFC4034_TIME_FORMAT)
  200. secondsSinceEpoch = calendar.timegm(parsedDate.utctimetuple())
  201. return cls(secondsSinceEpoch, serialBits=32)
  202. def toRFC4034DateString(self):
  203. """
  204. Calculate a date by treating the current L{SerialNumber} value as a UNIX
  205. timestamp and return a date string in the format described in
  206. U{RFC4034 3.2<https://tools.ietf.org/html/rfc4034#section-3.2>}.
  207. @return: The date string.
  208. """
  209. # Can't use datetime.utcfromtimestamp, because it seems to overflow the
  210. # signed 32bit int used in the underlying C library. SNA is unsigned
  211. # and capable of handling all timestamps up to 2**32.
  212. d = datetime(1970, 1, 1) + timedelta(seconds=self._number)
  213. return nativeString(d.strftime(RFC4034_TIME_FORMAT))
  214. __all__ = ["SerialNumber"]