ttl.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. """DNS TTL conversion."""
  17. import dns.exception
  18. # Technically TTLs are supposed to be between 0 and 2**31 - 1, with values
  19. # greater than that interpreted as 0, but we do not impose this policy here
  20. # as values > 2**31 - 1 occur in real world data.
  21. #
  22. # We leave it to applications to impose tighter bounds if desired.
  23. MAX_TTL = 2**32 - 1
  24. class BadTTL(dns.exception.SyntaxError):
  25. """DNS TTL value is not well-formed."""
  26. def from_text(text):
  27. """Convert the text form of a TTL to an integer.
  28. The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
  29. *text*, a ``str``, the textual TTL.
  30. Raises ``dns.ttl.BadTTL`` if the TTL is not well-formed.
  31. Returns an ``int``.
  32. """
  33. if text.isdigit():
  34. total = int(text)
  35. elif len(text) == 0:
  36. raise BadTTL
  37. else:
  38. total = 0
  39. current = 0
  40. need_digit = True
  41. for c in text:
  42. if c.isdigit():
  43. current *= 10
  44. current += int(c)
  45. need_digit = False
  46. else:
  47. if need_digit:
  48. raise BadTTL
  49. c = c.lower()
  50. if c == 'w':
  51. total += current * 604800
  52. elif c == 'd':
  53. total += current * 86400
  54. elif c == 'h':
  55. total += current * 3600
  56. elif c == 'm':
  57. total += current * 60
  58. elif c == 's':
  59. total += current
  60. else:
  61. raise BadTTL("unknown unit '%s'" % c)
  62. current = 0
  63. need_digit = True
  64. if not current == 0:
  65. raise BadTTL("trailing integer")
  66. if total < 0 or total > MAX_TTL:
  67. raise BadTTL("TTL should be between 0 and 2**32 - 1 (inclusive)")
  68. return total
  69. def make(value):
  70. if isinstance(value, int):
  71. return value
  72. elif isinstance(value, str):
  73. return dns.ttl.from_text(value)
  74. else:
  75. raise ValueError('cannot convert value to TTL')